Go over midterm
Coding tips and help
return and print.Fetch today's material:
nbgrader fetch phys202-2015 day11
nbgrader fetch phys202-2015 assignment08
A function that has no return statement will always return None:
In [ ]:
def f(x):
print(x**2)
In [ ]:
a = f(2)
In [ ]:
print(a)
If you want a function to do anything useful, you have to return something:
In [4]:
def g(x):
return x**2
In [5]:
b = g(2)
In [6]:
print(b)
String can be turned into lists and tuples:
In [11]:
import random
alpha = 'abcdefghijklmnopqrstuvwxyz'
In [21]:
l = [random.choice(alpha) for i in range(10)]
l
Out[21]:
In [22]:
s = ''.join(l)
s
Out[22]:
In [25]:
for c in s:
print(c)
In [27]:
[c.upper() for c in s]
Out[27]:
In [23]:
list(s)
Out[23]:
In [24]:
tuple(s)
Out[24]:
In [29]:
digits = str(1001023039)
In [31]:
list(digits)
Out[31]:
In [32]:
[int(d) for d in digits]
Out[32]:
In [38]:
def random_string(n):
return ''.join([random.choice(alpha) for i in range(n)])
In [39]:
random_string(100)
Out[39]:
In [46]:
def count0(seq):
counts = {}
for s in seq:
counts[s] = seq.count(s)
return counts
In [65]:
rs = random_string(10)
count0(rs), rs
Out[65]:
In [52]:
%timeit count0(random_string(10000))
In [72]:
def count1(seq):
counts = {}
for s in seq:
if s in counts:
counts[s] += 1
else:
counts[s] = 1
return counts
In [73]:
rs = random_string(10)
count1(rs), rs
Out[73]:
In [74]:
%timeit count1(random_string(10000))
In [75]:
from collections import defaultdict
def count2(seq):
counts = defaultdict(int)
for s in seq:
counts[s] += 1
return counts
In [76]:
rs = random_string(10)
count2(rs), rs
Out[76]:
In [77]:
%timeit count2(random_string(10000))
In [78]:
from collections import Counter
In [84]:
def count3(seq):
return dict(Counter(seq))
In [85]:
rs = random_string(10)
count3(rs), rs
Out[85]:
In [86]:
%timeit count3(random_string(10000))
assignment08 by Wednesday (Day 12).