Lists Advanced Concepts Dennis Komm Programming and Problem-Solving The modules numpy , matplotlib , and pandas Spring 2020 – April 02, 2020 Listen List Comprehensions So far Now: List Comprehensions to initialize. . . Initializing a list: x = [] or x = [1, 4, 8] a list of the first ten natural numbers: x = [i for i in range(0, 10)] Initializing a list with ten zeros: x = [0] * 10 a list of the first ten even numbers: Appending elements: x.append(3) x = [i for i in range(0, 20, 2)] Merging lists: x = x + y or x = x + [5, 7, 9] a list of the squares of the first ten natural numbers: x = [i * i for i in range(0, 10)] Accessing (and removing) the first element: z = x.pop(0) a list of the squares of [8, 19, 71, 101] : Accessing (and removing) the last element: z = x.pop() x = [i * i for i in [8, 19, 71, 101]] Accessing i th element: z = x[i] Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 1 / 34 Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 2 / 34
List Comprehensions Exercise – List Comprehensions [ � Expression depending on variable i � for i in � list � ] Initialize a list that [ � Expression depending on variable i � for i in range( . . . ) ] contains all prime numbers between Filter 1 and 1000 [ � Expression depending on variable i � for i in � list � if � Condition � ] uses the function primetest and list comprehensions List of all numbers from [8, 60, 3, 19, 21] that are larger than 8: x = [i for i in [8, 60, 3, 19, 21] if i > 8] List of all numbers from [9, 6, 10, 19] that are divisible by 5: [ � Expression depending on variable i � for i in range( . . . ) if � Condition � ] y = [9, 6, 10, 19] x = [i for i in y if i % 5 == 0] Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 3 / 34 Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 4 / 34 List Comprehensions Accessing Elements from math import sqrt Accessing element at position 0: x[0] def primetest(x): if x < 2 or (x > 2 and x % 2 == 0): Accessing element at last position: x[len(x) - 1] return False Accessing element at last position: x[-1] d = 3 while d <= sqrt(x): if x % d == 0: Accessing sublist from positions 4 to 9: z = x[4:10] return False d += 2 Accessing sublist from position 5 z = x[5:] return True Accessing sublist to position 3 z = x[:4] y = [i for i in range(1001) if primetest(i)] Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 5 / 34 Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 6 / 34
Namespaces So far Including own / existing modules Square root function from math from math import sqrt Namespaces from math import * Problem if different modules use same function names Use namespaces This gives content of module a unique name import math as mymath print(mymath.sqrt(9)) Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 7 / 34 numpy and matplotlib Two modules are frequently used in a scientific context numpy and matplotlib They allow a functionality similar to MATLAB The Modules numpy and matplotlib numpy Calculations with vectors and matrices Numerical methods Documentation: https://numpy.org/doc/ matplotlib Data visualization (Plots) Documentation: https://matplotlib.org/contents.html Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 8 / 34
The Module numpy numpy builds the foundation for many other scientific modules The Module numpy Focus on efficient processing of large vectors and matrices It contains its own data structures, e.g., numpy arrays These work similar to Python lists numpy arrays are faster numpy arrays allow for more operations Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 9 / 34 The Module numpy The Module numpy Large range of functions import numpy as np Linear algebra (Submodule) Convert Python list into numpy array import numpy as np import numpy.linalg as npla x = np.array([1, 3, 4]) This also works for more dimensions a = np.array([[5, 3, 0], [1, 2, 0], [0, 2, 11]]) b = np.array([4, 8, 1]) y = np.array([[1, 3, 4], [6, 8, 1], [0, 9, 4]]) x = npla.solve(a, b) numpy arrays can be added and multiplied Statistics print(x + y) Interpolation (e.g., least square method) print(x * y) . . . Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 10 / 34 Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 11 / 34
The Module matplotlib Module to generate plots Data visualization Submodule matplotlib.pyplot allows usage analogously to MATLAB The Module matplotlib Data given by, e.g., Python lists or numpy arrays import numpy as np import matplotlib.pyplot as plt plt.plot([1, 4, 9, 16, 25]) plt.show() Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 12 / 34 The Module matplotlib – Code-Expert The Module matplotlib Specifying both x - and y -values: The function show cannot be used in Code-Expert plt.plot([0, 4, 8, 12], [0, 10, 20, 35]) Instead, we save the plot using the function savefig plt.show() Using numpy arrays: import numpy as np import matplotlib.pyplot as plt x = np.array([0, 4, 8, 12]) y = np.array([0, 10, 20, 35]) plt.plot(x, y) plt.plot([1, 4, 9, 16, 25]) plt.show() plt.savefig("cx_out/out.png") Using arange() instead of range() : Plot has to be saved in cx_out x = np.arange(0, 13, 4) y = np.array([0, 10, 20, 35]) Display under “Files” plt.plot(x, y) plt.show() Within these slides, we use plot Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 13 / 34 Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 14 / 34
The Module matplotlib The Module matplotlib Options plot( � x-values � , � y-values � , � list of options � ) color, line style, line width, dots instead of lines, . . . See documentation import numpy as np Import of numpy and matplotlib import matplotlib.pyplot as plt Labeling axes x -values 0 , 0 . 01 , 0 . 02 , . . . , 10 x = np.arange(0, 10.01, 0.01) plt.xlabel() f1 = np.sin(x) plt.ylabel() f2 = np.cos(x) f3 = 0.01 * x**2 + 0.15 * x - 1 Animations plt.plot(x, f1, color="red") Three functions: sine, cosine, polynomial Displaying plot only shortly with plt.pause() instead of plt.plot() plt.plot(x, f2, color="blue") (plot is not yet displayed) plt.plot(x, f3, color="green") Removing old plot with plt.close() Submodule matplotlib.animation for more professional animations plot is displayed plt.show() Also see documentation Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 15 / 34 Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 16 / 34 The Module matplotlib Animated Bubblesort import matplotlib.pyplot as plt x = np.array([1, 2, 1.5, 1.75, 1.5]) y = np.array([2, 1.75, 1.5, 2.25, 1.85]) def bubblesort(data): plt.scatter(x, y) n = len(data) plt.show() x = range(len(data)) for d in range(n, 1, -1): for i in range(0, d-1): x = np.arange(0, 10) plt.bar(x, data) y = np.array([1, 4, 4, 8, 9, 6, 7, 6, 3, 2]) plt.pause(0.001) plt.bar(x, y) plt.close() plt.show() if data[i] > data[i+1]: tmp = data[i] x = np.arange(0, 10) data[i] = data[i+1] y = np.array([1, 1, 2, 3, 4, 2, 3, 6, 7, 9]) data[i+1] = tmp plt.barh(x, y) return data plt.show() print(bubblesort([6, 22, 61, 1, 89, 31, 9, 10, 76])) Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 17 / 34 Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 18 / 34
Animated Bubblesort – Code-Expert import matplotlib.pyplot as plt def bubblesort(data): n = len(data) x = range(len(data)) The Module matplotlib for d in range(n, 1, -1): for i in range(0, d-1): plt.bar(x, data) Visualizing the complexity of Bubblesort plt.savefig("cx_out/out.png") input("Weiter mit beliebiger Taste") plt.close() if data[i] > data[i+1]: tmp = data[i] data[i] = data[i+1] data[i+1] = tmp return data print(bubblesort([6, 22, 61, 1, 89, 31, 9, 10, 76])) Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 19 / 34 Exercise – Complexity of Bubblesort Complexity of Bubblesort def bubblesort(data): n = len(data) Copy Bubblesort counter = 0 Use a variable counter to count the number for d in range(n, 1, -1): values = [] of comparisons for i in range(0, d-1): for i in range(10, 201): counter += 1if data[i] data = np.arange(i, 0, -1) Return this value using return > data[i+1]: values.append(bubblesort(data)) Run this algorithm on backward-sorted lists if data[i] > data[i+1]: of lengths from 10 to 200 counter += 1 plt.plot(values) plt.show() tmp = data[i] Save these values in a list and plot it data[i] = data[i+1] data[i+1] = tmp return counter Count permutations Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 20 / 34 Programming and Problem-Solving – numpy , matplotlib , and pandas Spring 2020 Dennis Komm 21 / 34 Count comparisons
Recommend
More recommend