簡體   English   中英

如何在執行 itertools.combinations 時限制列表中的元素數量?

[英]How to restrict number of elements in list while doing itertools.combinations?

嗨,我正在寫一個小項目。 我的代碼的元素之一是創建工資組合。 我嘗試做的是獲得 4 個數字(從 0.0 到 1.0)的所有可能組合,這將給我一個 1.0 的總和。 我用 step = 5 循環以使其快速。

for i in range(0,101,5):
  wage = i/100
  l_wages.append(wage)
numbers = l_wages
result = [list(seq) for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) == 1.0]
result

我想要總和為 1 的工資。我已經做到了。 我現在唯一需要做的就是在每個列表中有 4 個元素時遇到一種情況。 經常有一個 output 像“0.9,0.1”。 我希望它是“0.9,0.1,.0.0,0.0”。

希望有人能幫我解決這個問題。

如果你想采用這種格式: [0.9, 0.1, 0.0, 0.0]

這意味着值將repeat

組合的含義是它們被sorted並且它們不repeat 這是你在高中backtracking時學到的第一件事。

有一個快速的解決方案:

this solution doesnt implement combinations

l_wages = []
for i in range(0,101,5):
    wage = i/100
    l_wages.append(wage)

solutions = []
for x in l_wages:
    for y in l_wages:
        for z in l_wages:
            for w in l_wages:
                sol = [x, y, z, w]
                if sum(sol) == 1.0:
                    solutions.append(sol)

for s in solutions:
    print(s)
print(len(solutions))

output(有很多解決方案)

computation takes around 2-3 seconds (if you print them)

[0.0, 0.0, 0.0, 1.0]
[0.0, 0.0, 0.05, 0.95]
[0.0, 0.0, 0.1, 0.9]
[0.0, 0.0, 0.15, 0.85]
[0.0, 0.0, 0.2, 0.8]
[0.0, 0.0, 0.25, 0.75]
[0.0, 0.0, 0.3, 0.7]
...
...
...
[0.9, 0.0, 0.05, 0.05]
[0.9, 0.0, 0.1, 0.0]
[0.9, 0.05, 0.0, 0.05]
[0.9, 0.05, 0.05, 0.0]
[0.9, 0.1, 0.0, 0.0]
[0.95, 0.0, 0.0, 0.05]
[0.95, 0.0, 0.05, 0.0]
[0.95, 0.05, 0.0, 0.0]
[1.0, 0.0, 0.0, 0.0]
1680

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM