Product of lists

TODO: Index accounting is incorrect


In [3]:
from functools import reduce

In [4]:
def product_naive(*xs):
    o = []
    lens = [len(x) for x in xs]
    indices = [0] * len(xs)
    current_pos = len(lens) - 1
    
    for _ in range(reduce(lambda x, y: x * y, lens)):
        tmp = []
        for i, ind in enumerate(indices):
            tmp.append(xs[i][ind])
        o.append(tuple(tmp))
        if indices[current_pos] == lens[current_pos] - 1:
            indices[current_pos] = 0
            for i_inner in range(current_pos + 1, len(lens)):
                indices[i_inner] = 0
                
            current_pos += 1
            indices[current_pos] += 1
        else:
            indices[current_pos] += 1
            
    return o

In [5]:
test_cases = [
    [[1, 2], [3, 4]],
    [[1, 2], [3, 4], [5, 6]],
    [[1, 2, 3], [4, 5, 6]],
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
]
[product_naive(*test_case) == list(product(*test_case))
     for test_case in test_cases]


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-25d7e0ae4232> in <module>()
      6 ]
      7 [product_naive(*test_case) == list(product(*test_case))
----> 8      for test_case in test_cases]

<ipython-input-5-25d7e0ae4232> in <listcomp>(.0)
      6 ]
      7 [product_naive(*test_case) == list(product(*test_case))
----> 8      for test_case in test_cases]

<ipython-input-4-e2e81cedeab9> in product_naive(*xs)
     16 
     17             current_pos += 1
---> 18             indices[current_pos] += 1
     19         else:
     20             indices[current_pos] += 1

IndexError: list index out of range

In [ ]: