Programming for Engineers in Python
Recitation 4
Programming for Engineers in Python
1
AgendaSample problemsHash functions & dictionaries (or next week)Car simulation2
2
A function can be an argument3def do_twice(f):f()f()def print_spam():print 'spam'>>> do_twice(print_spam)spamspam
Fermats last theorem4Pierre de Fermat1601-1665
Fermats last theorem5>>> check_fermat(3,4,5,2)No, that doesn't work>>> check_fermat(3,4,5,3)No, that doesn't workDirty shortcut since 1995:def check_fermat(a,b,c,n):print "Wiles proved it doesnt work"
Sir Andrew John Wiles1953-
Cumulative sum6For 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 its Taylor expansion7from math import factorial, e
term = 1summ = 0k = 0while term > 1e-15: term = 1.0/factorial(k) summ += term k += 1
print "Python e:", eprint Taylors e:", summprint Iterations:, k
Brook Taylor, 1685-1731
Estimating by the Basel problem8from math import factorial, pi, sqrt
term = 1summ = 0k = 1while term > 1e-15: term = 1.0/k**2 summ += term k += 1summ = sqrt(summ*6.0)
print "Python pi:", piprint Eulers pi:", summprint Iterations:, k
Leonard Euler,1707-1783
Ramanujans estimation (optional)9from math import factorial, pi
term = 1summ = 0k = 0while term > 1e-15: term = factorial(4.0*k) / factorial(k)**4.0 term *= (1103.0+26390.0*k) / 396.0**(4.0*k) summ += term k += 1summ = 1.0/(summ * 2.0*2.0**0.5 / 9801.0)
print "Python Pi:", piprint "Ramanujan Pi:", summprint Iterations:, k
Srinivasa Ramanujan, 1887-1920
Triple Double Word10We want to find a word that has three double letters in it, like aabbcc (which is not a word!)Almost qualifiers:CommitteeMississippiWrite a function to check if a word qualifiesWrite a function that reads a text file and checks all the words Code: http://www.greenteapress.com/thinkpython/code/cartalk.pyCorpus: http://www.csie.ntu.edu.tw/~pangfeng/Fortran%20examples/words.txt
PyGame11A set of Python modules designed for writing computer gamesDownload & install:http://pygame.org/ftp/pygame-1.9.2a0.win32-py2.7.msi
Car game12Control a car moving on the screenYouTube demo: http://www.youtube.com/watch?v=DMOj3HpjemECode: https://gist.github.com/1372753 or in car.pyCar controlled by arrowsHonk with EnterExit with ESC
ToDo List:13Fix stirring problemHonk by pressing spaceCar will go from the bottom to top and from one side to the other (instead of getting stuck)Switch to turtle!
2 players car game14Collision avoidance simulator:When the cars are too close one of them honksPlayers need to maneuver the cars to avoid honksCode: https://gist.github.com/1380291 or cars.pyRed car controlled by arrowsBlue car controlled by z, x, c, s