我有 2 個串列,一個有 12 個元素,一個有 3 個子串列。
a = [1,2,3,4,5,6,7,8,9,10,11,12]
b = [[],[],[]]
我需要撰寫 Python 代碼來生成所有可能的方式,其中 a 中的 12 個元素可以分布在 b 中的子串列中。有 3^12(剛超過一百萬)組合。例如,一些可能的組合如下:
[[1,2,3,4,5,6,7,8,9,10,11,12],[],[]]
[[1,2,3,4],[5,6],[7,8,9,10,11,12]]
[[1,4,12],[2,3,9,11],[5,6,7,8,10]]
串列中的順序無關緊要。我試過使用一些 itertools 函式,例如排列和組合,但它們似乎沒有做我想要的。我試過
buildings = list(range(1,13)) #assign each building a unique id
building_arrangement = [list(range(1,13)),[],[]] # quarries, factories, markets
all_arrangements.append(building_arrangement)
combos = itertools.combinations(buildings, 3)
for combo in combos:
print(combo)
但是上面的方法似乎是將 12 個數字中的每一個單獨組合起來,而不是將完整的 12 個數字視為一個集合并找到每個可以制作的唯一集合。我不確定這是否可以通過任何預先存在的庫來完成,itertools 似乎沒有提供一種方法來從我在檔案中看到的內容來做到這一點,但我可能是錯的。
uj5u.com熱心網友回復:
請注意,每個組合都可以用 m 元數進行編碼,其中 m 是子串列的數量。迭代所有 n 位 m-ary 數字(其中 n 是元素的數量)將解決問題:
N = 12
M = 3
for n in range(N**M):
combination = [[] for __ in range(M)]
for i in range(N):
combination[n // 3**i % 3].append(i)
print(combination)
uj5u.com熱心網友回復:
您可以使用遞回生成器函式:
a = [1,2,3,4,5,6,7,8,9,10,11,12]
def groups(d, n, c = []):
if not d and len(c) == n:
yield c
elif d:
for i, j in enumerate(d):
if not c or len(c) 1 <= n:
yield from groups(d[:i] d[i 1:], n, c [[j]])
if c:
yield from groups(d[:i] d[i 1:], n, c[:-1] [[*c[-1], j]])
def results(d, n):
s = []
for i in groups(d, n):
if (k:=[*map(sorted, i)]) not in s:
yield k
s.append(k)
r = results(a, 3)
for _ in range(10): #first 10 results
print(next(r))
輸出:
[[1], [2], [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]
[[1], [2, 3], [4, 5, 6, 7, 8, 9, 10, 11, 12]]
[[1], [2, 3, 4], [5, 6, 7, 8, 9, 10, 11, 12]]
[[1], [2, 3, 4, 5], [6, 7, 8, 9, 10, 11, 12]]
[[1], [2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
[[1], [2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12]]
[[1], [2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12]]
[[1], [2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12]]
[[1], [2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12]]
[[1], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12]]
uj5u.com熱心網友回復:
還有為什么不試試itertool recipes,powerset()
pip install more-itertools
然后,
from more_itertools import recipes
a = [1,2,3,4,5,6,7,8,9,10,11,12]
tuples = recipes.powerset(a)
for tuple in tuples:
print(tuple)
這將從提供??給它的迭代中創建所有可能的集合。您可以使用不同的功能將其分成 3 個串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/373309.html
