#!/usr/bin/python3
# Tuples and dictionaries are both sensible choices for storing this kind of information
# Tuples cannot be changed once created, which is sometimes a limitation
# Make a list of tuples
that = [('gary', 47), ('howard', 50), ('mark', 46), ('jason', 48), ('robbie', 44)]
# Make a dictionary
that = {'gary': 47, 'howard': 50, 'mark': 46, 'robbie': 44}
# Add an entry to the dictionary
that['jason'] = 48 # simply refer to something by key, and it will be added, or overwritten if it already exists
# Remove an entry
that.pop('robbie')
# ======================================================================================
s = {1,2,3}
r = {2,4,6}
s.add(5) # add an entry
s.remove(3) # remove an entry
inter = s.intersection(r)
union = s | r
diff = s - r
symmetric_difference = s ^ r # elements that appear in one set, but not in both
# ======================================================================================
def f(x):
return x,x**2,x**3,x**4
a,b,c,d = f(2) # i.e. unpack by having comma separated names on the left hand side of the equals sign
# This is to illustrate how to use a function which returns more than one value
# e.g. scipy.integrate.quad, which we use like "answer,error = quad(f,0,np.inf)" or similar
# ======================================================================================
from scipy.integrate import quad
import numpy as np
def f(x):
return np.cos(x)*np.exp(-x**2)
answer,error = quad(f, 0, np.inf)
def f(x):
return np.exp(-x)
def F(x):
answer, error = quad(f, 0, x)
return answer
import matplotlib.pyplot as plt
x = np.linspace(0,10,1001)
y = [F(xi) for xi in x] # can't just do y=F(x) because quad can't handle an array as a limit of the integral
plt.plot(x,y)
plt.show()
# ======================================================================================
print("self-reference is probably not useful")
stuff = [0,1,2]
stuff.append(stuff) # this is a strange thing to do, and almost never useful
print(stuff) # my intention was to show that Python handles abstract things with ease.
print("sort method of a list sorts the list in-place i.e. it changes the list")
stuff = [1,5,2,7,1,7,5,3]
print(stuff)
stuff.sort()
print(stuff)
print("sorted makes a new list and leaves the original unchanged")
stuff = [1,5,2,7,1,7,5,3]
sorted_stuff = sorted(stuff)
print(stuff)
print(sorted_stuff)