minor enhancements of session 2

pull/10/head
Kenneth C. Kleissl 2019-12-02 22:30:12 +01:00
parent 8d2fb458c6
commit e2f26787e5
1 changed files with 100 additions and 49 deletions

View File

@ -294,13 +294,12 @@
"\n",
"Data structures are constructs that can contain one or more variables. They are containers that can store a lot of data into a single entity.\n",
"\n",
"**Python's four basic data structures are**\n",
"**Python's four basic data structures are:**\n",
" * Lists\n",
" * Dictionaries\n",
" * Tuples\n",
" * Sets\n",
"\n",
" \n",
"## Lists \n",
"Lists are defined by square brackets `[]` with elements separated by commas. They can have elements of any data type.\n",
"\n",
@ -309,7 +308,6 @@
"### List syntax \n",
"<code> L = [item_1, item_2, ..., item_n] </code>\n",
"\n",
"\n",
"### Mutability\n",
"Lists are ***mutable***. They can be changed after creation.\n",
"\n",
@ -338,13 +336,11 @@
"metadata": {},
"source": [
"## Dictionaries\n",
"Dictionaries have key/value pairs which are enclosed in curly brackets`{}`. A value can be fetched by querying the corresponding key. \n",
"This can for some problems be much easier than having two lists that relate to each other by index.\n",
"Dictionaries have key/value pairs which are enclosed in curly brackets`{}`. A value can be fetched by querying the corresponding key. Refering the data via logically named keys instead of list indexes makes the code more readable.\n",
"\n",
"### Dictionary syntax \n",
" \n",
"<code> d = {key1: value1, key2: value2, ..., key_n, value_n} </code>\n",
"\n",
"<code> d = {key1: value1, key2: value2, ..., key_n: value_n} </code>\n",
" \n",
"Note that values can be of any data type like floats, strings etc., but they can also be lists or other data structures.\n",
"\n",
@ -674,12 +670,12 @@
"## Indexing \n",
"When elements are put into a sequences (strings, lists, tuples etc.), the individual elements gets an index assgined to them. This enables each element to be extracted. \n",
" \n",
"> **Indexing in Python** starts from `0`, while the negative index starts from `-1`.\n",
"> **Indexing in Python starts from `0`**, while the last element can be access via index `-1`.\n",
"\n",
"![image.png](attachment:image.png)\n",
"\n",
"### Use square brackets `[]`\n",
"To extract an element by indexing, use sqaure brackets `[]`. This is the general way and works for all sequences. Strings, lists and tuples are all sequences."
"### Use square brackets `[]` to access elements\n",
"To extract an element by indexing, use sqaure brackets `[]`. This is the general way and works for all sequences."
]
},
{
@ -722,7 +718,7 @@
}
],
"source": [
"# Extract second to last element\n",
"# Extract second last element\n",
"example_list[-2]"
]
},
@ -790,7 +786,7 @@
"metadata": {},
"source": [
"### Extracting values from dictionaries\n",
"Dictionaries differ from data structures like strings, lists and tuples since **they do not have an index**. Instead, a value is extracted by indexing the corresponding key:"
"Dictionaries differ from data structures like strings, lists and tuples since **they do not have an index**. Instead, a value is extracted by using the corresponding key:"
]
},
{
@ -818,8 +814,6 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that this means that **keys in a dictionary must be unique!**\n",
"\n",
"See demonstation below, where the key `'a'` is defined twice. The second defintion overwrites the first one."
]
},
@ -858,10 +852,10 @@
"\n",
"> **When slicing**, the stop point of the slice is not included.\n",
"\n",
"Examples is this section are shown for lists, but the same concept works for strings and tuples. Set objects do not support indexing/slicing since they are unordered, and dictionaries cannot be sliced either as they have the key functionality instead.\n",
"Examples in this section are shown for lists, but the same concept works for strings and tuples. Set objects do not support indexing/slicing since they are unordered, and dictionaries cannot be sliced either as they have the key functionality instead.\n",
"\n",
"### Common slicing operations \n",
"Suppose a list `n` has been defined along with two integers `n` and `n`:\n",
"Suppose a list `n` has been defined along with two integers `start` and `stop`:\n",
"\n",
"\n",
"```python\n",
@ -886,8 +880,6 @@
"# Copy of the whole list (alternative: list.copy())\n",
"n[:] -> [3, 25, 83, 31, 14, 47, 1, 23, 57] \n",
"```\n",
"The same concept works for other sequence like strings and tuples.\n",
"\n",
"\n",
"As seen, the last one creates a copy. This can be useful when working with mutable objects. For example for copying a list to mutate the copy while keeping the original list unchanged.\n",
"\n",
@ -1197,8 +1189,8 @@
],
"source": [
"# Printing numbers from 0-5\n",
"for i in [0, 1, 2, 3, 4, 5]:\n",
" print(i)"
"for num in [0, 1, 2, 3, 4, 5]:\n",
" print(num))"
]
},
{
@ -1238,9 +1230,9 @@
}
],
"source": [
"# Printing numbers from 0-5\n",
"for i in range(6):\n",
" print(i**2)"
"# Printing square of numbers from 0-5\n",
"for num in range(6):\n",
" print(num**2)"
]
},
{
@ -1252,17 +1244,13 @@
},
{
"cell_type": "code",
"execution_count": 31,
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"superman\n",
"spiderman\n",
"green lantern\n"
]
"text": "superman\nspiderman\ngreen lantern\n"
}
],
"source": [
@ -1275,7 +1263,45 @@
},
{
"cell_type": "markdown",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Note how for-loops in Python can avoid dealing with indexes, while still supporting the alternative."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "superman\nspiderman\ngreen lantern\n"
}
],
"source": [
"# Using enumerate to also gain access to the running index\n",
"for i, string in enumerate(strings):\n",
" if len(strings[i]) > 7: # If the current string has more than seven characters \n",
" print(strings[i]) # Print it"
]
},
{
"cell_type": "markdown",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (<ipython-input-2-4d251609901f>, line 2)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"<ipython-input-2-4d251609901f>\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m A `while` loop is a loop that continues until some condition is no longer satisfied.\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"## `while` loops\n",
"A `while` loop is a loop that continues until some condition is no longer satisfied.\n",
@ -1323,7 +1349,7 @@
"counter = 1\n",
"while counter < 5: \n",
" print(f'The count is {counter}')\n",
" counter += 1 # Update counter (equivalent to: counter=counter+1)"
" counter += 1 # Update counter (equivalent to: counter=counter+1)"
]
},
{
@ -1335,19 +1361,48 @@
"\n",
" > **Remember:** All code inside a `while`-block must be indented!\n",
"\n",
"A `while`-loop can be good when the number of iterations are unknown beforehand. This could be when searching for a root of an equation (e.g finding the neutral axis of a reinforced concrete section).\n",
"A `while`-loop can be good when the number of iterations are unknown beforehand. This could be when searching for a root of an equation.\n",
"\n",
"When iterating, convergence is not always guaranteed. A common way of exiting the `while`-loop is to define a max number of iterations and then check in each loop whether this number has been reached. If it has, then the loop should `break`.\n",
"\n",
"A similar logic to `while`-loops could be done with by `for`-loops, but a `while`-loop is cleaner for some purposes and can help to clarify the intent of the code."
]
},
{
"cell_type": "markdown",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Both for and while loops can be affected by `continue` and/or `break`. `Continue` starts on the next interation while skipping the rest of the code block and `break` stops the whole loop. The example above is reproduced below using `break`. This can sometime yield more readable code."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "The count is 1\nThe count is 2\nThe count is 3\nThe count is 4\n"
}
],
"source": [
"counter = 1\n",
"while True: \n",
" print(f'The count is {counter}')\n",
" counter += 1 # Update counter (equivalent to: counter=counter+1)\n",
" if counter > 4:\n",
" break # break out of while loop"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## List comprehensions\n",
"List comprehensions are other ways of writing `for`-loops. They can be done in one line and are often cleaner and more readable for simple iteration.\n",
"List comprehensions are another way of writing `for`-loops in a single line of code. They're generally faster and can be used for more compact representation of simple interations yielding more readable code.\n",
"\n",
"### General form of list comprehensions\n",
"The general form of the simplest list comprehension is\n",
@ -1391,7 +1446,7 @@
"L1 = [12, 215, 31, 437, 51]\n",
"\n",
"# List comprehension to multiply each element of L1 by 2\n",
"L2 = [2*i for i in L1] \n",
"L2 = [2*elem for elem in L1] \n",
"L2"
]
},
@ -1426,7 +1481,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"To get a vectorized behavior like that we could have use `numpy`, which is a third party library for numerical compuations similar to Matlab. Later sessions will explore `numpy` further."
"To get a vectorized behavior like that we could have used `numpy`, which is a hugely popular third party library for numerical compuations similar to Matlab. Later sessions will explore `numpy` further."
]
},
{
@ -1452,16 +1507,14 @@
},
{
"cell_type": "code",
"execution_count": 35,
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[4, 5]"
]
"text/plain": "[4, 5]"
},
"execution_count": 35,
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
@ -1471,7 +1524,7 @@
"x = [1, 2, 3, 4, 5] \n",
"\n",
"# Filter list with list comprehension by use of condition\n",
"result_list = [i for i in x if i > 3]\n",
"result_list = [x for x in x if x > 3]\n",
"result_list"
]
},
@ -1479,7 +1532,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"### List comprehension with `if`-statement\n",
"### List comprehension with `if`-`else`-statement\n",
" \n",
"~~~~python\n",
" result_list = [expression1 if condition else expression2 for item in iterable]\n",
@ -1502,16 +1555,14 @@
},
{
"cell_type": "code",
"execution_count": 36,
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0, 0, 182, 0, 151, 174]"
]
"text/plain": "[None, None, 182, None, 151, 174]"
},
"execution_count": 36,
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
@ -1521,7 +1572,7 @@
"v = [3, 62, 182, 26, 151, 174]\n",
"\n",
"# Set all elements of v that are less than 100 equal to 0\n",
"w = [0 if i < 100 else i for i in v]\n",
"w = [None if x < 100 else x for x in v]\n",
"w"
]
},
@ -1691,7 +1742,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.1"
"version": "3.7.3"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
@ -1735,4 +1786,4 @@
},
"nbformat": 4,
"nbformat_minor": 2
}
}