I am implementing the Cartesian product of multiple sets in python using recursion.
Here is my implementation:
def car_two_sets(a, b):
result = []
for x in a:
for y in b:
result.append(str(x) + str(y))
return result
def car_multiple_sets(lists):
if len(lists) == 2:
return car_two_sets(lists[0], lists[1])
else:
return car_multiple_sets([car_two_sets(lists[0], lists[1])] + lists[2:])
a = [1, 2]
b = [3, 4]
c = [6, 7, 8]
lists = [a, b, c]
print(car_multiple_sets(lists))
The code works correctly, but for larger number of sets, it is slow. Any ideas on how to improve this implementation? I thought of memoization, but could not find any repetitive calculations to cache.
I do not want to use itertools functions.