Recitation 4 Programming for Engineers in Python
Agenda Sample problems Hash functions & dictionaries (or next week) Car simulation 2
A function can be an argument 3 def do_twice(f): f() def print_spam(): print 'spam' >>> do_twice(print_spam) spam
Fermat’s last theorem 4 Pierre de Fermat
Fermat’s last theorem 5 >>> check_fermat(3,4,5,2) No, that doesn't work >>> check_fermat(3,4,5,3) No, that doesn't work Dirty shortcut since 1995: def check_fermat(a,b,c,n): print "Wiles proved it doesn’t work" Sir Andrew John Wiles 1953-
Cumulative sum 6 For a given list A we will return a list B such that B[n] = A[0]+A[1]+…A[n] Take 1: def cumulative_sum(lst): summ = [ lst[0] ] * len(lst) for i in range(1, len(lst)): summ[i] = summ[i-1] + lst[i] return summ Take 2: def cumulative_sum(lst): return [sum(lst[0:n]) for n in range(1, len(lst)+1)]
Estimating e by it’s Taylor expansion 7 from math import factorial, e term = 1 summ = 0 k = 0 while term > 1e-15: term = 1.0/factorial(k) summ += term k += 1 print "Python e:", e print “Taylor’s e:", summ print “Iterations:”, k Brook Taylor,
Estimating π by the Basel problem 8 from math import factorial, pi, sqrt term = 1 summ = 0 k = 1 while term > 1e-15: term = 1.0/k**2 summ += term k += 1 summ = sqrt(summ*6.0) print "Python pi:", pi print “Euler’s pi:", summ print “Iterations:”, k Leonard Euler,
Ramanujan’s π estimation (optional) 9 from math import factorial, pi term = 1 summ = 0 k = 0 while term > 1e-15: term = factorial(4.0*k) / factorial(k)**4.0 term *= ( *k) / 396.0**(4.0*k) summ += term k += 1 summ = 1.0/(summ * 2.0*2.0**0.5 / ) print "Python Pi:", pi print "Ramanujan Pi:", summ print “Iterations:”, k Srinivasa Ramanujan,
Triple Double Word 10 We want to find a word that has three double letters in it, like aabbcc (which is not a word!) Almost qualifiers: Committee Mississippi Write a function to check if a word qualifies Write a function that reads a text file and checks all the words Code: Corpus: words.txt words.txt
PyGame 11 A set of Python modules designed for writing computer games Download & install:
Car game 12 Control a car moving on the screen YouTube demo: Code: or in car.pyhttps://gist.github.com/ Car controlled by arrows Honk with Enter Exit with ESC
ToDo List: 13 Fix stirring problem Honk by pressing space Car will go from the bottom to top and from one side to the other (instead of getting stuck) Switch to turtle!
2 players car game 14 Collision avoidance simulator: When the cars are too close one of them honks Players need to maneuver the cars to avoid honks Code: or cars.pyhttps://gist.github.com/ Red car controlled by arrows Blue car controlled by z, x, c, s