Reputation: 125
Is it possible to write a function that adds more for
loops to a nested loop. So lets say I have a function for_loops(3)
.
def for_loops(n):
a = []
for add_v in range(n):
a.append("AB")
for i in range(len(a[0])):
for j in range(len(a[1])):
for k in range(len(a[2])):
print(a[0][i]+" "+a[1][j]+" "+a[2][k])
for_loops(3)
then for_loops(4)
def for_loops(n):
a = []
for add_v in range(n):
a.append("AB")
for i in range(len(a[0])):
for j in range(len(a[1])):
for k in range(len(a[2])):
for l in range(len(a[3])):
print(a[0][i]+" "+a[1][j]+" "+a[2][k]+" "+a[3][l])
for_loops(4)
Upvotes: 1
Views: 53
Reputation: 63737
You can achieve a similar result using itertools.product
which generates a Cartesian product
def for_loops(n):
from itertools import product
for row in product("AB", repeat = n):
print " ".join(row)
The way it works is, given a set, it will generate the Cartesian product of n cardinality i.e.
(A, B) X (A, B) X (A, B) .... n
n = 4
, this would be (A, B) X (A, B) X (A, B) X (A, B)
n = 3
, this would be (A, B) X (A, B) X (A, B)
And example run with n = 4
is shown below, which matches with the result you have from the 4 nested loop
>>> for_loops(4)
A A A A
A A A B
A A B A
A A B B
A B A A
A B A B
A B B A
A B B B
B A A A
B A A B
B A B A
B A B B
B B A A
B B A B
B B B A
B B B B
Edit 1
Thanx, this does exactly what I want it to do but I'm trying to do it without using any built in function. –
If you do not want to use any builtin function, the following might be an alternate approach for you
def for_loops(n):
for i in range(2**n):
print " ".join("AB"[int(j)] for j in "{:04b}".format(i))
Upvotes: 3