Home > other >  Simplifying nested for loops
Simplifying nested for loops

Time:09-22

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)

Thanks in advance.

CodePudding user response:

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.

CodePudding user response:

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
  • Related