Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!

# Untitled

By: a guest on May 3rd, 2008  |  syntax: Python  |  size: 1.20 KB  |  views: 64  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
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.
21.     for a, b in combine(add, mul):
22.       yield a + "+" + b
24.
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