Introduction: During the interview, the interviewer asked this question. It was not very good at the time. After the interview, I checked it and found that most of the blogs are implemented using toolkits, and most of the blog content is still complete. Similarly, even the numbers haven't changed, and I haven't found a few useful blogs after searching for a long time. In fact, this is also the current trend of most blogs, plagiarizing each other, without any thoughts of my own, I don't understand the meaning of writing such blogs. So I plan to implement a solution that does not use a toolkit, so with the help of someone else's blog, I realized the use of backtracking to solve the Cartesian product. Here are a few ways to solve this problem:
1. Toolkit
from itertools import product
res = list(product(['a','b],['c'],['d','e','g']))
print(res)
2. Recursive generator, this method refers to the content of the blog https://www.lfhacks.com/tech/python-recursive-generator , and the code is copied directly
def combi(seq):
if not seq:
yield []
else:
for element in seq[0]:
for rest in combi(seq[1:]):
yield [element] + rest
Test with the following code
n=[[1,2,3],[4],[5,6,7]]
print list(combi(n))
The operating mode is:
拆出第一个序列,得到1,2,3
对于1 (暂存结果[1])
拆出第2个序列,得到4
对于4 (暂存结果[1, 4])
拆出第3个序列,得到5,6,7
对于5 (暂存结果[1, 4, 5])
拆出第4个序列(空),得到(空)
把5加到(空)前面,返回结果 (返回暂存结果[1, 4, 5])
对于6 (暂存结果[1, 4, 6])
拆出第4个序列(空),得到(空)
把6加到(空)前面,返回结果 (返回暂存结果[1, 4, 6])
对于7 (暂存结果[1, 4, 7])
拆出第4个序列(空),得到(空)
把7加到(空)前面,返回结果 (返回暂存结果[1, 4, 7])
3. Implementation of the retrospective method
arr = [['a','b],['c'],['d','e','g']]
res = []
layer = len(arr)
def func(arr,index,temp,layer):
if len(temp)==layer:
res.append(temp[:])
else:
if not arr[index]:
layer -= 1
func(arr, index + 1, temp,layer)
else:
for i in range(len(arr[index])):
temp.append(arr[index][i])
func(arr,index+1,temp,layer)
temp.pop()
func(arr,0,[],layer)
print(res)
The reason for using layer here is to prevent the sub-list from appearing as an empty list. If the sub-list is not an empty list, you can add temp to the result set when the length of temp is equal to the length of arr.
Reference: https://blog.csdn.net/ylyg050518/article/details/78787432