Partitions of an integer

George Yoshida ml at dynkin.com
Sat Jul 24 12:50:44 EDT 2004


Nick J Chackowsky wrote:
> Wrote a python script to find the partitions of an integer (a list of 
> all the ways you can express n as a sum of integers). For example, the 
> partitions of 5 are
> 5
> 4+1
> 3+2
> 2+2+1
> 3+1+1
> 2+1+1+1
> 1+1+1+1+1
> 
> My method, however, generates plenty of duplicates (note the if 
> statement to catch them). Generating the 15 partitions of 7, for 
> example, also generates 19 duplicates. Can someone spot a way to improve 
> or eliminate the duplicates?
> 
> Nick.

You should check this recipe:

Generator for integer partitions
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/218332

This is a cool example of how to use generators with recursion.
--
George



More information about the Python-list mailing list