Improve this recursive code please!

waxmop waxmop at sarcastic-horse.com
Tue May 6 12:14:29 EDT 2003


Hi - I wrote a program that gets two arguments: numbricks, and numbins.
The program calculates every possible way to distribute all the bricks
into the bins, using a recursive function.

The program works ok, especially when numbricks and numbins are under 5
each.  However, I need to run this program when numbricks = 100 or more,
and I'm concerned about memory issues.

Is there a way I can avoid building a giant stack?  This program doesn't
need to run fast at all.  It just needs to run with enormous numbers of
bricks and bins, even if it takes a few hours.  I just don't want to
overload our server while it's happening.

Finally. I do have access to a beowulf cluster; is this something that
could take advantage of that?

I'm still learning python, so other comments about the code are
welcomed.  And no, this isn't a homework assignment.

The program can be run like so:

./tupp.py 4 4

or

./tupp.py -help

to get a usage message.


Here's the program:

#! /usr/bin/env python

import sys
import types
import string

def mk_tree(numbricks, numbins):
  bin = [0]*numbins
  results = {}
  mk_tree_r(numbricks, numbins, bin, results)
  tups = results.keys()
  tups.sort()
  tups.reverse()
  return tups


def mk_tree_r(numbricks, numbins, bin, results):
  if countbricks(bin) < numbricks:
    for i in range(numbins):
      bin[i] += 1
      mk_tree_r(numbricks, numbins, bin, results)
      bin[i] -= 1
  else:
    t = tuple(bin)
    results[t] = 1


def countbricks(bin):
  sum = 0
  for bricks in bin:
    if bricks:
      sum += bricks
  return sum


#main method:
def main():

  usage = """
      USAGE: python %s <number of bricks> <number of bins>
        <number of bricks> must be an integer.
        <number of bins> must also be an integer.
    """ % sys.argv[0]

  try:
    numbricks = string.atoi(sys.argv[1])
    if type(numbricks) is not types.IntType: raise
    numbins = string.atoi(sys.argv[2])
    if type(numbins) is not types.IntType: raise
  except:
    raise SystemExit, usage

  t = mk_tree(numbricks, numbins)
  f = open('tuples.txt', 'w')
  for tup in t:
    print >> f, tup
  f.close()
  print "wrote a total of %d tuples to tuples.txt" % len(t)

if __name__ == '__main__': main()







More information about the Python-list mailing list