0

source code of product I found here: https://docs.python.org/3/library/itertools.html#itertools.product is:

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)

I simplified it for my needs as:

def product(self, lists):
    tuples = [tuple(lst) for lst in lists]
    res = [[]]
    for tup in tuples:
        # for y in tup:
        #     for x in res:
        #         res.append(x+[y])
        res = [x+[y] for x in res for y in tup]
    return res         

I want to also take out res = [x+[y] for x in res for y in tup] out of this 1-liner.

How do I convert it to old-fashioned for loop?
My attempt is in comment above. Tried also to swap between tup and res but in both attempts Memory Limit Exceeded (in Leetcode)

Thank you

belostoky
  • 934
  • 2
  • 11
  • 22
  • Reverse the order: `for x in res: for y in tup:`... – Tomerikoo Jul 26 '22 at 11:42
  • Does this answer your question? [Understanding nested list comprehension](https://stackoverflow.com/questions/8049798/understanding-nested-list-comprehension) – Tomerikoo Jul 26 '22 at 11:43
  • I tried also swapping ```for y in tup:``` and ```for x in res:``` but still get "Memory Limit Exceeded" – belostoky Jul 27 '22 at 05:00
  • yes this post https://stackoverflow.com/questions/8049798/understanding-nested-list-comprehension answers part of my question. I guess the other part is how to handle ```res = [x+[y]...```. maybe appending `x+[y]` to res is what causing the memory exception – belostoky Jul 27 '22 at 05:01

0 Answers0