Reputation: 87
I'm starting to program in python and I came across a problem that I don't know how to solve.
I have a nested for
s function, where the number of nested for
s depends on an input parameter, for example, if I have the input parameter set to 2, I have to have:
for loop1 in range (0, limit):
for loop2 in range (0, limit):
print ('loop1: {} loop2: {}'.format(loop1,loop2))
If it is set equal to 3, I must have:
for loop1 in range (0, limit):
for loop2 in range (0, limit):
for loop3 in range (0, limit):
print ('loop1: {} loop2: {} loop3 {}'.format(loop1,loop2, loop3))
The results will be:
for 2:
0,0
0,1
1,0
1,1
for 3:
0,0,0
0,0,1
0,1,0
1,0,0
...
2,2,2
And so on.
Does anyone out there have any idea how to do this?
Upvotes: 0
Views: 256
Reputation: 124
Seems like something that has to be solved with a recursive function. something like:
def loops(n,limit):
for loop in range (0, limit):
n-=1
row = [loop]
if n == 1:
...
else:
row = row + loops(n,limit)
I didn't have time to finetune, but you get the idea. If not, do some research on recursive functions.
Upvotes: 0
Reputation: 3914
This is known as a cartesian product and is available in Python via itertools.product
import itertools
for i in itertools.product(range(3), repeat=3):
print(i)
To specify many you can just enter multiple iterators.
for i in itertools.product(range(1), range(2), range(3)):
print(i)
Upvotes: 2
Reputation: 131
You can do:
import itertools
for i in itertools.product(list(range(x)), repeat=x):
print(','.join(i), end=' ')
itertools.product
returns all products of range from 0 to x - 1, then you join and print them.
Upvotes: 1
Reputation: 117856
You can use itertools.product
with the repeat
argument to generate these sequences.
from itertools import product
def gen_sequence(limit):
for vals in product(range(limit), repeat=limit):
print(','.join(str(i) for i in vals))
Example
>>> gen_sequence(2)
0,0
0,1
1,0
1,1
>>> gen_sequence(3)
0,0,0
0,0,1
0,0,2
...
2,2,0
2,2,1
2,2,2
Upvotes: 3