Created
January 15, 2011 10:34
-
-
Save quantumelixir/780824 to your computer and use it in GitHub Desktop.
Compare two methods of computing partitions using Python's "yield" construct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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