Enumeration of balls in basket with a specific order

63 Views Asked by At

I'd like to enumerate the solution with a specific order. Currently, with the below code:

def balls_in_baskets(balls=1, baskets=1):
    if baskets == 1:
        yield [balls]
    elif balls == 0:
        yield [0]*baskets
    else:
        for i in range(balls+1):
            for j in balls_in_baskets(balls-i, 1):
                for k in balls_in_baskets(i, baskets-1):
                    yield j+k

x=[t for t in balls_in_baskets(3,3)][::-1]
for i in x:
    print(i)

I get this:

[0, 0, 3]
[0, 1, 2]
[0, 2, 1]
[0, 3, 0]
[1, 0, 2]
[1, 1, 1]
[1, 2, 0]
[2, 0, 1]
[2, 1, 0]
[3, 0, 0]

However, I would like this order:

[0, 0, 3]
[0, 1, 2]
[1, 0, 2]
[0, 2, 1]
[1, 1, 1]
[2, 0, 1]
[0, 3, 0]
[1, 2, 0]
[2, 1, 0]
[3, 0, 0]

How can I achieve this correct order?

1

There are 1 best solutions below

0
On BEST ANSWER

You already lose the memory-efficiency of your generator by consuming it in a list comprehension so you could also sort the result:

x = sorted(balls_in_baskets(3,3), key=lambda x: x[::-1], reverse=True)

which then prints the expected output:

[0, 0, 3]
[0, 1, 2]
[1, 0, 2]
[0, 2, 1]
[1, 1, 1]
[2, 0, 1]
[0, 3, 0]
[1, 2, 0]
[2, 1, 0]
[3, 0, 0]