2 回答

TA貢獻1886條經驗 獲得超2個贊
根據描述,您需要變量“map”中提到的所有路徑的可能組合。因此,您可以使用 itertools 來獲取路徑的所有可能組合。
我想這應該對你有用:
import itertools
pattern = list(itertools.product(*map))
print(pattern)
輸出
[(1, 3, 6),
(1, 3, 7),
(1, 4, 6),
(1, 4, 7),
(1, 5, 6),
(1, 5, 7),
(2, 3, 6),
(2, 3, 7),
(2, 4, 6),
(2, 4, 7),
(2, 5, 6),
(2, 5, 7)]

TA貢獻1784條經驗 獲得超8個贊
這是一個使用遞歸的解決方案,并且不使用庫,它可以與任意數量的組一起使用
mp = [
[1,2],
[3,4,5],
[6,7]
]
def possible_path(M,index,combination):
for i in M[index]:
if index<len(M)-1:
possible_path(M,index+1,combination+[i])
else:
print(combination+[i])
possible_path(mp,0,[])
這是輸出:
[1, 3, 6]
[1, 3, 7]
[1, 4, 6]
[1, 4, 7]
[1, 5, 6]
[1, 5, 7]
[2, 3, 6]
[2, 3, 7]
[2, 4, 6]
[2, 4, 7]
[2, 5, 6]
[2, 5, 7]
添加回答
舉報