Advertisement
Guest User

Untitled

a guest
May 3rd, 2008
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. from itertools import count
  2.  
  3. def numbers():
  4.   for n in count():
  5.     yield str(n)
  6.  
  7. def terms():
  8.   def parens():
  9.     for exp in expressions():
  10.       yield "(" + exp + ")"
  11.   return alternate(numbers, parens)
  12.  
  13. def mul():
  14.   def mul2():
  15.     for a, b in combine(mul, terms):
  16.       yield a + "*" + b
  17.   return alternate(terms, mul2)
  18.  
  19. def add():
  20.   def add2():
  21.     for a, b in combine(add, mul):
  22.       yield a + "+" + b
  23.   return alternate(mul, add2)
  24.  
  25. expressions = add
  26.  
  27. def alternate(s, t):
  28.   x = s()
  29.   y = t()
  30.   while True:
  31.     yield x.next()
  32.     yield y.next()
  33.  
  34. def combine(s, t):
  35.   for n in count(1):
  36.     comb = [x for x in partial_combination(s, t, n)]
  37.     #print "comb", n, comb
  38.     if len(comb) == 0:
  39.       return
  40.     else:
  41.       for p in comb:
  42.         yield p
  43.  
  44. def take_first(s, n):
  45.   x = s()
  46.   for i in range(0, n):
  47.     yield x.next()
  48.  
  49. def partial_combination(s, t, n):
  50.   vals = [val for val in take_first(s, n)]
  51.   for i in range(len(vals), n):
  52.     vals.append(None)
  53.   vals.reverse()
  54.   ygen = t()
  55.   for x in vals:
  56.     try:
  57.       y = ygen.next()
  58.       if x is not None:
  59.         yield (x, y)
  60.     except:
  61.       if x is None: return
  62.  
  63. for e in expressions():
  64.   print e
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement