diff --git a/.github/workflows/autopep8.yml b/.github/workflows/autopep8.yml new file mode 100644 index 0000000..4ce981e --- /dev/null +++ b/.github/workflows/autopep8.yml @@ -0,0 +1,22 @@ +name: Format python code +on: push +jobs: + autopep8: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: autopep8 + uses: peter-evans/autopep8@v1 + with: + args: --recursive --in-place --aggressive --aggressive . + - name: Create Pull Request + uses: peter-evans/create-pull-request@v2 + with: + token: ${{ secrets.GITHUB_TOKEN }} + commit-message: autopep8 action fixes + committer: Peter Evans + title: Fixes by autopep8 action + body: This is an auto-generated PR with fixes by autopep8. + labels: autopep8, automated pr + reviewers: peter-evans + branch: autopep8-patches diff --git a/book/figs/loop.py b/book/figs/loop.py index 1e4dea2..538dc1d 100644 --- a/book/figs/loop.py +++ b/book/figs/loop.py @@ -1,20 +1,24 @@ -import sys, os +import sys +import os from glob import glob + def pipe(cmd): fp = os.popen(cmd) res = fp.read() stat = fp.close() return res, stat - + + def main(script, files='*.eps'): for filename in sorted(glob(files)): destination = '.'.join(filename.split('.')[:-1]) + '.pdf' - cmd = 'convert %s %s' % (filename, destination) + cmd = 'convert %s %s' % (filename, destination) print cmd res, stat = pipe(cmd) print res, stat - + + if __name__ == '__main__': main(*sys.argv) diff --git a/book/localdef.py b/book/localdef.py index 14f7a5b..786dbe7 100644 --- a/book/localdef.py +++ b/book/localdef.py @@ -1,34 +1,41 @@ import plasTeX.Base as Base + def idgen(): """ Generate a unique ID """ i = 1 - while 1: + while True: yield 'a%.10d' % i i += 1 + idgen = idgen() + class Eqn(Base.Command): args = 'self' + class Anchor(Base.Command): args = 'label:str' + def invoke(self, tex): Base.Command.invoke(self, tex) self.ownerDocument.context.label(self.attributes['label'], self) + class exercise(Base.Environment): counter = 'exercise' + class index(Base.Command): args = 'termstring' def setEntry(self, s, seetype=0): - # TYPE_NORMAL = 0 - # TYPE_SEE = 1 - # TYPE_SEEALSO = 2 - if type(s) != type(''): + # TYPE_NORMAL = 0 + # TYPE_SEE = 1 + # TYPE_SEEALSO = 2 + if not isinstance(s, type('')): s = s.textContent if s.count('!'): priterm, secterm = s.split('!') @@ -52,13 +59,13 @@ def setEntry(self, s, seetype=0): # Base.IndexEntry([primary, secondary], self, [prisort, secsort], None, type=seetype)) # else: # self.ownerDocument.userdata.setdefault('index', []).append(\ -# Base.IndexEntry([primary], self, [prisort], None, type=seetype)) +# Base.IndexEntry([primary], self, [prisort], None, type=seetype)) return prisort, primary, secsort, secondary def invoke(self, tex): Base.Command.invoke(self, tex) self.ownerDocument.context.label(idgen.next(), self) - p0,p1,s0,s1 = self.setEntry(self.attributes['termstring']) + p0, p1, s0, s1 = self.setEntry(self.attributes['termstring']) if p0: self.prisort = '%s' % p0 if p1: @@ -68,14 +75,34 @@ def invoke(self, tex): if s1: self.secondary = '%s' % s1 + class scriptN(Base.Command): - unicode = u'\U0001D4A9' + unicode = u'\U0001D4A9' + + +class uxbar(Base.Command): + pass + + +class uybar(Base.Command): + pass + + +class unhat(Base.Command): + pass + + +class ule(Base.Command): + pass + + +class minus(Base.Command): + pass + + +class lowast(Base.Command): + pass -class uxbar(Base.Command): pass -class uybar(Base.Command): pass -class unhat(Base.Command): pass -class ule(Base.Command): pass -class minus(Base.Command): pass -class lowast(Base.Command): pass -class Erdos(Base.Command): pass +class Erdos(Base.Command): + pass diff --git a/code/Card.py b/code/Card.py index 86e43b2..944ffe3 100644 --- a/code/Card.py +++ b/code/Card.py @@ -6,21 +6,20 @@ License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ - import random class Card(object): """Represents a standard playing card. - + Attributes: suit: integer 0-3 rank: integer 1-13 """ suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"] - rank_names = [None, "Ace", "2", "3", "4", "5", "6", "7", - "8", "9", "10", "Jack", "Queen", "King"] + rank_names = [None, "Ace", "2", "3", "4", "5", "6", "7", + "8", "9", "10", "Jack", "Queen", "King"] def __init__(self, suit=0, rank=2): self.suit = suit @@ -48,7 +47,7 @@ class Deck(object): Attributes: cards: list of Card objects. """ - + def __init__(self): self.cards = [] for suit in range(4): @@ -97,14 +96,14 @@ def move_cards(self, hand, num): class Hand(Deck): """Represents a hand of playing cards.""" - + def __init__(self, label=''): self.cards = [] self.label = label def find_defining_class(obj, method_name): - """Finds and returns the class object that will provide + """Finds and returns the class object that will provide the definition of method_name (as a string) if it is invoked on obj. diff --git a/code/Highway.py b/code/Highway.py index 902e7b4..270797b 100644 --- a/code/Highway.py +++ b/code/Highway.py @@ -16,13 +16,14 @@ class Highway(TurtleWorld): """A circular Highway with one lane that spirals down the canvas. - + Attributes: rows: the number of rows that spiral down the canvas. delay: time between steps in seconds colors: list of RGB strings """ + def __init__(self): TurtleWorld.__init__(self) self.rows = 2.0 @@ -59,7 +60,7 @@ def lane_heading(self): def step(self): """Performs one time step.""" TurtleWorld.step(self) - + # compute average turtle speed total = 0.0 for turtle in self.animals: @@ -86,8 +87,8 @@ def make_drivers(self, n, constructor): # refers to the driver in front t.sort() turtles = [t[1] for t in t] - for i in range(n-1): - turtles[i].next = turtles[i+1] + for i in range(n - 1): + turtles[i].next = turtles[i + 1] turtles[-1].next = turtles[0] return turtles @@ -130,9 +131,9 @@ def brake(self, change): def step(self): """Checks the distance to the next driver, adjusts speed, and moves. - + This function enforces the rules for all drivers. - + Driver decision-making is in choose_acceleration(). """ dist = self.find_distance() @@ -166,7 +167,7 @@ def choose_acceleration(self, dist): else: return 0.3 - + def make_highway(n, driver=Driver): """Make the highway and drivers, then run the simulation. diff --git a/code/Map.py b/code/Map.py index da92ee3..6b8dbfd 100644 --- a/code/Map.py +++ b/code/Map.py @@ -7,6 +7,7 @@ """ + class LinearMap(object): """A simple implementation of a map using a list of tuples where each tuple is a key-value pair.""" diff --git a/code/MathClient.py b/code/MathClient.py index 73b0533..ed89b65 100644 --- a/code/MathClient.py +++ b/code/MathClient.py @@ -8,16 +8,18 @@ import sys import remote_object + def main(script, name='bob', *args): ns = remote_object.NameServer() server = ns.get_proxy(name) - print server.mul(111,9) - print server.add(100,222) - print server.sub(222,100) - print server.div(2.0,9.0) - print server.mul('*',10) - print server.add('String1','String2') + print server.mul(111, 9) + print server.add(100, 222) + print server.sub(222, 100) + print server.div(2.0, 9.0) + print server.mul('*', 10) + print server.add('String1', 'String2') + if __name__ == '__main__': main(*sys.argv) diff --git a/code/MathServer.py b/code/MathServer.py index 74d6be7..6847561 100644 --- a/code/MathServer.py +++ b/code/MathServer.py @@ -8,16 +8,19 @@ import sys import remote_object + class MathServer(remote_object.RemoteObject): - def mul(s, arg1, arg2): return arg1*arg2 - def add(s, arg1, arg2): return arg1+arg2 - def sub(s, arg1, arg2): return arg1-arg2 - def div(s, arg1, arg2): return arg1/arg2 - + def mul(s, arg1, arg2): return arg1 * arg2 + def add(s, arg1, arg2): return arg1 + arg2 + def sub(s, arg1, arg2): return arg1 - arg2 + def div(s, arg1, arg2): return arg1 / arg2 + + def main(script, name='bob', *args): print 'Starting MathServer %s...' % name server = MathServer(name) server.requestLoop() - + + if __name__ == '__main__': main(*sys.argv) diff --git a/code/Modifier.py b/code/Modifier.py index ed0d23b..3bfdf8d 100644 --- a/code/Modifier.py +++ b/code/Modifier.py @@ -13,15 +13,14 @@ class Modifier: """A Modifier is an object that reads and writes the state of a Subject, but it is not a registered Observer.""" - def __init__(self, subject_name): self.subject = ns.get_proxy(subject_name) def modify(self): """Increment the state of the Subject.""" state = self.subject.get_state() - self.subject.set_state(state+1) - print 'Set state ' + str(state+1) + self.subject.set_state(state + 1) + print 'Set state ' + str(state + 1) ns = NameServer() diff --git a/code/Observer.py b/code/Observer.py index bafbe90..04b227e 100644 --- a/code/Observer.py +++ b/code/Observer.py @@ -22,7 +22,7 @@ def __init__(self, subject_name): id = random.randint(0, 1000000) observer_name = subject_name + '_observer%d' % id RemoteObject.__init__(self, observer_name) - + # register with the subject self.subject = subject_name ns = NameServer() @@ -44,6 +44,6 @@ def notify(self): state = proxy.get_state() print 'Observer notified; new state =', state + obs = Observer('simple_subject') obs.requestLoop() - diff --git a/code/Point1.py b/code/Point1.py index ba9d171..849852a 100644 --- a/code/Point1.py +++ b/code/Point1.py @@ -8,6 +8,7 @@ """ + class Point(object): """Represents a point in 2-D space.""" @@ -18,7 +19,7 @@ def print_point(p): class Rectangle(object): - """Represents a rectangle. + """Represents a rectangle. attributes: width, height, corner. """ @@ -27,8 +28,8 @@ class Rectangle(object): def find_center(rect): """Returns a Point at the center of a Rectangle.""" p = Point() - p.x = rect.corner.x + rect.width/2.0 - p.y = rect.corner.y + rect.height/2.0 + p.x = rect.corner.x + rect.width / 2.0 + p.y = rect.corner.y + rect.height / 2.0 return p @@ -71,4 +72,3 @@ def main(): if __name__ == '__main__': main() - diff --git a/code/Point1_soln.py b/code/Point1_soln.py index 1c5a9c3..4d90270 100644 --- a/code/Point1_soln.py +++ b/code/Point1_soln.py @@ -10,7 +10,7 @@ import copy import math -# to avoid duplicating code, I'm importing everything from Point1 +# to avoid duplicating code, I'm importing everything from Point1 from Point1 import * @@ -57,7 +57,6 @@ def main(): print 'distance', print distance_between_points(grosse, blank) - box = Rectangle() box.width = 100.0 box.height = 200.0 @@ -76,6 +75,6 @@ def main(): print box.corner.x print box.corner.y + if __name__ == '__main__': main() - diff --git a/code/Poker.py b/code/Poker.py index c475cd7..05706e0 100644 --- a/code/Poker.py +++ b/code/Poker.py @@ -28,14 +28,14 @@ def __init__(self): def setup(self): self.ca_width = 100 self.ca_height = 100 - + # left frame self.row() self.canvas = self.ca(width=self.ca_width, height=self.ca_height, bg='dark green', transforms=[]) # right frame - self.col([1,1,1]) + self.col([1, 1, 1]) self.bu('Quit', command=self.quit) self.bu('Deal', command=self.deal_hands) self.bu('Print', command=self.canvas.dump) @@ -48,7 +48,7 @@ def set_cardset(self, cardset, numhands=6, numcards=9): width = self.cardset.width height = self.cardset.height self.canvas.add_transform(TableTransform(width, height)) - self.canvas.configure(width=width*numcards, height=height*numhands) + self.canvas.configure(width=width * numcards, height=height * numhands) def deal_hands(self, nhands=6, ncards=7): """deal the cards and display them on the canvas, @@ -71,7 +71,7 @@ def deal_hands(self, nhands=6, ncards=7): # this version only checks for flushes if hand.has_flush(): hand.label = 'flush' - + view = HandView(hand, self) view.draw(0, i) self.views[hand] = view @@ -92,7 +92,7 @@ class TableTransform(Gui.Transform): def __init__(self, width, height): self.width = width self.height = height - + def trans(self, p): x = p[0] * self.width y = p[1] * self.height @@ -113,17 +113,17 @@ def __init__(self, dir=None, ext='gif'): def read_cards(self, dir, ext='gif'): suits = 'cdhs' - for rank in range(1,14): + for rank in range(1, 14): for suit in range(4): filename = '%s/%.2d%s.%s' % (dir, rank, suits[suit], ext) image = ImageTk.PhotoImage(file=filename) - self[suit,rank] = image + self[suit, rank] = image filename = '%s/back01.gif' % (dir) try: image = ImageTk.PhotoImage(file=filename) self['back'] = image - except: + except BaseException: pass # cardset keeps track of the width and height of the cards @@ -134,9 +134,10 @@ def lookup(self, card): """lookup the given card and return the Image that depicts it""" return self[card.suit, card.rank] + class HandView: """A HandView object represents a Hand being displayed on a Table""" - + def __init__(self, hand, table): self.hand = hand self.table = table @@ -170,15 +171,14 @@ def delete(self): """remove the graphical representation of this HandView""" self.table.canvas.delete(self.tag) - + def main(name, cardstyle='tuxedo', *args): table = Table() cardset = Cardset('cardsets/cardset-' + cardstyle) - table.set_cardset(cardset) + table.set_cardset(cardset) table.mainloop() - + + if __name__ == '__main__': import sys main(*sys.argv) - - diff --git a/code/PokerExam.py b/code/PokerExam.py index f1418d3..d102996 100644 --- a/code/PokerExam.py +++ b/code/PokerExam.py @@ -28,14 +28,14 @@ def __init__(self): def setup(self): self.ca_width = 100 self.ca_height = 100 - + # left frame self.row() self.canvas = self.ca(width=self.ca_width, height=self.ca_height, bg='dark green', transforms=[]) # right frame - self.col([1,1,1]) + self.col([1, 1, 1]) self.bu('Quit', command=self.quit) self.bu('Deal', command=self.deal_hand) self.bu('Print', command=self.canvas.dump) @@ -48,7 +48,7 @@ def set_cardset(self, cardset, numhands=6, numcards=9): width = self.cardset.width height = self.cardset.height self.canvas.add_transform(TableTransform(width, height)) - self.canvas.configure(width=width*numcards, height=height*numhands) + self.canvas.configure(width=width * numcards, height=height * numhands) def deal_hand(self, numcards=7): """Deal one hand and create a HandView.""" @@ -57,7 +57,7 @@ def deal_hand(self, numcards=7): deck = PokerHand.Deck() deck.shuffle() - # deal the cards + # deal the cards hand = PokerHand.PokerHand() deck.move_cards(hand, numcards) @@ -82,7 +82,7 @@ class TableTransform(Gui.Transform): def __init__(self, width, height): self.width = width self.height = height - + def trans(self, p): x = p[0] * self.width y = p[1] * self.height @@ -103,17 +103,17 @@ def __init__(self, dir=None, ext='gif'): def read_cards(self, dir, ext='gif'): suits = 'cdhs' - for rank in range(1,14): + for rank in range(1, 14): for suit in range(4): filename = '%s/%.2d%s.%s' % (dir, rank, suits[suit], ext) image = ImageTk.PhotoImage(file=filename) - self[suit,rank] = image + self[suit, rank] = image filename = '%s/back01.gif' % (dir) try: image = ImageTk.PhotoImage(file=filename) self['back'] = image - except: + except BaseException: pass # cardset keeps track of the width and height of the cards @@ -124,9 +124,10 @@ def lookup(self, card): """lookup the given card and return the Image that depicts it""" return self[card.suit, card.rank] + class HandView: """A HandView object represents a Hand being displayed on a Table""" - + def __init__(self, hand, table): self.hand = hand self.table = table @@ -160,13 +161,14 @@ def delete(self): """remove the graphical representation of this HandView""" self.table.canvas.delete(self.tag) - + def main(name, cardstyle='tuxedo', *args): table = Table() cardset = Cardset('cardsets/cardset-' + cardstyle) - table.set_cardset(cardset) + table.set_cardset(cardset) table.mainloop() - + + if __name__ == '__main__': import sys main(*sys.argv) diff --git a/code/PokerHand.py b/code/PokerHand.py index 44a9741..42fe425 100644 --- a/code/PokerHand.py +++ b/code/PokerHand.py @@ -23,7 +23,7 @@ def suit_hist(self): def has_flush(self): """Returns True if the hand has a flush, False otherwise. - + Note that this works correctly for hands with more than 5 cards. """ self.suit_hist() @@ -46,4 +46,3 @@ def has_flush(self): print hand print hand.has_flush() print '' - diff --git a/code/PokerHandSoln.py b/code/PokerHandSoln.py index d0fca79..aa6a347 100644 --- a/code/PokerHandSoln.py +++ b/code/PokerHandSoln.py @@ -44,18 +44,18 @@ def make_histograms(self): """ self.suits = Hist() self.ranks = Hist() - + for c in self.cards: self.suits.count(c.suit) self.ranks.count(c.rank) self.sets = self.ranks.values() self.sets.sort(reverse=True) - + def has_highcard(self): """Returns True if this hand has a high card.""" return len(self.cards) - + def check_sets(self, *t): """Checks whether self.sets contains sets that are at least as big as the requirements in t. @@ -63,21 +63,22 @@ def check_sets(self, *t): t: list of int """ for need, have in zip(t, self.sets): - if need > have: return False + if need > have: + return False return True def has_pair(self): """Checks whether this hand has a pair.""" return self.check_sets(2) - + def has_twopair(self): """Checks whether this hand has two pair.""" return self.check_sets(2, 2) - + def has_threekind(self): """Checks whether this hand has three of a kind.""" return self.check_sets(3) - + def has_fourkind(self): """Checks whether this hand has four of a kind.""" return self.check_sets(4) @@ -91,7 +92,7 @@ def has_flush(self): for val in self.suits.values(): if val >= 5: return True - return False + return False def has_straight(self): """Checks whether this hand has a straight.""" @@ -112,11 +113,12 @@ def in_a_row(self, ranks, n): for i in range(1, 15): if ranks.get(i, 0): count += 1 - if count == 5: return True + if count == 5: + return True else: count = 0 return False - + def has_straightflush(self): """Checks whether this hand has a straight flush. @@ -136,11 +138,12 @@ def has_straightflush(self): for rank in range(1, 15): if (rank, suit) in s: count += 1 - if count == 5: return True + if count == 5: + return True else: count = 0 return False - + def has_straightflush(self): """Checks whether this hand has a straight flush. @@ -156,13 +159,12 @@ def has_straightflush(self): # see if any of the partitioned hands has a straight for hand in d.values(): if len(hand.cards) < 5: - continue + continue hand.make_histograms() if hand.has_straight(): return True return False - def classify(self): """Classifies this hand. @@ -183,7 +185,7 @@ class PokerDeck(Deck): def deal_hands(deck, num_cards=5, num_hands=10): hands = [] - for i in range(num_hands): + for i in range(num_hands): hand = PokerHand() deck.move_cards(hand, num_cards) hand.classify() @@ -198,9 +200,9 @@ def main(*args): # loop n times, dealing 7 hands per iteration, 7 cards each n = 10000 for i in range(n): - if i%1000 == 0: + if i % 1000 == 0: print i - + deck = PokerDeck() deck.shuffle() @@ -208,19 +210,18 @@ def main(*args): for hand in hands: for label in hand.labels: lhist.count(label) - + # print the results total = 7.0 * n print total, 'hands dealt:' for label in PokerHand.all_labels: freq = lhist.get(label, 0) - if freq == 0: + if freq == 0: continue p = total / freq print '%s happens one time in %.2f' % (label, p) - + if __name__ == '__main__': main(*sys.argv) - diff --git a/code/Popup.py b/code/Popup.py index 4c93aaa..968e239 100644 --- a/code/Popup.py +++ b/code/Popup.py @@ -8,6 +8,7 @@ from swampy.Gui import Gui + class Popup(Gui): """Creates a top-level window with a message.""" diff --git a/code/PopupDemo.py b/code/PopupDemo.py index cbf3808..6c9f2d0 100644 --- a/code/PopupDemo.py +++ b/code/PopupDemo.py @@ -8,6 +8,7 @@ import sys from subprocess import Popen + def spawn_popup(message, sender): """Launches a Popup in a subprocess.""" cmd = ['python', 'Popup.py', message, sender] @@ -18,7 +19,7 @@ def spawn_popup(message, sender): def main(script): """Spawns three Popups.""" - # if you don't get this reference, see + # if you don't get this reference, see # http://www.ibras.dk/montypython/episode03.htm for innuendo in ['Nudge, nudge', 'Snap, snap.', 'Grin, grin.']: @@ -27,4 +28,3 @@ def main(script): if __name__ == '__main__': main(*sys.argv) - diff --git a/code/PopupServer.py b/code/PopupServer.py index 05a06ff..ea5151a 100644 --- a/code/PopupServer.py +++ b/code/PopupServer.py @@ -9,18 +9,21 @@ from remote_object import RemoteObject from PopupDemo import spawn_popup + class PopupServer(RemoteObject): """a PopupServer is a remote object that provides a method, popup() that takes a message and displays it in a Popup""" + def popup(self, message, sender): spawn_popup(message, sender) + def main(script, name='popup_downey', *args): """name is the name of the remote object""" print 'Starting PopupServer %s...' % name server = PopupServer(name) server.requestLoop() - + + if __name__ == '__main__': main(*sys.argv) - diff --git a/code/Shape.py b/code/Shape.py index 6f2a1c2..33ed652 100644 --- a/code/Shape.py +++ b/code/Shape.py @@ -18,7 +18,7 @@ def distance(self, other): """Computes the distance from this location to other.""" dx = self.x - other.x dy = self.y - other.y - return math.sqrt(dx*dx + dy*dy) + return math.sqrt(dx * dx + dy * dy) def isLeft(self, other): return self.x < other.x def isRight(self, other): return self.x > other.x @@ -37,7 +37,7 @@ def __init__(self, center, radius): def contains(self, loc): """Returns True if Location loc is inside this circle - (including the boundary).""" + (including the boundary).""" return loc.distance(self.center) <= self.radius @@ -49,10 +49,14 @@ def __init__(self, topLeft, botRight): def contains(self, loc): """return True if Location loc is inside this rectangle (including the boundary)""" - if loc.isLeft(self.topLeft): return False - if loc.isRight(self.botRight): return False - if loc.isAbove(self.topLeft): return False - if loc.isBelow(self.botRight): return False + if loc.isLeft(self.topLeft): + return False + if loc.isRight(self.botRight): + return False + if loc.isAbove(self.topLeft): + return False + if loc.isBelow(self.botRight): + return False return True @@ -60,5 +64,5 @@ def contains(self, loc): circle = Circle(center, 75) loc = Location(150, 150) -bool = circle.contains(loc) +bool = circle.contains(loc) print bool diff --git a/code/Subject.py b/code/Subject.py index 9188089..751ff9b 100644 --- a/code/Subject.py +++ b/code/Subject.py @@ -24,18 +24,18 @@ def __init__(self, name): def notify_observers(self): """notify all registered observers when the state of the subject changes""" - + for observer in copy(self.observers): try: print 'Notifying', observer ns = NameServer() proxy = ns.get_proxy(observer) proxy.notify() - except Exception, x: + except Exception as x: # this clause should catch errors that occur # in the Observer code. print ''.join(Pyro.util.getPyroTraceback(x)) - except: + except BaseException: # this clause should catch Pyro NamingErrors, # which occur when an observer dies. print 'Removing ' + observer @@ -59,7 +59,7 @@ def __init__(self, name, state=0): self.state = 0 # the following methods are intended to be invoked remotely - + def set_state(self, state): """Changes the state of the Subject.""" print 'New state', state @@ -70,6 +70,6 @@ def get_state(self): """Gets the current state of the Subject.""" return self.state + sub = SimpleSubject('simple_subject') sub.requestLoop() - diff --git a/code/Tagger.py b/code/Tagger.py index 3dfbef5..f8aecff 100644 --- a/code/Tagger.py +++ b/code/Tagger.py @@ -53,7 +53,6 @@ def steer(self): self.apply_tag(target) except Missed: self.chase(target) - def turn_toward(self, x=0, y=0): """Turns to face the given point. @@ -111,7 +110,7 @@ def flee(self, other): other: Turtle object """ self.heading = self.away(other.x, other.y) - + def chase(self, other): """Faces the other turtle. @@ -125,7 +124,7 @@ def closest(self, others): others: list of Animals """ t = [(self.distance_from(animal), animal) - for animal in others if animal is not self] + for animal in others if animal is not self] (distance, animal) = min(t) return animal diff --git a/code/Threader.py b/code/Threader.py index d403c5e..39c3d2a 100644 --- a/code/Threader.py +++ b/code/Threader.py @@ -24,7 +24,7 @@ def step(): See http://en.wikipedia.org/wiki/Stinking_badges """ - + def moveto(self, x, y): """Teleports to the given coordinates and redraws.""" self.x = x @@ -36,11 +36,11 @@ def koch(self, n): See http://en.wikipedia.org/wiki/Koch_snowflake """ - if n<8: + if n < 8: self.fd(n) return for angle in [-60, 120, -60, 0]: - self.koch(n/3.0) + self.koch(n / 3.0) self.rt(angle) def snowflake(self): @@ -66,4 +66,3 @@ def make_threader(world): # add a button that calls make_threader world.bu(text='Make Threader', command=Callable(make_threader, world)) world.mainloop() - diff --git a/code/Threader_soln.py b/code/Threader_soln.py index 5f64bd6..79b296d 100644 --- a/code/Threader_soln.py +++ b/code/Threader_soln.py @@ -25,7 +25,7 @@ def step(): See http://en.wikipedia.org/wiki/Stinking_badges """ - + def moveto(self, x, y): """Teleports to the given coordinates and redraws.""" self.x = x @@ -37,11 +37,11 @@ def koch(self, n): See http://en.wikipedia.org/wiki/Koch_snowflake """ - if n<8: + if n < 8: self.fd(n) return for angle in [-60, 120, -60, 0]: - self.koch(n/3.0) + self.koch(n / 3.0) self.rt(angle) def snowflake(self): @@ -67,4 +67,3 @@ def make_threader(world): # add a button that calls make_threader world.bu(text='Make Threader', command=Callable(make_threader, world)) world.mainloop() - diff --git a/code/Time1.py b/code/Time1.py index 2bcfdc8..da20a7c 100644 --- a/code/Time1.py +++ b/code/Time1.py @@ -8,12 +8,14 @@ """ + class Time(object): """Represents the time of day. - + attributes: hour, minute, second """ + def print_time(t): print '%.2d:%.2d:%.2d' % (t.hour, t.minute, t.second) @@ -76,5 +78,6 @@ def main(): print 'Ends at', print_time(end_time) + if __name__ == '__main__': main() diff --git a/code/Time1_soln.py b/code/Time1_soln.py index a188e07..48f659e 100644 --- a/code/Time1_soln.py +++ b/code/Time1_soln.py @@ -41,7 +41,7 @@ def days_until_birthday(birthday): # if it has gone by, when will it be next year if today > next_birthday: - next_birthday = datetime(today.year+1, birthday.month, birthday.day) + next_birthday = datetime(today.year + 1, birthday.month, birthday.day) # subtraction on datetime objects returns a timedelta object delta = next_birthday - today @@ -111,13 +111,13 @@ def main(): race_time = Time() race_time.hour = 1 race_time.minute = 34 - race_time.second = 05 + race_time.second = 0o5 print 'Half marathon time', print_time(race_time) distance = 13.1 # miles - pace = mul_time(race_time, 1/distance) + pace = mul_time(race_time, 1 / distance) print 'Time per mile', print_time(pace) diff --git a/code/Time2.py b/code/Time2.py index 8a03498..3de8014 100644 --- a/code/Time2.py +++ b/code/Time2.py @@ -8,11 +8,13 @@ """ + class Time(object): """Represents the time of day. - + attributes: hour, minute, second """ + def __init__(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute diff --git a/code/Time2_soln.py b/code/Time2_soln.py index 7ac775a..376af27 100644 --- a/code/Time2_soln.py +++ b/code/Time2_soln.py @@ -8,11 +8,13 @@ """ + class Time(object): """Represents the time of day. - + attributes: hour, minute, second """ + def __init__(self, hour=0, minute=0, second=0): minutes = hour * 60 + minute self.seconds = minutes * 60 + second @@ -60,7 +62,7 @@ def increment(self, seconds): def is_valid(self): """Checks whether a Time object satisfies the invariants.""" - return self.seconds >= 0 and self.seconds < 24*60*60 + return self.seconds >= 0 and self.seconds < 24 * 60 * 60 def int_to_time(seconds): diff --git a/code/Wanderer.py b/code/Wanderer.py index 4b34f7a..8f73a50 100644 --- a/code/Wanderer.py +++ b/code/Wanderer.py @@ -43,7 +43,7 @@ def __init__(self, speed=1, clumsiness=60): self.clumsiness = clumsiness # Wanderers start out facing in a random direction - self.rt(randint(0,360)) + self.rt(randint(0, 360)) def distance(self): """Computes the distance from the Turtle to the origin.""" @@ -61,11 +61,11 @@ def step(self): # call the function that keeps the Wanderers in bounds self.keep_in_bounds(dist) - + # choose a random direction and turn - dir = randint(0,self.clumsiness) - randint(0,self.clumsiness) + dir = randint(0, self.clumsiness) - randint(0, self.clumsiness) self.rt(dir) - + # move forward according to the speed attribute self.fd(self.speed) @@ -74,7 +74,7 @@ def keep_in_bounds(self, dist): # you should modify this method pass - + # create a new TurtleWorld world = TurtleWorld() @@ -83,9 +83,8 @@ def keep_in_bounds(self, dist): world.setup_run() # make three Wanderers with different speed and clumsiness attributes -for i in range(1,4): - Wanderer(i, i*45) +for i in range(1, 4): + Wanderer(i, i * 45) # tell world to start processing events (button presses, etc) wait_for_user() - diff --git a/code/ackermann.py b/code/ackermann.py index b932577..08443d3 100644 --- a/code/ackermann.py +++ b/code/ackermann.py @@ -7,6 +7,7 @@ """ + def ackermann(m, n): """Computes the Ackermann function A(m, n) @@ -15,9 +16,10 @@ def ackermann(m, n): n, m: non-negative integers """ if m == 0: - return n+1 + return n + 1 if n == 0: - return ackermann(m-1, 1) - return ackermann(m-1, ackermann(m, n-1)) + return ackermann(m - 1, 1) + return ackermann(m - 1, ackermann(m, n - 1)) + print ackermann(3, 4) diff --git a/code/ackermann_memo.py b/code/ackermann_memo.py index 4becb87..4fd7254 100644 --- a/code/ackermann_memo.py +++ b/code/ackermann_memo.py @@ -9,6 +9,7 @@ cache = {} + def ackermann(m, n): """Computes the Ackermann function A(m, n) @@ -17,14 +18,15 @@ def ackermann(m, n): n, m: non-negative integers """ if m == 0: - return n+1 + return n + 1 if n == 0: - return ackermann(m-1, 1) + return ackermann(m - 1, 1) try: return cache[m, n] except KeyError: - cache[m, n] = ackermann(m-1, ackermann(m, n-1)) + cache[m, n] = ackermann(m - 1, ackermann(m, n - 1)) return cache[m, n] + print ackermann(3, 4) print ackermann(3, 6) diff --git a/code/anagram_db.py b/code/anagram_db.py index cf7ca37..efe868e 100644 --- a/code/anagram_db.py +++ b/code/anagram_db.py @@ -22,7 +22,7 @@ def store_anagrams(filename, ad): shelf = shelve.open(filename, 'c') for word, word_list in ad.iteritems(): - shelf[word] = word_list + shelf[word] = word_list shelf.close() @@ -49,7 +49,5 @@ def main(name, command='store'): print read_anagrams('anagrams.db', command) - if __name__ == '__main__': main(*sys.argv) - diff --git a/code/anagram_sets.py b/code/anagram_sets.py index 2745573..7839d82 100644 --- a/code/anagram_sets.py +++ b/code/anagram_sets.py @@ -12,8 +12,7 @@ def signature(s): """Returns the signature of this string, which is a string that contains all of the letters in order. """ - t = list(s) - t.sort() + t = sorted(s) t = ''.join(t) return t @@ -88,4 +87,3 @@ def filter_length(d, n): eight_letters = filter_length(d, 8) print_anagram_sets_in_order(eight_letters) - diff --git a/code/analyze_book.py b/code/analyze_book.py index d8e1aaf..f78f686 100644 --- a/code/analyze_book.py +++ b/code/analyze_book.py @@ -16,7 +16,7 @@ def process_file(filename, skip_header): filename: string skip_header: boolean, whether to skip the Gutenberg header - + Returns: map from each word to the number of times it appears. """ hist = {} @@ -50,7 +50,7 @@ def process_line(line, hist): """ # replace hyphens with spaces before splitting line = line.replace('-', ' ') - + for word in line.split(): # remove punctuation and convert to lowercase word = word.strip(string.punctuation + string.whitespace) @@ -74,7 +74,7 @@ def most_common(hist): def print_most_common(hist, num=10): """Prints the most commons words in a histgram and their frequencies. - + hist: histogram (map from word to frequency num: number of words to print """ @@ -138,4 +138,3 @@ def random_word(hist): print "\n\nHere are some random words from the book" for i in range(100): print random_word(hist), - diff --git a/code/analyze_book2.py b/code/analyze_book2.py index 8fdb629..141883b 100644 --- a/code/analyze_book2.py +++ b/code/analyze_book2.py @@ -41,4 +41,3 @@ def subtract(d1, d2): print "\n\nHere are some random words from the book" for i in range(100): print random_word(hist), - diff --git a/code/analyze_book3.py b/code/analyze_book3.py index 188489a..4d7daee 100644 --- a/code/analyze_book3.py +++ b/code/analyze_book3.py @@ -34,7 +34,7 @@ def random_word(hist): freqs.append(total_freq) # choose a random value and find its location in the cumulative list - x = random.randint(0, total_freq-1) + x = random.randint(0, total_freq - 1) index = bisect(freqs, x) return words[index] @@ -59,4 +59,3 @@ def random_word(hist): print "\n\nHere are some random words from the book" for i in range(100): print random_word(hist), - diff --git a/code/birthday.py b/code/birthday.py index 015bc97..05765ea 100644 --- a/code/birthday.py +++ b/code/birthday.py @@ -9,13 +9,13 @@ import random + def has_duplicates(t): """Returns True if any element appears more than once in (t), False otherwise.""" - s = t[:] - s.sort() - for i in range(len(s)-1): - if s[i] == s[i+1]: + s = sorted(t[:]) + for i in range(len(s) - 1): + if s[i] == s[i + 1]: return True return False @@ -39,6 +39,7 @@ def count_matches(students, samples): count += 1 return count + """run the birthday simulation 1000 times and print the number of matches""" num_students = 23 num_simulations = 1000 diff --git a/code/button_demo.py b/code/button_demo.py index eeffabe..b09dbaf 100644 --- a/code/button_demo.py +++ b/code/button_demo.py @@ -12,12 +12,15 @@ g = Gui() g.title('') + def callback1(): g.bu(text='Now press me.', command=callback2) + def callback2(): g.la(text='Nice job.') + g.bu(text='Press me.', command=callback1) g.mainloop() diff --git a/code/canvas_demo.py b/code/canvas_demo.py index b525def..da0474b 100644 --- a/code/canvas_demo.py +++ b/code/canvas_demo.py @@ -14,18 +14,18 @@ world = World() canvas = world.ca(width=500, height=500, background='white') -bbox = [[-150,-110], [150, 110]] +bbox = [[-150, -110], [150, 110]] canvas.rectangle(bbox, outline='purple', width=5, fill='green') canvas.oval(bbox, outline='purple', width=5, fill='yellow') -canvas.circle([0,0], 100, outline='purple', width=5, fill='orange') +canvas.circle([0, 0], 100, outline='purple', width=5, fill='orange') canvas.line(bbox, fill='purple', width=5) photo = PhotoImage(file='allen.ppm') -image = canvas.image([0,0], image=photo) +image = canvas.image([0, 0], image=photo) bbox = image.bbox() diff --git a/code/cartalk1.py b/code/cartalk1.py index d54bc96..b74e8f1 100644 --- a/code/cartalk1.py +++ b/code/cartalk1.py @@ -8,12 +8,13 @@ http://www.cartalk.com/content/puzzler/transcripts/200725 """ + def is_triple_double(word): """Tests if a word contains three consecutive double letters.""" i = 0 count = 0 - while i < len(word)-1: - if word[i] == word[i+1]: + while i < len(word) - 1: + if word[i] == word[i + 1]: count = count + 1 if count == 3: return True @@ -37,5 +38,3 @@ def find_triple_double(): print 'three consecutive double letters.' find_triple_double() print '' - - diff --git a/code/cartalk2.py b/code/cartalk2.py index 834f7c3..c9bf95b 100644 --- a/code/cartalk2.py +++ b/code/cartalk2.py @@ -8,21 +8,24 @@ http://www.cartalk.com/content/puzzler/transcripts/200803 """ + def has_palindrome(i, start, len): """return True if the integer i, when written as a string, contains a palindrome with length (len), starting at index (start). """ - s = str(i)[start:start+len] + s = str(i)[start:start + len] return s[::-1] == s - + + def check(i): """check whether the integer (i) has the properties described in the puzzler """ - return (has_palindrome(i, 2, 4) and - has_palindrome(i+1, 1, 5) and - has_palindrome(i+2, 1, 4) and - has_palindrome(i+3, 0, 6)) + return (has_palindrome(i, 2, 4) and + has_palindrome(i + 1, 1, 5) and + has_palindrome(i + 2, 1, 4) and + has_palindrome(i + 3, 0, 6)) + def check_all(): """enumerate the six-digit numbers and print any that satisfy the @@ -34,8 +37,7 @@ def check_all(): print i i = i + 1 + print 'The following are the possible odometer readings:' check_all() print - - diff --git a/code/cartalk3.py b/code/cartalk3.py index e14ffda..41eb01d 100644 --- a/code/cartalk3.py +++ b/code/cartalk3.py @@ -8,6 +8,7 @@ http://www.cartalk.com/content/puzzler/transcripts/200813 """ + def str_fill(i, len): """return the integer (i) written as a string with at least (len) digits""" @@ -17,7 +18,7 @@ def str_fill(i, len): def are_reversed(i, j): """ return True if the integers i and j, written as strings, are the reverse of each other""" - return str_fill(i,2) == str_fill(j,2)[::-1] + return str_fill(i, 2) == str_fill(j, 2)[::-1] def num_instances(diff, flag=False): @@ -28,7 +29,11 @@ def num_instances(diff, flag=False): count = 0 while True: mother = daughter + diff - if are_reversed(daughter, mother) or are_reversed(daughter, mother+1): + if are_reversed( + daughter, + mother) or are_reversed( + daughter, + mother + 1): count = count + 1 if flag: print daughter, mother @@ -36,7 +41,7 @@ def num_instances(diff, flag=False): break daughter = daughter + 1 return count - + def check_diffs(): """enumerate the possible differences in age between mother @@ -50,6 +55,7 @@ def check_diffs(): print diff, n diff = diff + 1 + print 'diff #instances' check_diffs() diff --git a/code/circle_demo.py b/code/circle_demo.py index dda821b..8eec19c 100644 --- a/code/circle_demo.py +++ b/code/circle_demo.py @@ -14,26 +14,28 @@ canvas = g.ca(width=500, height=500, bg='white') circle = None + def callback1(): """called when the user presses 'Create circle' """ global circle - circle = canvas.circle([0,0], 100) + circle = canvas.circle([0, 0], 100) + def callback2(): """called when the user presses 'Change color' """ # if the circle hasn't been created yet, do nothing - if circle == None: + if circle is None: return # get the text from the entry and try to change the circle's color color = entry.get() try: circle.config(fill=color) - except TclError, message: + except TclError as message: # probably an unknown color name print message - + # create the widgets g.bu(text='Create circle', command=callback1) diff --git a/code/color_list.py b/code/color_list.py index ec5ab91..2db564f 100644 --- a/code/color_list.py +++ b/code/color_list.py @@ -769,6 +769,7 @@ """ + def make_color_dict(colors=COLORS): """Returns a dictionary that maps color names to RGB strings. diff --git a/code/color_space.py b/code/color_space.py index 13b4ba2..c3cef3d 100644 --- a/code/color_space.py +++ b/code/color_space.py @@ -4,7 +4,7 @@ Copyright 2010 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html -This module uses color_list and Visual Python to +This module uses color_list and Visual Python to draw the X11 colors as spheres in 3-D RGB space. The size of the spheres (can be) proportional to the distance @@ -31,6 +31,7 @@ import sys from visual import * + def draw_spheres(rgbs, radius=10): """rgbs is a dictionary that maps from an rgb tuple to a list of color names. rgb values are in the range 0-255. @@ -43,12 +44,13 @@ def draw_spheres(rgbs, radius=10): spheres = [] for rgb, names in rgbs: pos = vector(rgb) - color = pos/255.0 + color = pos / 255.0 obj = sphere(pos=pos, radius=radius, color=color) obj.names = names spheres.append(obj) return spheres + def find_nearest_neighbor(s, spheres): """of the objects in (spheres) find the one closest to s and return a tuple (distance, closest_object) @@ -56,6 +58,7 @@ def find_nearest_neighbor(s, spheres): t = [(mag(s.pos - s2.pos), s2) for s2 in spheres if s2 is not s] return min(t) + def set_size(spheres, factor=0.7): """for each sphere, find d, the distance to the nearest neighbor and set radius = factor * d @@ -64,19 +67,20 @@ def set_size(spheres, factor=0.7): d, n = find_nearest_neighbor(s, spheres) s.radius = factor * d + def find_biggest_hole(spheres): """of the web safe colors, find the one whose nearest neighbor is the farthest. the answer is (51, 51, 255) or #3333ff which is a nive shade of blue that deserves a name. """ - s = sphere(color=(1,1,1)) + s = sphere(color=(1, 1, 1)) t = range(0, 256, 51) res = [] for r in t: for g in t: for b in t: - pos = (r,g,b) + pos = (r, g, b) s.pos = pos d, n = find_nearest_neighbor(s, spheres) print d, pos @@ -86,7 +90,8 @@ def find_biggest_hole(spheres): print 'winner', d, pos s.pos = pos s.radius = d - s.color = vector(pos)/255.0 + s.color = vector(pos) / 255.0 + def find_closest_sphere(m, spheres): """given the mouse information in (m), find the closest @@ -98,7 +103,7 @@ def find_closest_sphere(m, spheres): t = [] for obj in spheres: - d = obj.pos-c # vector from camera to object + d = obj.pos - c # vector from camera to object dist = dot(d, r) # distance from the camera proj = dist * r # projection of d onto ray off = mag(d - proj) # perp dist of object from ray line @@ -114,15 +119,17 @@ def find_closest_sphere(m, spheres): else: return None + def toggle_label(obj): """add or remove the label from a color sphere """ try: obj.label.visible ^= 1 - except: - obj.label = label(pos=obj.pos, text=obj.names[0], - xoffset=8, yoffset=8, - space=obj.radius/2, height=10, border=6) + except BaseException: + obj.label = label(pos=obj.pos, text=obj.names[0], + xoffset=8, yoffset=8, + space=obj.radius / 2, height=10, border=6) + def main(script, *args): """create the display and wait for user events @@ -141,14 +148,14 @@ def main(script, *args): # add an entry for the biggest unnamed color in X11 space name = 'allen blue' - rgbs.append(((51,51,255), [name])) + rgbs.append(((51, 51, 255), [name])) # draw the spheres spheres = draw_spheres(rgbs) if 'resize' in args: set_size(spheres) - #find_biggest_hole(spheres) + # find_biggest_hole(spheres) print """ Left-click on a sphere to see the color name(s). @@ -159,13 +166,14 @@ def main(script, *args): """ # wait for mouse clicks - while 1: - if scene.mouse.clicked: - m = scene.mouse.getclick() - obj = find_closest_sphere(m, spheres) - if obj: - print ', '.join(obj.names) - toggle_label(obj) + while True: + if scene.mouse.clicked: + m = scene.mouse.getclick() + obj = find_closest_sphere(m, spheres) + if obj: + print ', '.join(obj.names) + toggle_label(obj) + if __name__ == '__main__': main(*sys.argv) diff --git a/code/do_four.py b/code/do_four.py index 32225ff..3f835ef 100644 --- a/code/do_four.py +++ b/code/do_four.py @@ -7,20 +7,25 @@ """ + def do_twice(f, arg): f(arg) f(arg) + def print_twice(arg): print arg print arg + do_twice(print_twice, 'spam') print '' + def do_four(f, arg): do_twice(f, arg) do_twice(f, arg) + do_four(print_twice, 'spam') print '' diff --git a/code/draggable_demo.py b/code/draggable_demo.py index 13d05da..2c99a0e 100644 --- a/code/draggable_demo.py +++ b/code/draggable_demo.py @@ -9,12 +9,14 @@ from swampy.Gui import * + class Draggable(Item): """A Canvas Item with bindings for dragging and dropping. Given an item, Draggable(item) creates bindings and returns a Draggable object with the same canvas and tag as the original. """ + def __init__(self, item): self.canvas = item.canvas self.tag = item.tag @@ -31,7 +33,7 @@ def select(self, event): self.fill = self.cget('fill') self.config(fill='orange') - + def drag(self, event): """Move this item using the pixel coordinates in the event object.""" # see how far we have moved @@ -42,7 +44,7 @@ def drag(self, event): self.dragx = event.x self.dragy = event.y - # move the item + # move the item self.move(dx, dy) def drop(self, event): @@ -54,22 +56,25 @@ def drop(self, event): g = Gui() ca = g.ca(width=500, height=500, bg='white') + def make_circle(event): """Makes a circle item at the location of a button press.""" pos = ca.canvas_coords([event.x, event.y]) item = ca.circle(pos, 5, fill='red') item = Draggable(item) + ca.bind('', make_circle) + def make_text(event=None): """Pressing Return in the Entry makes a text item.""" text = en.get() - item = ca.text([0,0], text) + item = ca.text([0, 0], text) item = Draggable(item) -g.row([0,1]) +g.row([0, 1]) bu = g.bu('Make text item:', make_text) en = g.en() en.bind('', make_text) diff --git a/code/exercise-2.1.py b/code/exercise-2.1.py index 0fb59a5..abc156e 100644 --- a/code/exercise-2.1.py +++ b/code/exercise-2.1.py @@ -24,7 +24,7 @@ """ -print 01, 010, 0100, 01000 +print 0o1, 0o10, 0o100, 0o1000 """ @@ -51,4 +51,3 @@ In Python 3, this "feature" has been removed. """ - diff --git a/code/find_duplicates.py b/code/find_duplicates.py index d07b73a..d62656a 100644 --- a/code/find_duplicates.py +++ b/code/find_duplicates.py @@ -9,6 +9,7 @@ import os + def walk(dirname): """Finds the names of all files in dirname and its subdirectories. diff --git a/code/flower.py b/code/flower.py index 92e5773..5058b14 100644 --- a/code/flower.py +++ b/code/flower.py @@ -26,7 +26,7 @@ def petal(t, r, angle): """ for i in range(2): arc(t, r, angle) - lt(t, 180-angle) + lt(t, 180 - angle) def flower(t, n, r, angle): @@ -39,7 +39,7 @@ def flower(t, n, r, angle): """ for i in range(n): petal(t, r, angle) - lt(t, 360.0/n) + lt(t, 360.0 / n) def move(t, length): diff --git a/code/grid.py b/code/grid.py index 46e5cdf..07ae234 100644 --- a/code/grid.py +++ b/code/grid.py @@ -10,38 +10,47 @@ # here is a mostly-straightforward solution to the # two-by-two version of the grid. + def do_twice(f): f() f() + def do_four(f): do_twice(f) do_twice(f) + def print_beam(): print '+ - - - -', + def print_post(): print '| ', + def print_beams(): do_twice(print_beam) print '+' + def print_posts(): do_twice(print_post) print '|' + def print_row(): print_beams() do_four(print_posts) + def print_grid(): do_twice(print_row) print_beams() + print_grid() - + # here is a less-straightforward solution to the # four-by-four grid @@ -51,42 +60,55 @@ def one_four_one(f, g, h): do_four(g) h() + def print_plus(): print '+', + def print_dash(): print '-', + def print_bar(): print '|', + def print_space(): print ' ', + def print_end(): print + def nothing(): "do nothing" + def print1beam(): one_four_one(nothing, print_dash, print_plus) + def print1post(): one_four_one(nothing, print_space, print_bar) + def print4beams(): one_four_one(print_plus, print1beam, print_end) + def print4posts(): one_four_one(print_bar, print1post, print_end) + def print_row(): one_four_one(nothing, print4posts, print4beams) + def print_grid(): one_four_one(print4beams, print_row, nothing) + print_grid() comment = """ diff --git a/code/has_duplicates.py b/code/has_duplicates.py index ce4afcd..491668e 100644 --- a/code/has_duplicates.py +++ b/code/has_duplicates.py @@ -43,4 +43,3 @@ def has_duplicates2(t): print has_duplicates2(t) t.append(1) print has_duplicates2(t) - diff --git a/code/image_demo.py b/code/image_demo.py index f79ffb0..67ca355 100644 --- a/code/image_demo.py +++ b/code/image_demo.py @@ -7,6 +7,8 @@ """ +import ImageTk +import Image as PIL from swampy.Gui import * from Tkinter import PhotoImage @@ -15,10 +17,8 @@ g.bu(image=photo) canvas = g.ca(width=300) -canvas.image([0,0], image=photo) +canvas.image([0, 0], image=photo) -import Image as PIL -import ImageTk image = PIL.open('allen.png') photo2 = ImageTk.PhotoImage(image) diff --git a/code/interlock.py b/code/interlock.py index 28842f0..a2951bf 100644 --- a/code/interlock.py +++ b/code/interlock.py @@ -18,8 +18,8 @@ def interlock(word_list, word): """ evens = word[::2] odds = word[1::2] - return in_bisect(word_list, evens) and in_bisect(word_list, odds) - + return in_bisect(word_list, evens) and in_bisect(word_list, odds) + def interlock_general(word_list, word, n=3): """Checks whether a reversed word appears in word_list. @@ -33,11 +33,11 @@ def interlock_general(word_list, word, n=3): if not in_bisect(word_list, inter): return False return True - + if __name__ == '__main__': word_list = make_word_list() - + for word in word_list: if interlock(word_list, word): print word, word[::2], word[1::2] @@ -45,5 +45,3 @@ def interlock_general(word_list, word, n=3): for word in word_list: if interlock_general(word_list, word, 3): print word, word[0::3], word[1::3], word[2::3] - - diff --git a/code/invert_dict.py b/code/invert_dict.py index 01588e3..53a0957 100644 --- a/code/invert_dict.py +++ b/code/invert_dict.py @@ -7,6 +7,7 @@ """ + def invert_dict(d): """Inverts a dictionary, returning a map from val to a list of keys. @@ -28,4 +29,3 @@ def invert_dict(d): inverse = invert_dict(d) for val, keys in inverse.iteritems(): print val, keys - diff --git a/code/koch.py b/code/koch.py index 23e0969..6d4ef6b 100644 --- a/code/koch.py +++ b/code/koch.py @@ -17,10 +17,10 @@ def koch(t, n): """Draws a koch curve with length n.""" - if n<3: + if n < 3: fd(t, n) return - m = n/3.0 + m = n / 3.0 koch(t, m) lt(t, 60) koch(t, m) diff --git a/code/letters.py b/code/letters.py index 5e44e91..1fa9fff 100644 --- a/code/letters.py +++ b/code/letters.py @@ -23,23 +23,27 @@ def fdlt(t, n, angle=90): fd(t, n) lt(t, angle) + def fdbk(t, n): """forward and back, ending at the original position""" fd(t, n) bk(t, n) + def skip(t, n): """lift the pen and move""" pu(t) fd(t, n) pd(t) + def stump(t, n, angle=90): """make a vertical line and leave the turtle at the top, facing right""" lt(t) fd(t, n) rt(t, angle) + def hollow(t, n): """move the turtle vertically and leave it at the top, facing right""" lt(t) @@ -58,11 +62,12 @@ def post(t, n): fdbk(t, n) rt(t) + def beam(t, n, height): """make a horizontal line at the given height and return.""" - hollow(t, n*height) + hollow(t, n * height) fdbk(t, n) - hollow(t, -n*height) + hollow(t, -n * height) def hangman(t, n, height): @@ -73,9 +78,10 @@ def hangman(t, n, height): stump(t, n * height) fdbk(t, n) lt(t) - bk(t, n*height) + bk(t, n * height) rt(t) + def diagonal(t, x, y): """make a diagonal line to the given x, y offsets and return""" from math import atan2, sqrt, pi @@ -85,17 +91,19 @@ def diagonal(t, x, y): fdbk(t, dist) rt(t, angle) + def vshape(t, n, height): - diagonal(t, -n/2, height*n) - diagonal(t, n/2, height*n) + diagonal(t, -n / 2, height * n) + diagonal(t, n / 2, height * n) + def bump(t, n, height): - """make a bump with radius n at height*n + """make a bump with radius n at height*n """ - stump(t, n*height) - arc(t, n/2.0, 180) + stump(t, n * height) + arc(t, n / 2.0, 180) lt(t) - fdlt(t, n*height+n) + fdlt(t, n * height + n) """ @@ -110,159 +118,189 @@ def bump(t, n, height): """ + def draw_a(t, n): - diagonal(t, n/2, 2*n) + diagonal(t, n / 2, 2 * n) beam(t, n, 1) skip(t, n) - diagonal(t, -n/2, 2*n) + diagonal(t, -n / 2, 2 * n) + def draw_b(t, n): bump(t, n, 1) bump(t, n, 0) - skip(t, n/2) + skip(t, n / 2) + def draw_c(t, n): hangman(t, n, 2) fd(t, n) + def draw_d(t, n): - bump(t, 2*n, 0) + bump(t, 2 * n, 0) skip(t, n) + def draw_ef(t, n): hangman(t, n, 2) hangman(t, n, 1) + def draw_e(t, n): draw_ef(t, n) fd(t, n) + def draw_f(t, n): draw_ef(t, n) skip(t, n) + def draw_g(t, n): hangman(t, n, 2) - fd(t, n/2) - beam(t, n/2, 2) - fd(t, n/2) + fd(t, n / 2) + beam(t, n / 2, 2) + fd(t, n / 2) post(t, n) + def draw_h(t, n): - post(t, 2*n) + post(t, 2 * n) hangman(t, n, 1) skip(t, n) - post(t, 2*n) + post(t, 2 * n) + def draw_i(t, n): beam(t, n, 2) - fd(t, n/2) - post(t, 2*n) - fd(t, n/2) + fd(t, n / 2) + post(t, 2 * n) + fd(t, n / 2) + def draw_j(t, n): beam(t, n, 2) - arc(t, n/2, 90) - fd(t, 3*n/2) - skip(t, -2*n) + arc(t, n / 2, 90) + fd(t, 3 * n / 2) + skip(t, -2 * n) rt(t) - skip(t, n/2) + skip(t, n / 2) + def draw_k(t, n): - post(t, 2*n) + post(t, 2 * n) stump(t, n, 180) - vshape(t, 2*n, 0.5) + vshape(t, 2 * n, 0.5) fdlt(t, n) skip(t, n) + def draw_l(t, n): - post(t, 2*n) + post(t, 2 * n) fd(t, n) + def draw_n(t, n): - post(t, 2*n) + post(t, 2 * n) skip(t, n) - diagonal(t, -n, 2*n) - post(t, 2*n) + diagonal(t, -n, 2 * n) + post(t, 2 * n) + def draw_m(t, n): - post(t, 2*n) + post(t, 2 * n) draw_v(t, n) - post(t, 2*n) + post(t, 2 * n) + def draw_o(t, n): skip(t, n) circle(t, n) skip(t, n) + def draw_p(t, n): bump(t, n, 1) - skip(t, n/2) + skip(t, n / 2) + def draw_q(t, n): draw_o(t, n) - diagonal(t, -n/2, n) + diagonal(t, -n / 2, n) + def draw_r(t, n): draw_p(t, n) - diagonal(t, -n/2, n) + diagonal(t, -n / 2, n) + def draw_s(t, n): - fd(t, n/2) - arc(t, n/2, 180) - arc(t, n/2, -180) - fdlt(t, n/2, -90) - skip(t, 2*n) + fd(t, n / 2) + arc(t, n / 2, 180) + arc(t, n / 2, -180) + fdlt(t, n / 2, -90) + skip(t, 2 * n) lt(t) + def draw_t(t, n): beam(t, n, 2) - skip(t, n/2) - post(t, 2*n) - skip(t, n/2) + skip(t, n / 2) + post(t, 2 * n) + skip(t, n / 2) + def draw_u(t, n): - post(t, 2*n) + post(t, 2 * n) fd(t, n) - post(t, 2*n) + post(t, 2 * n) + def draw_v(t, n): - skip(t, n/2) + skip(t, n / 2) vshape(t, n, 2) - skip(t, n/2) + skip(t, n / 2) + def draw_w(t, n): draw_v(t, n) draw_v(t, n) + def draw_x(t, n): - diagonal(t, n, 2*n) + diagonal(t, n, 2 * n) skip(t, n) - diagonal(t, -n, 2*n) + diagonal(t, -n, 2 * n) + def draw_v(t, n): - skip(t, n/2) - diagonal(t, -n/2, 2*n) - diagonal(t, n/2, 2*n) - skip(t, n/2) + skip(t, n / 2) + diagonal(t, -n / 2, 2 * n) + diagonal(t, n / 2, 2 * n) + skip(t, n / 2) + def draw_y(t, n): - skip(t, n/2) + skip(t, n / 2) stump(t, n) vshape(t, n, 1) rt(t) fdlt(t, n) - skip(t, n/2) + skip(t, n / 2) + def draw_z(t, n): beam(t, n, 2) - diagonal(t, n, 2*n) + diagonal(t, n, 2 * n) fd(t, n) + def draw_(t, n): # draw a space skip(t, n) + if __name__ == '__main__': world = TurtleWorld() diff --git a/code/lumpy_demo1.py b/code/lumpy_demo1.py index 63e59ce..8fe5f53 100644 --- a/code/lumpy_demo1.py +++ b/code/lumpy_demo1.py @@ -21,4 +21,3 @@ lumpy.object_diagram() print_diagram(lumpy, 'lumpydemo1.eps') - diff --git a/code/lumpy_demo2.py b/code/lumpy_demo2.py index 107c975..59bd28e 100644 --- a/code/lumpy_demo2.py +++ b/code/lumpy_demo2.py @@ -11,6 +11,7 @@ from swampy.Lumpy import Lumpy + def countdown(n): if n <= 0: print 'Blastoff!' @@ -18,10 +19,9 @@ def countdown(n): print_diagram(lumpy, 'lumpydemo2.eps') else: print n - countdown(n-1) + countdown(n - 1) + lumpy = Lumpy() lumpy.make_reference() countdown(2) - - diff --git a/code/lumpy_demo3.py b/code/lumpy_demo3.py index 421136c..4654fe9 100644 --- a/code/lumpy_demo3.py +++ b/code/lumpy_demo3.py @@ -20,4 +20,3 @@ lumpy.object_diagram() print_diagram(lumpy, 'lumpydemo3.eps') - diff --git a/code/lumpy_demo4.py b/code/lumpy_demo4.py index e13140e..0fabdb5 100644 --- a/code/lumpy_demo4.py +++ b/code/lumpy_demo4.py @@ -7,8 +7,10 @@ """ +from swampy.Lumpy import Lumpy from lumpy_demo import * + def histogram(s): d = dict() for c in s: @@ -18,6 +20,7 @@ def histogram(s): d[c] += 1 return d + def invert_dict(d): inv = dict() for key in d: @@ -28,7 +31,6 @@ def invert_dict(d): inv[val].append(key) return inv -from swampy.Lumpy import Lumpy lumpy = Lumpy() lumpy.make_reference() @@ -38,4 +40,3 @@ def invert_dict(d): lumpy.object_diagram() print_diagram(lumpy, 'lumpydemo4.eps') - diff --git a/code/lumpy_demo5.py b/code/lumpy_demo5.py index 8d3808c..cff5ea7 100644 --- a/code/lumpy_demo5.py +++ b/code/lumpy_demo5.py @@ -13,12 +13,15 @@ from swampy.Lumpy import Lumpy + class Point(object): """Represents a point in 2-D space.""" + class Rectangle(object): """Represents a rectangle.""" + lumpy = Lumpy() lumpy.make_reference() @@ -33,6 +36,3 @@ class Rectangle(object): lumpy.object_diagram() print_diagram(lumpy, 'lumpydemo5.eps') - - - diff --git a/code/lumpy_demo6.py b/code/lumpy_demo6.py index 8a573a0..91bc85f 100644 --- a/code/lumpy_demo6.py +++ b/code/lumpy_demo6.py @@ -14,12 +14,15 @@ lumpy = Lumpy() lumpy.make_reference() + class Point(object): """Represents a point in 2-D space.""" + class Rectangle(object): """Represents a rectangle.""" + def instantiate(constructor): """Instantiates a new object.""" obj = constructor() @@ -27,8 +30,5 @@ def instantiate(constructor): print_diagram(lumpy, 'lumpydemo6.eps') return obj -point = instantiate(Point) - - - +point = instantiate(Point) diff --git a/code/lumpy_demo7.py b/code/lumpy_demo7.py index b72324e..db57578 100644 --- a/code/lumpy_demo7.py +++ b/code/lumpy_demo7.py @@ -13,12 +13,15 @@ from swampy.Lumpy import Lumpy + class Point(object): """Represents a point in 2-D space.""" + class Rectangle(object): """Represents a rectangle.""" + lumpy = Lumpy() lumpy.make_reference() @@ -31,6 +34,3 @@ class Rectangle(object): lumpy.class_diagram() print_diagram(lumpy, 'lumpydemo7.eps') - - - diff --git a/code/lumpy_demo8.py b/code/lumpy_demo8.py index eba7a76..8117024 100644 --- a/code/lumpy_demo8.py +++ b/code/lumpy_demo8.py @@ -22,6 +22,3 @@ lumpy.class_diagram() print_diagram(lumpy, 'lumpydemo8.eps') - - - diff --git a/code/lumpy_diag05.py b/code/lumpy_diag05.py index d647e04..d7b3f43 100644 --- a/code/lumpy_diag05.py +++ b/code/lumpy_diag05.py @@ -24,13 +24,13 @@ for i in range(3): x = i + def function(parameter): local = parameter + 1 # draw the state while function is running lumpy.object_diagram() -variable = 3 -function(variable+1) - +variable = 3 +function(variable + 1) diff --git a/code/markov.py b/code/markov.py index bb0a8ab..9efaf49 100644 --- a/code/markov.py +++ b/code/markov.py @@ -48,7 +48,7 @@ def process_word(word, order=2): word: string order: integer - During the first few iterations, all we do is store up the words; + During the first few iterations, all we do is store up the words; after that we start adding entries to the dictionary. """ global prefix @@ -74,13 +74,13 @@ def random_text(n=100): """ # choose a random prefix (not weighted by frequency) start = random.choice(suffix_map.keys()) - + for i in range(n): suffixes = suffix_map.get(start, None) - if suffixes == None: + if suffixes is None: # if the start isn't in map, we got to the end of the # original text, so we have to start again. - random_text(n-i) + random_text(n - i) return # choose a random suffix @@ -104,9 +104,9 @@ def main(name, filename='', n=100, order=2, *args): try: n = int(n) order = int(order) - except: + except BaseException: print 'Usage: randomtext.py filename [# of words] [prefix length]' - else: + else: process_file(filename, order) random_text(n) diff --git a/code/menubutton_demo.py b/code/menubutton_demo.py index 7b619dc..cfd4d43 100644 --- a/code/menubutton_demo.py +++ b/code/menubutton_demo.py @@ -15,10 +15,12 @@ colors = ['red', 'green', 'blue'] mb = g.mb(text=colors[0]) + def set_color(color): print color mb.config(text=color) + for color in colors: g.mi(mb, text=color, command=Callable(set_color, color)) diff --git a/code/metathesis.py b/code/metathesis.py index 444eb10..d88a9d1 100644 --- a/code/metathesis.py +++ b/code/metathesis.py @@ -9,6 +9,7 @@ from anagram_sets import * + def metathesis_pairs(d): """Print all pairs of words that differ by swapping two letters. diff --git a/code/most_frequent.py b/code/most_frequent.py index ebcf91a..4cdcb53 100644 --- a/code/most_frequent.py +++ b/code/most_frequent.py @@ -30,7 +30,7 @@ def most_frequent(s): res.append(x) return res - + def make_histogram(s): """Make a map from letters to number of times they appear in s. diff --git a/code/pace_calc.py b/code/pace_calc.py index fb2c138..74521ac 100644 --- a/code/pace_calc.py +++ b/code/pace_calc.py @@ -17,7 +17,7 @@ km_per_mile = 1.61 km = 10 -miles = km / km_per_mile +miles = km / km_per_mile pace = minutes / miles mph = miles / hours diff --git a/code/pack_demo.py b/code/pack_demo.py index fdedc3e..6f3e04b 100644 --- a/code/pack_demo.py +++ b/code/pack_demo.py @@ -11,6 +11,7 @@ from swampy.Gui import * + def figure1(): print 'Figure 17.3 a' @@ -29,6 +30,7 @@ def figure2(): g.mainloop() + def figure3(): print 'Figure 17.3 c' @@ -142,6 +144,7 @@ def pack(**options): g.mainloop() + def figure11(): print 'Figure 17.7 c' @@ -155,6 +158,7 @@ def figure11(): g.mainloop() + def figure12(): print 'Figure 17.7 d' @@ -162,6 +166,7 @@ def figure12(): g.mainloop() + def figure13(): print 'Figure 17.7 e' @@ -170,7 +175,9 @@ def figure13(): g.mainloop() + def main(): figure8() + main() diff --git a/code/palindrome_soln.py b/code/palindrome_soln.py index 39409f5..d91569f 100644 --- a/code/palindrome_soln.py +++ b/code/palindrome_soln.py @@ -7,6 +7,7 @@ """ + def first(word): """Returns the first character of a string.""" return word[0] @@ -35,4 +36,3 @@ def is_palindrome(word): print is_palindrome('bob') print is_palindrome('otto') print is_palindrome('redivider') - diff --git a/code/pi.py b/code/pi.py index 5a79e4d..029f0e1 100644 --- a/code/pi.py +++ b/code/pi.py @@ -15,7 +15,7 @@ def factorial(n): if n == 0: return 1 else: - recurse = factorial(n-1) + recurse = factorial(n - 1) result = n * recurse return result @@ -23,21 +23,23 @@ def factorial(n): def estimate_pi(): """Computes an estimate of pi. - Algorithm due to Srinivasa Ramanujan, from + Algorithm due to Srinivasa Ramanujan, from http://en.wikipedia.org/wiki/Pi """ total = 0 k = 0 factor = 2 * math.sqrt(2) / 9801 while True: - num = factorial(4*k) * (1103 + 26390*k) - den = factorial(k)**4 * 396**(4*k) + num = factorial(4 * k) * (1103 + 26390 * k) + den = factorial(k)**4 * 396**(4 * k) term = factor * num / den total += term - - if abs(term) < 1e-15: break + + if abs(term) < 1e-15: + break k += 1 return 1 / total + print estimate_pi() diff --git a/code/pie.py b/code/pie.py index 4b0781e..63ea36d 100644 --- a/code/pie.py +++ b/code/pie.py @@ -26,10 +26,10 @@ def draw_pie(t, n, r): """ polypie(t, n, r) pu(t) - fd(t, r*2 + 10) + fd(t, r * 2 + 10) pd(t) - + def polypie(t, n, r): """Draws a pie divided into radial segments. @@ -39,7 +39,7 @@ def polypie(t, n, r): """ angle = 360.0 / n for i in range(n): - isosceles(t, r, angle/2) + isosceles(t, r, angle / 2) lt(t, angle) @@ -56,11 +56,11 @@ def isosceles(t, r, angle): rt(t, angle) fd(t, r) - lt(t, 90+angle) - fd(t, 2*y) - lt(t, 90+angle) + lt(t, 90 + angle) + fd(t, 2 * y) + lt(t, 90 + angle) fd(t, r) - lt(t, 180-angle) + lt(t, 180 - angle) # create the world and bob @@ -83,4 +83,3 @@ def isosceles(t, r, angle): world.canvas.dump() wait_for_user() - diff --git a/code/pil_demo.py b/code/pil_demo.py index 2de80ea..b1c8938 100644 --- a/code/pil_demo.py +++ b/code/pil_demo.py @@ -9,11 +9,13 @@ """ -import os, sys +import os +import sys from swampy.Gui import * import Image as PIL # to avoid name conflict with Tkinter import ImageTk + def show_image(filename): # tkpi has to be global because otherwise it gets # deallocated when the function ends. @@ -23,7 +25,7 @@ def show_image(filename): tkpi = ImageTk.PhotoImage(image) g.la(image=tkpi) + g = Gui() show_image('allen.png') g.mainloop() - diff --git a/code/polygon.py b/code/polygon.py index 3977761..f08b0d8 100644 --- a/code/polygon.py +++ b/code/polygon.py @@ -47,7 +47,7 @@ def polygon(t, n, length): n: number of sides length: length of each side. """ - angle = 360.0/n + angle = 360.0 / n polyline(t, n, length, angle) @@ -65,9 +65,9 @@ def arc(t, r, angle): # making a slight left turn before starting reduces # the error caused by the linear approximation of the arc - lt(t, step_angle/2) + lt(t, step_angle / 2) polyline(t, n, step_length, step_angle) - rt(t, step_angle/2) + rt(t, step_angle / 2) def circle(t, r): @@ -84,7 +84,7 @@ def circle(t, r): # or being imported, in which case don't. if __name__ == '__main__': - world = TurtleWorld() + world = TurtleWorld() bob = Turtle() bob.delay = 0.001 diff --git a/code/reducible.py b/code/reducible.py index 6713039..d7caa53 100644 --- a/code/reducible.py +++ b/code/reducible.py @@ -7,6 +7,7 @@ """ + def make_word_dict(): """Reads the words in words.txt and returns a dictionary that contains the words as keys.""" @@ -36,13 +37,13 @@ def is_reducible(word, word_dict): Also adds an entry to the memo dictionary. - A string is reducible if it has at least one child that is + A string is reducible if it has at least one child that is reducible. The empty string is also reducible. word: string word_dict: dictionary with words as keys """ - # if have already checked this word, return the answer + # if have already checked this word, return the answer if word in memo: return memo[word] @@ -67,7 +68,7 @@ def children(word, word_dict): """ res = [] for i in range(len(word)): - child = word[:i] + word[i+1:] + child = word[:i] + word[i + 1:] if child in word_dict: res.append(child) return res diff --git a/code/remote_object.py b/code/remote_object.py index c43d4d8..4a792fb 100644 --- a/code/remote_object.py +++ b/code/remote_object.py @@ -22,6 +22,7 @@ class MyThread(threading.Thread): """MyThread is a wrapper for threading.Thread that improves the syntax for creating and starting threads.""" + def __init__(self, target, *args): threading.Thread.__init__(self, target=target, args=args) self.start() @@ -40,7 +41,7 @@ class Watcher: I have only tested this on Linux. I would expect it to work on OS X and not work on Windows.""" - + def __init__(self, callback=None): """ Creates a child thread, which returns. The parent thread waits for a KeyboardInterrupt and then kills @@ -50,7 +51,7 @@ def __init__(self, callback=None): if self.child == 0: return else: - self.watch(callback) + self.watch(callback) def watch(self, callback=None): """Waits for a KeyboardInterrupt and then kills the child process.""" @@ -117,16 +118,16 @@ def query(self, name, group=None): def create_group(self, name): """Creates a group with the given name.""" self.ns.createGroup(name) - + def delete_group(self, name): """Deletes a group with the given name.""" self.ns.deleteGroup(name) - + def get_remote_object_list(self, prefix='', group=None): """Returns a list of the remote objects in the given group that start with the given prefix.""" t = self.ns.list(group) - u = [s for (s, n) in t if n==1 and s.startswith(prefix)] + u = [s for (s, n) in t if n == 1 and s.startswith(prefix)] return u def clear(self, prefix='', group=None): @@ -135,13 +136,14 @@ def clear(self, prefix='', group=None): t = self.ns.list(group) for (s, n) in t: - if not s.startswith(prefix): continue - if n==1: + if not s.startswith(prefix): + continue + if n == 1: if group: s = '%s.%s' % (group, s) print 'Unregistering', s - self.ns.unregister(s) - + self.ns.unregister(s) + class RemoteObject(Pyro.core.ObjBase): """Extends Pyro.core.ObjBase and provides a higher level of abstraction. @@ -158,15 +160,15 @@ def __init__(self, name=None, ns=None): """ Pyro.core.ObjBase.__init__(self) - if name == None: + if name is None: name = 'remote_object' + str(id(self)) - self.name=name - - if ns == None: + self.name = name + + if ns is None: ns = NameServer() self.connect(ns, name) - + def connect(self, ns, name): """Connects to the given name server with the given name.""" @@ -189,19 +191,19 @@ def requestLoop(self): """Runs the request loop until an exception occurs.""" try: self.pyro_daemon.requestLoop() - except: + except BaseException: self.cleanup() - if sys.exc_type != KeyboardInterrupt: - raise sys.exc_type, sys.exc_value + if sys.exc_info()[0] != KeyboardInterrupt: + raise sys.exc_info()[0], sys.exc_info()[1] def cleanup(self): """Removes this object from the name server.""" print 'Shutting down remote object', self.name try: self.pyro_daemon.disconnect(self) - except: + except BaseException: print "Did not disconnect cleanly." - raise sys.exc_type, sys.exc_value + raise sys.exc_info()[0], sys.exc_info()[1] self.stopLoop() self.pyro_daemon.shutdown() @@ -209,7 +211,7 @@ def threadLoop(self): """Runs the request loop in a separate thread.""" self.thread = threading.Thread(target=self.stoppableLoop) self.thread.start() - + def stoppableLoop(self): """Run handleRequests until another thread clears self.running.""" self.running = True diff --git a/code/reverse_pair.py b/code/reverse_pair.py index f00c6fc..d473760 100644 --- a/code/reverse_pair.py +++ b/code/reverse_pair.py @@ -18,13 +18,11 @@ def reverse_pair(word_list, word): """ rev_word = word[::-1] return in_bisect(word_list, rev_word) - + if __name__ == '__main__': word_list = make_word_list() - + for word in word_list: if reverse_pair(word_list, word): print word, word[::-1] - - diff --git a/code/sed.py b/code/sed.py index 9334693..8d93221 100644 --- a/code/sed.py +++ b/code/sed.py @@ -30,7 +30,7 @@ def sed(pattern, replace, source, dest): fin.close() fout.close() - except: + except BaseException: print 'Something went wrong.' diff --git a/code/spiral.py b/code/spiral.py index 8f1b3ff..f6f63fc 100644 --- a/code/spiral.py +++ b/code/spiral.py @@ -43,4 +43,3 @@ def draw_spiral(t, n, length=3, a=0.1, b=0.0002): draw_spiral(bob, n=1000) wait_for_user() - diff --git a/code/stack_diagram.py b/code/stack_diagram.py index 737a0a6..1787e16 100644 --- a/code/stack_diagram.py +++ b/code/stack_diagram.py @@ -15,19 +15,22 @@ def b(z): print z, prod return prod + def a(x, y): x = x + 1 lumpy.object_diagram() return x * y + def c(x, y, z): total = x + y + z square = b(total)**2 return square + lumpy = Lumpy() lumpy.make_reference() x = 1 y = x + 1 -print c(x, y+3, x+y) +print c(x, y + 3, x + y) diff --git a/code/structshape.py b/code/structshape.py index 15f9916..f25dd5c 100644 --- a/code/structshape.py +++ b/code/structshape.py @@ -12,6 +12,7 @@ """ + def structshape(ds): """Returns a string that describes the shape of a data structure. @@ -37,7 +38,7 @@ def structshape(ds): for k, v in ds.items(): keys.add(structshape(k)) vals.add(structshape(v)) - rep = '%s of %d %s->%s' % (typename, len(ds), + rep = '%s of %d %s->%s' % (typename, len(ds), setrep(keys), setrep(vals)) return rep @@ -82,7 +83,7 @@ def setrep(s): return rep else: return '(' + rep + ')' - return + return def append(res, typestr, count): @@ -105,10 +106,10 @@ def append(res, typestr, count): if __name__ == '__main__': - t = [1,2,3] + t = [1, 2, 3] print structshape(t) - t2 = [[1,2], [3,4], [5,6]] + t2 = [[1, 2], [3, 4], [5, 6]] print structshape(t2) t3 = [1, 2, 3, 4.0, '5', '6', [7], [8], 9] @@ -126,7 +127,7 @@ class Point: lt = zip(t, s) print structshape(lt) - d = dict(lt) + d = dict(lt) print structshape(d) it = iter('abc') diff --git a/code/thread.py b/code/thread.py index bd8ccc2..0a07962 100644 --- a/code/thread.py +++ b/code/thread.py @@ -8,15 +8,16 @@ from threading import Thread from time import sleep + def counter(xs, delay=1): for x in xs: print x sleep(delay) + # one thread counts backwards, fast t = Thread(target=counter, args=[range(100, 1, -1), 0.25]) t.start() # the other thread count forwards, slow counter(range(1, 100), 1) - diff --git a/code/typewriter.py b/code/typewriter.py index 20f0359..13e8e0a 100644 --- a/code/typewriter.py +++ b/code/typewriter.py @@ -12,11 +12,11 @@ that contains functions with names like draw_a, draw_b, etc. """ -from time import sleep try: +from swampy.TurtleWorld import * +from time import sleep # see if Swampy is installed as a package - from swampy.TurtleWorld import * except ImportError: # otherwise see if the modules are on the PYTHONPATH from TurtleWorld import * @@ -24,10 +24,10 @@ # check if the reader has provided letters.py try: from letters import * -except ImportError, e: +except ImportError as e: message = e.args[0] if message.startswith('No module'): - raise ImportError(message + + raise ImportError(message + '\nYou have to provide a module named letters.py') @@ -60,10 +60,10 @@ def keypress(event): # check if the user pressed return if event.char in ['\n', '\r']: - teleport(bob, -180, bob.y-size*3) + teleport(bob, -180, bob.y - size * 3) bob.busy = False return - + # figure out which function to call, and call it try: func = eval('draw_' + event.char) @@ -74,7 +74,7 @@ def keypress(event): func(bob, size) - skip(bob, size/2) + skip(bob, size / 2) bob.busy = False diff --git a/code/unstable_sort.py b/code/unstable_sort.py index 3e73d00..5608941 100644 --- a/code/unstable_sort.py +++ b/code/unstable_sort.py @@ -22,7 +22,7 @@ def sort_by_length(words): """ t = [] for word in words: - t.append((len(word), word)) + t.append((len(word), word)) t.sort(reverse=True) @@ -49,7 +49,7 @@ def sort_by_length_random(words): """ t = [] for word in words: - t.append((len(word), random.random(), word)) + t.append((len(word), random.random(), word)) t.sort(reverse=True) diff --git a/code/walk.py b/code/walk.py index d9df4d9..a1f2f01 100644 --- a/code/walk.py +++ b/code/walk.py @@ -9,6 +9,7 @@ import os + def walk(dirname): """Prints the names of all files in dirname and its subdirectories. @@ -36,4 +37,3 @@ def walk2(dirname): if __name__ == '__main__': walk('.') walk2('.') - diff --git a/code/widget_demo.py b/code/widget_demo.py index cb64027..0a5ab41 100644 --- a/code/widget_demo.py +++ b/code/widget_demo.py @@ -36,11 +36,13 @@ la2 = g.la(text='') + def press_me(): """this callback gets invoked when the user presses the button""" text = en.get() la2.configure(text=text) + # bu is for button bu = g.bu(text='Press me', command=press_me) @@ -62,15 +64,17 @@ def press_me(): # mb is for menubutton mb = g.mb(text='Choose a color') + def set_color(color): ca.itemconfig(item2, fill=color) + # mi is for menuitem for color in ['red', 'green', 'blue']: # Callable is an object that can be used like a function g.mi(mb, color, command=Callable(set_color, color)) - + g.endcol() @@ -78,23 +82,27 @@ def set_color(color): g.col() + def get_selection(): t = lb.curselection() try: index = int(t[0]) color = lb.get(index) return color - except: + except BaseException: return None + def print_selection(event): print get_selection() + def apply_color(): color = get_selection() if color: ca.itemconfig(item1, fill=color) + la = g.la(text='List of colors:') g.row() @@ -151,7 +159,7 @@ def apply_color(): # gr is for grid: start a grid with three columns # the rweights control how extra space is divided among the rows -g.gr(3, rweights=[1,1,1]) +g.gr(3, rweights=[1, 1, 1]) for i in range(1, 10): g.bu(text=str(i)) @@ -163,9 +171,11 @@ def apply_color(): g.col() + def print_var(obj): print obj.var.get() + g.la(text='Font:') fontsize = IntVar() diff --git a/code/wordlist.py b/code/wordlist.py index 8e85fc9..06083f1 100644 --- a/code/wordlist.py +++ b/code/wordlist.py @@ -45,4 +45,3 @@ def make_word_list2(): print len(t) print t[:10] print elapsed_time, 'seconds' - diff --git a/code/zip_code.py b/code/zip_code.py index 0ad9b6a..6fa0774 100644 --- a/code/zip_code.py +++ b/code/zip_code.py @@ -15,8 +15,8 @@ """ -import urllib +import urllib zipcode = '02492' url = 'http://uszip.com/zip/' + zipcode @@ -26,9 +26,9 @@ line = line.strip() if 'Population' in line: print line - if 'Longitude' in line: + if 'Longitude' in line: print line - if 'Latitude' in line: + if 'Latitude' in line: print line conn.close()