2

I am looking for a shorter (probably recursive) way to write the following:

for x1 in range(10):
    for x2 in range(10 - x1):
        for x3 in range(10 - (x1 + x2)):
            for x4 in range(10 - (x1 + x2 + x3)):
                print(x1,x2,x3,x4)
2

2 Answers 2

2

What you want is a filtered product. Use itertools for that, no need for recursion.

from itertools import product

n=10
for x1, x2, x3, x4 in filter(lambda x: sum(x) < n, product(range(n), repeat=4)):
    print(x1, x2, x3, x4)

Output:

0 0 0 0
0 0 0 1
0 0 0 2
0 0 0 3
0 0 0 4
0 0 0 5
0 0 0 6
0 0 0 7
0 0 0 8
0 0 0 9
0 0 1 0
...
9 0 0 0
Sign up to request clarification or add additional context in comments.

8 Comments

aren't you forgetting about some possibilities? combinations_with_replacement preserve the order, you should use product: you can have 0001 but never 1000
@cards yes it's actually a product, there are 10**4 possibilities, I corrected the answer
but I think it is still not enough, there are 10**4 possibilities assuming that the index space a fixed size of 10, but it reducing so one should be filter such product
I didn't get your last point
for example with your code you will get: if (x1, x2, x3, x4) == (3, 9, 9, 9): print('not possible!!') but this tuple should NOT exist in the original problem
|
0

Here's some hints to get you going, and then if you get stuck you can ask more pointed questions: To find a recursive formulation, first give a high-level description of what you want to achieve, then see if you can identify the recursive nature of the problem. To do that, you'll probably need to generalize your problem.

So let me give you the high-level description of your problem, in its concrete form:

"Print out all 4-tuples of non-negative numbers such that their sum is 4."

I'd generalize that to

"Print out all n-tuples of non-negative numbers such that their sum is k."

Now try if you can solve that task recursively.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.