# Python Examples # Mainly from www.python.org documentation # Numbers 3.4 4**6 1/2 1./2 # Strings "hello"+" world" "hi"*3 "hello"[2] "hello"[2:] "hello"[-3:] "hello"[:3] "hello"[1:3] len("hello") # Lists a = [99, "bottles of beer", ["on", "the", "wall"]] b = [1,"hi"] a+b b*3 a[1:2] # ['bottles of beer'] a[1:2] = ['bottles','of','beer'] a del a[-1] a = range(5) # [0,1,2,3,4] a.append(5) # [0,1,2,3,4,5] a.pop() # [0,1,2,3,4] #5 a.insert(0, 5.5) # [5.5,0,1,2,3,4] a.pop(0) # [0,1,2,3,4] #5.5 a.reverse() # [4,3,2,1,0] a.sort() # [0,1,2,3,4] # Dictionaries d = {"duck": "eend", "water": "water"} d["duck"] del d["water"] d["hi"]="foo" d d.keys() d.values() d.items() # Tuples (immutable lists) t=("hello","world") t[0] 1,2 # parens optional (1,) # singleton w/trailing comma () # empty tuple # If, for, indentation for i in range(20): if i%3 == 0: i if i%5 == 0: print "Bingo!" print "---" # Functions def gcd(a,b): "greatest common divisor" while a != 0: a,b=b%a,a return b # Lambda abstractions/higher-order programming s = lambda x: x*x s(5) map(s,range(4)) curry = lambda f: lambda x: lambda y: f(x,y) squarelist = curry(map)(s) squarelist(range(5)) # Classes class Stack: "A well-known data structure" # doc string def __init__(self): # constructor self.items = [] def push(self, x): self.items.append(x) # the sky is the limit def pop(self): return self.items.pop() # what happens if it's empty? def empty(self): return len(self.items) == 0 s= Stack() s.empty() s.push(1) s.empty() s.push("hi") s.pop() s.items s.pop() s.empty() s.pop() class EStack: "An encapsulated stack" # doc string def __init__(self): # constructor self.__items = [] def push(self, x): self.__items.append(x) # the sky is the limit def pop(self): return self.__items.pop() # what happens if it's empty? def empty(self): return len(self.__items) == 0 es = EStack() es.push(0) es.__items % AttributeError es._EStack__items % Still reachable... class FancyStack(Stack): "stack with added ability to inspect inferior stack items" def peek(self, n): "peek(0) returns top; peek(-1) returns item below that; etc." size = len(self.items) assert 0 <= -n < size # test precondition return self.items[-1+n] f=FancyStack() for i in range(5): f.push(i) # why is this empty line needed? f.pop() f.peek(0) f.peek(-1) class LimitedStack(FancyStack): "fancy stack with limit on stack size" def __init__(self, limit): self.limit = limit FancyStack.__init__(self) # base class constructor def push(self, x): assert len(self.items) < self.limit FancyStack.push(self, x) # "super" method call l = LimitedStack(3) l.push(1) l.push(2) l.push(3) l.peek(0) l.peek(-2) l.push(4) l.__doc__ # exception handling def printdiv(x): try: print 1./x except ZeroDivisionError, message: print "Can't divide by zero:" print message printdiv(3) printdiv(0) # exception raising class FullStackException(Exception): 'Full Stack Exception' class LimitedStack(FancyStack): "fancy stack with limit on stack size" def __init__(self, limit): self.limit = limit FancyStack.__init__(self) # base class constructor def push(self, x): if len(self.items) >= self.limit: raise FullStackException, "Maximum stack size reached" FancyStack.push(self, x) # "super" method call l = LimitedStack(3) l.push(1) l.push(2) l.push(3) l.peek(0) l.peek(-2) l.push(4) # threads import threading class PrintThread(threading.Thread): def __init__(self,frequency,name): self.frequency=frequency self.name=name threading.Thread.__init__(self) def run(self): for i in range(self.frequency): print self.name for t in range(10): PrintThread(t,t).start()