我在 python 中創建“Boggle”,我有一個表示游戲板上坐標的元組串列:
all_coordinates = [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2), (0, 3), (1, 3), (2, 3)]
我正在嘗試創建一個新的元組串列串列,這些串列將代表板上所有可能的路徑。
它看起來像這樣:
[[(0,0),(1,0)], ... , [(0,0),(1,0),(2,0),(2,1)] , ... , [(2, 1), (2, 2), (2, 3)], ...]
我嘗試使用itertools.combinationsanditertools.permutations但它似乎沒有完成這項作業,例如以下路徑:
[(2,1),(1,1),(1,0),(2,0)]
沒有出現在串列中。
這個特定的函式不一定要輸出“有效”路徑(有效 = 每次水平、垂直或對角線移動一步),只需輸出代表棋盤的元組的所有可能組合。我有一個函式可以檢查某個路徑是否回傳有效單詞。我正在嘗試列印出在板上回傳有效單詞的所有可能路徑。
uj5u.com熱心網友回復:
itertools.permutations確實產生了所有的排列,包括[(2,1),(1,1),(1,0),(2,0)]你說缺少的排列。請注意,每次呼叫permutations都會為您提供特定長度的所有排列:
>>> all_coordinates = [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2), (0, 3), (1, 3), (2, 3)]
>>> from itertools import permutations
>>> ((2,1),(1,1),(1,0),(2,0)) in permutations(all_coordinates, 4)
True
如果您想查看從長度 2 到長度 4 的所有排列,請嘗試:
for k in range(2, 5):
for p in permutations(all_coordinates, k):
print(p)
結果序列很長;正如其他人指出的那樣,您可能想提出另一種方法來生成僅包含相鄰坐標的路徑(例如,廣度優先搜索)。
(編輯)只是為了好玩,這里有一個非常快速的 DFS 方法,通過僅查看相鄰坐標來構建長度為 4 的所有路徑:
>>> def print_paths(path):
... print(path)
... if len(path) >= 4:
... return
... x, y = path[-1]
... for dx in range(-1, 2):
... for dy in range(-1, 2):
... c = x dx, y dy
... if c not in path and c in all_coordinates:
... print_paths(path [c])
...
>>> print_paths([(2, 1)])
[(2, 1)]
[(2, 1), (1, 0)]
[(2, 1), (1, 0), (0, 0)]
[(2, 1), (1, 0), (0, 0), (0, 1)]
[(2, 1), (1, 0), (0, 0), (1, 1)]
[(2, 1), (1, 0), (0, 1)]
[(2, 1), (1, 0), (0, 1), (0, 0)]
[(2, 1), (1, 0), (0, 1), (0, 2)]
[(2, 1), (1, 0), (0, 1), (1, 1)]
[(2, 1), (1, 0), (0, 1), (1, 2)]
[(2, 1), (1, 0), (1, 1)]
[(2, 1), (1, 0), (1, 1), (0, 0)]
[(2, 1), (1, 0), (1, 1), (0, 1)]
[(2, 1), (1, 0), (1, 1), (0, 2)]
[(2, 1), (1, 0), (1, 1), (1, 2)]
[(2, 1), (1, 0), (1, 1), (2, 0)]
[(2, 1), (1, 0), (1, 1), (2, 2)]
[(2, 1), (1, 0), (2, 0)]
[(2, 1), (1, 0), (2, 0), (1, 1)]
[(2, 1), (1, 1)]
[(2, 1), (1, 1), (0, 0)]
[(2, 1), (1, 1), (0, 0), (0, 1)]
[(2, 1), (1, 1), (0, 0), (1, 0)]
[(2, 1), (1, 1), (0, 1)]
[(2, 1), (1, 1), (0, 1), (0, 0)]
[(2, 1), (1, 1), (0, 1), (0, 2)]
[(2, 1), (1, 1), (0, 1), (1, 0)]
[(2, 1), (1, 1), (0, 1), (1, 2)]
[(2, 1), (1, 1), (0, 2)]
[(2, 1), (1, 1), (0, 2), (0, 1)]
[(2, 1), (1, 1), (0, 2), (0, 3)]
[(2, 1), (1, 1), (0, 2), (1, 2)]
[(2, 1), (1, 1), (0, 2), (1, 3)]
[(2, 1), (1, 1), (1, 0)]
[(2, 1), (1, 1), (1, 0), (0, 0)]
[(2, 1), (1, 1), (1, 0), (0, 1)]
[(2, 1), (1, 1), (1, 0), (2, 0)]
(...)
uj5u.com熱心網友回復:
itertools.product() 正是你正在尋找的。
>>> import itertools
>>> tuple1 = ("A", "B", "C")
>>> tuple2 = ("D", "E", "F")
>>> list(itertools.product(tuple1, tuple2))
[('A', 'D'), ('A', 'E'), ('A', 'F'), ('B', 'D'), ('B', 'E'), ('B', 'F'), ('C', 'D'), ('C', 'E'), ('C', 'F')]
>>> [''.join(x) for x in itertools.product(tuple1, tuple2)]
['AD', 'AE', 'AF', 'BD', 'BE', 'BF', 'CD', 'CE', 'CF']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400225.html
上一篇:如何在特定節點停止深度優先搜索
