1

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)
2
  • 8
    You might want to look into doing something else. Either recursion, or just not having such crazily nested lists. There's not really a good way to do this in exactly this way. Commented Jul 13, 2016 at 19:03
  • 2
    Probably you could use itertools.product docs.python.org/2.7/library/itertools.html#itertools.product But I agree with Morgan Thrapp, this approach seems like it probably isn't ideal. Commented Jul 13, 2016 at 19:09

1 Answer 1

3

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
  • For n = 4, this would be (A, B) X (A, B) X (A, B) X (A, B)
  • For 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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanx, this does exactly what I want it to do but I'm trying to do it without using any built in function.

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.