""" John Rachlin DS 2000: Intro to Programming with Data Filename: lol Description: """ #%% Tuples: Lists that can't be changed T = (1, 2, 3) T[0] #T[1] = 99 # Not allowed # We could also say: a, b, c = 1, 2, 3 print(a) print(b) print(c) # How we swap values in other languages x = 'hello' y = 'world' print(x, y) temp = x x = y y = temp print(x, y) # How we swap values in python # Lets restore x and y back to their original values x, y = y, x print(x, y) #%% # Why tuples? # Sometimes you want a function to return multiple values def min_avg_max(L): """ Return the minimum, average, and maximum of a list """ if len(L) == 0: return None minimum = min(L) maximum = max(L) average = sum(L) / len(L) return minimum, average, maximum a, b, c = min_avg_max([1,4,6,8,5,6,3,5,4,2,3,99]) print(a,b,c) #%% Tuples play an important role in dictionaries (LATER) # << Coming soon >> #%% Lists of lists # Lists can store anything, including other lists # The elements don't have to be the same type L = [1, 2, "hello", True, ['a', 'b', 'c']] len(L) #%% A 4 x 3 array: 3 sublists each of length 3 groceries = [['apples', 6, 0.99], ['milk', 1, 1.49], ['break', 2, 3.50]] groceries[1] groceries[1][0] #%% named parameters. Parameters can be explicitely named # when calling a function. This can help make your code more # readable in some cases. Matplotlib does this all the time. def calc(x, y): return 2 * x + y calc(1, 2) calc(x = 1, y = 2) calc(y = 2, x = 1) # listing parameters in a different order! #%% optional parameters # In this example, e is optional. The default value, 2, is used # if we don't provide a second parameter def pow(x, e=2): return x ** e pow(3) pow(3, 3) #%% Let's put it all together def total_bill(grocery_list, sales_tax = 0.0): total = 0.0 for item in range(len(grocery_list)): total += grocery_list[item][1] * grocery_list[item][2] # add sales tax total += total * (1 + sales_tax) return round(total, 2) total_bill(groceries, sales_tax = 0.07) #%% A multiplication table # True story: in Vermont they only teach you up to 10x10. # Don't ask me what 12x8 is. I have no idea. Kidding I know. # But I have to think about it..... # Create a 13 x 13 table. # 13 lists each containing 13 elements MT = [] for i in range(13): MT.append([]) # Start a new row for j in range(13): MT[i].append(i * j) print(MT[12][8]) for row in MT: print(row) #%% Cool patterns # Create a 500 x 500 table. # 13 lists each containing 13 elements WIDTH = 500 LENGTH = 500 pat = [] for i in range(WIDTH): pat.append([]) # Start a new row for j in range(LENGTH): pat[i].append((i * i - j*j) % 207) # Can you come up with # an interesting patter? import matplotlib.pyplot as plt plt.figure(figsize=(5,5), dpi=200) plt.imshow(pat, cmap='Spectral') plt.savefig('pattern.png')