[SciPy-User] Semi-OT: weekend puzzle enumerating number of balls in bins

Alan G Isaac alan.isaac at gmail.com
Mon Jan 13 01:46:28 EST 2014


I think this does what you want.
(BSD license.)
Note I left out argument error checking
for presentational clarity.

Alan


def exact_partitions(n, nbins):
   result = []
   if nbins == 1:
     result.append([n])
   else:
     for n1 in range(n+1):
       for part in exact_partitions(n-n1,nbins-1):
         result.append([n1]+part)
   return result

def all_partitions(n, nbins):
   result = []
   for n1 in range(n+1):
     result += exact_partitions(n1, nbins)
   return result



More information about the SciPy-User mailing list