簡體   English   中英

用它們所有可能組合的 2 位數字隨機填充列表,以便列表元素的總和給出一個給定的數字

[英]Fill a list randomly with 2 digits of all possible combinations of them so that the sum of the elements of the list gives a given number

我知道我提到的標題喚起了這里已經提到的許多其他主題(如庫 itertools),但沒有一個可以給我一個解決方案。 我的問題並不難理解。 我有 2 個數字(比如 1 和 2),我想把它們放在一個列表中,這樣列表中數字的總和給我一個數字(比如 5),我需要知道這個列表中所有可能的組合。 例如 :

a = 1
b = 2
L = [1, 2, 2] -> 5
L = [1, 1, 1, 1, 1] -> 5
L = [1, 1, 1, 2] -> 5
.
.
.

我希望能夠描述我的問題,我感到失望已經超過 2 天了。

祝大家有個美好的一天

稍微修改一下我在提議的副本中展示的想法:

from collections import Counter

def subset_sum(vals, target):
    counts = [[Counter()]] + [[] for _ in range(target)]
    for val in vals:
        for i in range(val, target + 1):
            counts[i] += [c + Counter({val: 1}) for c in counts[i-val]]
    return counts[target]

這給出了結果:

>>> for counts in subset_sum(vals=(1, 2), target=5):
...     L = [*counts.elements()]
...     print(L, "->", sum(L))
[1, 1, 1, 1, 1] -> 5
[1, 1, 1, 2] -> 5
[1, 2, 2] -> 5

暫無
暫無

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

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