Improve this recursive code please!
waxmop
waxmop at sarcastic-horse.com
Tue May 6 16:48:11 EDT 2003
Steven Taschuk wrote:
<snip>
> So, instead of assigning bricks one by one, let's try assigning to
> the bins one by one. Something like this:
>
> def findarrangements(bricksleft, binsleft, bins):
> if binsleft > 1:
> # More than one bin left, and we need to distribute
> # bricksleft bricks among them.
> for n in range(bricksleft+1):
> # Find arrangements in which next bin has n bricks.
> bins.append(n)
> findarrangements(binsleft - 1, bricksleft - n, bins)
> bins.pop()
> else:
> # Only one bin left; put all remaining bricks there.
> bins.append(bricksleft)
> print tuple(binsbuilt)
>
>
I think that "binsbuilt" should just be bins, right? Here's the code that I
tried:
def findarrangements(bricksleft, binsleft, bins):
if binsleft > 1:
for n in range(bricksleft+1):
bins.append(n)
findarrangements(binsleft-1, bricksleft-n, bins)
bins.pop
else:
bins.append(bricksleft)
print tuple(bins)
bins.pop()
----- and here's the results I got:
>>> from revtupp import findarrangements
>>> bin=[]
>>> findarrangements(2,2,bin)
(0, 0, 1)
(0, 0, 1, 1)
(0, 0, 1, 1, 1)
(0, 0, 1, 1, 2, 1)
I'm still working on it; maybe I typed something in wrong.
More information about the Python-list
mailing list