-1

Basically I want something that was asked in All combinations of a list of lists, but using ONLY while or/and for loops. In the other words, without the use of itertools nor recursion.

I know many similar questions have been asked before, but unfortunately I could not find a desired answer. I have looked for some solutions which make use of both loops and recursions, but when I attempted to translate them into only loops, I found out it did not work for me. I have thought of putting for loop inside a while loop but then it works differently than using recursion, because the entire for loop finishes before another while loop starts.

I have stuck for hours, any help/hint is greatly appreciated. I am using Python 3 though!

Community
  • 1
  • 1

1 Answers1

0

Well, if you are asking for an implementation of itertools.product using only for-loops, you'll find exactly that in the documentation.

def product(*args, repeat=1):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • Assuming that args is always >, is there any way to change this so neither tuple nor yield is used? – slopys1324 Feb 18 '17 at 20:32
  • @slopys1324 Well, sure. Use `list` instead of `tuple`, and accumulate the results of the last for-loop into a list and return it instead of using yield. – juanpa.arrivillaga Feb 18 '17 at 20:35
  • Probably the last question. Is there an equivalent way of doing `[x+[y] for x in result for y in pool]` instead of putting two for-loops on one line? Thanks! – slopys1324 Feb 18 '17 at 23:38
  • I've tried myself but it ends up with an infinite loop for some reason. – slopys1324 Feb 19 '17 at 01:32