簡體   English   中英

如何在 python 中進行特定組合?

[英]How make a especific combinations in python?

我正在嘗試進行特定組合,以便通過添加以下規格將其加起來為“4”:

a+a+a+a+a+a+a+a = 0.5 per/unit  = (In total it sum:) 4
b+b+b+b = 1 per/unit  = (In total it sum:) 4
c+c = 2 per/unit  = (In total it sum:) 4

這樣我想知道結果並在屏幕上打印組合:

a+a+a+a+a+a+a+a = 4
a+a+a+a+a+a+b = 4
a+a+a+a+b+b = 4
a+a+b+b+b = 4
a+a+a+a+a+a+c = 4
a+a+b+c = 4
a+a+c+b = 4
b+a+a+a+a+a+a = 4
b+b+a+a+a+a = 4
b+b+b+a+a = 4
b+b+c = 4
b+c+a+a = 4
b+a+c = 4
b+c+a = 4
c+a+a+a+a = 4
c+b+a+a = 4
c+a+a+b = 4

我的代碼:

from itertools import combinations
numbers=[2,4,8]
for c in combinations(numbers, 3):
    print(c)

有沒有辦法做到這一點? 非常感謝自述文件。

我將嘗試在不提供完整代碼的情況下以教學方式回答您的問題(正如您在上面的評論中所要求的那樣)。

  1. 組合方法

直接的解決方案是只查看不同長度的數字數組的可能組合。 循環遍歷長度以及組合,您可以檢查這些元素的總和是否給出了您的解決方案。

您應該查看 function itertools.combinations_with_replacement ,因為它允許每個元素多次出現。

from itertools import combinations_with_replacement

numbers=[2,4,8]
for length in [3]:
   for c in combinations_with_replacement(numbers, length):
      print(c, f"sum {sum(c)}")

> (2, 2, 2) sum 6
> (2, 2, 4) sum 8
> (2, 2, 8) sum 12
> (2, 4, 4) sum 10
> (2, 4, 8) sum 14
> (2, 8, 8) sum 18
> (4, 4, 4) sum 12
> (4, 4, 8) sum 16
> (4, 8, 8) sum 20
> (8, 8, 8) sum 24

您必須相應地指定長度數組並添加一個 if 子句進行打印。

  1. 功能方法:

假設您要查找的 function 定義為def calcComb(sum,numbers): ...它返回您嘗試過的一串組合。

此問題的典型功能解決方案是遞歸調用內部 function rec(sumRest,numRest,textComb)來跟蹤您構建的總和以及您正在測試的組合(此處為字符串格式)。 骨骼結構類似於:

def rec(sumRest,numRest,textComb):
 if  ... :  return ... 
 elif ... : return ...
 else :
    newText = ...
    return rec(sumRest-numRest[0],numRest,textComb+newText) 
          + rec(sumRest,numRest[1:],textComb) 

編輯:

上述方法是問題的直接實現,並沒有在性能方面進行優化。 如果您的問題擴大,您可能有興趣保存先前計算步驟(動態方法)的 state 或將中間結果緩存在字典中(備忘錄)。

暫無
暫無

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

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