Skip to content

Instantly share code, notes, and snippets.

@quantumelixir
Created January 15, 2011 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quantumelixir/780824 to your computer and use it in GitHub Desktop.
Save quantumelixir/780824 to your computer and use it in GitHub Desktop.
Compare two methods of computing partitions using Python's "yield" construct
#!/usr/bin/env python
def partitions(n, curtot = 0, cur = []) :
if curtot == n :
yield cur
t = cur[-1] if cur else 1
for i in xrange(t, n - curtot + 1) :
for j in partitions(n, curtot + i, cur + [i]) :
yield j
def part(n):
# base case of recursion: zero is the sum of the empty list
if n == 0:
yield []
return
# modify partitions of n-1 to form partitions of n
for p in partitions(n-1):
yield [1] + p
if p and (len(p) < 2 or p[1] > p[0]):
yield [p[0] + 1] + p[1:]
if __name__ == '__main__':
import timeit
t1 = timeit.Timer('for i in partitions(30) : pass', 'from __main__ import partitions')
t2 = timeit.Timer('for i in part(30) : pass', 'from __main__ import part')
print t1.timeit(number=10), t2.timeit(number=10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment