1 #-- The Computer Language Shootout 2 #-- http://shootout.alioth.debian.org/ 3 #-- contributed by Tobias Polzin, translated from Mike Pall's Lua program 4 #-- modified by Josh Goldfoot to use ifs for the complement routine 5 6 import sys 7 8 N = int(sys.argv[1]) 9 first = None 10 second = None 11 meetings = 0 12 13 RED, BLUE, YELLOW = xrange(1,4) 14 15 #-- Create a very social creature. 16 def creature(me): 17 global N, first, second, meetings 18 met = 0 19 while 1: 20 #-- Meet another creature. 21 22 #-- Wait until meeting place clears. 23 while second: 24 yield None 25 26 other = first 27 if other: 28 #-- Hey, I found a new friend! 29 second = me 30 else: 31 # -- Sniff, nobody here (yet). 32 if N <= 0: 33 #-- Uh oh, the mall is closed. 34 meetings += met 35 yield None 36 37 # The mall was closed, so everyone is faded. 38 raise StopIteration 39 N -= 1 40 first = me 41 while not second: 42 yield None #-- Wait for another creature. 43 other = second 44 45 first = None 46 second = None 47 yield None 48 49 # perform meeting 50 met += 1 51 if me != other: 52 if me == BLUE: 53 me = other == RED and YELLOW or RED 54 elif me == RED: 55 me = other == BLUE and YELLOW or BLUE 56 elif me == YELLOW: 57 me = other == BLUE and RED or BLUE 58 59 #-- Trivial round-robin scheduler. 60 def schedule(threads): 61 global meetings 62 try: 63 while 1: 64 for thread in threads: 65 thread.next() 66 except StopIteration: 67 return meetings 68 69 def main(): 70 #-- A bunch of colorful creatures. 71 threads = [ 72 creature(BLUE), 73 creature(RED), 74 creature(YELLOW), 75 creature(BLUE) ] 76 77 print schedule(threads) 78 79 main()