簡體   English   中英

從python中的int列表生成加法組合

[英]Generating addition combinations from an int list in python

我有一個長度未知的浮點數組。 數字范圍是0-1000。 我正在尋找從那些小於用戶定義值的數字生成所有可能的加法組合,並將它們附加到另一個列表中。 例如,如果numlist = [200,350,510]並且定義的最大值為1200,我想生成組合:

200、400(numlist [1] * 2 + numlist [2] * 0 + numlist [3] * 0),600、800、1000、1200、350、700(200 * 0 + 350 * 2 + 510 * 0) ,1050(200 * 0 + 350 * 0 + 510 * 2),510、1020、550(200 * 1 + 350 * 1),900(200 * 1 + 350 * 2)等。

該程序的目標是檢查大型浮點文件,並打印是否可以使用numlist中的數字構造單個浮點。 我認為最有效的方法是先找到所有組合,然后檢查float-combination == 0是否有系統的方法或另一種方法? numlist沒有設置長度。

這是一個動態編程示例:

def make_combo_dict(nums, max_):
    nums = sorted(set(nums))
    prev = {0: [""]}    # base state: no combinations
    for num in nums:
        nxt = defaultdict(list)
        for total, ways in prev.items():
            # k = 0
            nxt[total] = ways
            # k > 0
            max_k = (max_ - total) // num
            for k in range(1, max_k + 1):
                nxt[total + k*num].extend(
                    "{}{}{}*{}"
                    .format(way, " + " if way else "", k, num)
                    for way in ways
                )
        prev = nxt
    return prev

運行像

>>> combos = make_combo_dict([350, 200, 500, 510], 1200)

>>> for total,ways in sorted(combos.items()):
...     print("{:>4d}: {}".format(total, ", ".join(ways)))
   0: 
 200: 1*200
 350: 1*350
 400: 2*200
 500: 1*500
 510: 1*510
 550: 1*350 + 1*200
 600: 3*200
 700: 2*350
 710: 1*200 + 1*510
 750: 1*350 + 2*200
 800: 4*200
 850: 1*350 + 1*500
 860: 1*350 + 1*510
 900: 2*350 + 1*200, 2*200 + 1*500
 910: 2*200 + 1*510
 950: 1*350 + 3*200
1000: 5*200
1010: 1*500 + 1*510
1020: 2*510
1050: 3*350
1060: 1*350 + 1*200 + 1*510
1100: 2*350 + 2*200, 3*200 + 1*500
1110: 3*200 + 1*510
1150: 1*350 + 4*200
1200: 6*200, 1*200 + 2*500, 2*350 + 1*500

暫無
暫無

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

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