Software Design Fall 2004 For next time: 1) read Chapter 8 of "How to think..." 2) prepare for a quiz covering Chapters 2-7, probably involving a stack diagram The first exam will be Thursday 30 September, during class time. Homework 3 Tips --------------- As we learn more about strings and lists, you might want to go back and look for easier ways. The in operator: >>> 'e' in 'Allen' True String operations: from string import * s = lower('ALLEN') http://www.python.org/doc/current/lib/module-string.html String methods: s = 'ALLEN' s2 = s.lower() http://www.python.org/doc/current/lib/string-methods.html List methods: http://www.python.org/doc/current/lib/typesseq-mutable.html Homework 2 Solutions -------------------- wget http://wb/sd/code/polygon.py wget http://wb/sd/code/Wanderer_soln.py polygon.py highlights: def polyline(t, n, length, angle): for i in range(n): fd(t, length) lt(t, angle) def polygon(t, n, length): angle = 360.0/n polyline(t, n, length, angle) What's wrong with the following, INCORRECT, version of arc? def arc(t, r, theta=360.0, length=1): # draw part of a circle with radius r and angle theta. # using segments with the given length circum = 2 * pi * r * theta / 360 n = circum / length length = circum / n angle = theta / n polyline(t, n, length, angle) Wanderer.py highlights: def out_of_bounds(t): # which way is toward the center? away = atan2(t.y, t.x) * 180 / pi toward = (away + 180) % 360 # choose two possible headings d1 = t.heading + rand_turn(t.clumsiness) d2 = t.heading + rand_turn(t.clumsiness) # choose the one that is more toward the center diff1 = angle_distance(toward, d1) diff2 = angle_distance(toward, d2) if diff1 < diff2: t.heading = d1 else: t.heading = d2 Looping ------- Chapter 6 talks mostly about while loops, because control flow is explicit: i = 0 while i<3: print i i = i + 1 However, the for loop is far more common in Python. We have already seen some examples: for i in range(4): print i The range command returns a list: >>> range(4) [0, 1, 2, 3] >>> range(2,5) [2, 3, 4] >>> range(2,10,2) [2, 4, 6, 8] So the previous example is equivalent to for i in [0, 1, 2, 3]: print i And we saw the following example in class: def koch(t, n): if n<4: fd(t, n) return for angle in [60, -120, 60, 0]: koch(t, n/3.0) lt(t, angle) We also saw this example in notes02 (a list of strings!): for color in ['red', 'yellow', 'blue']: bob.set_color(color) for loops also traverse the letters of a string: for letter in 'allen': print letter The while statement is more general than the for loop, because you can generate the sequence "on the fly": while n != 1: print n, if n%2 == 0: n = n/2 else: n = n*3+1 Can you express this as a for loop?