简体   繁体   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

I know that the title I mentioned evokes many other topics already mentioned here (like library itertools) but none could give me a solution.我知道我提到的标题唤起了这里已经提到的许多其他主题(如库 itertools),但没有一个可以给我一个解决方案。 My problem is not complicated to understand.我的问题并不难理解。 I have 2 digits (say 1 and 2) and I want to put them in a list so that the sum of the numbers in the list gives me a number (say 5) and I need to know all possible combinations from this list there.我有 2 个数字(比如 1 和 2),我想把它们放在一个列表中,这样列表中数字的总和给我一个数字(比如 5),我需要知道这个列表中所有可能的组合。 For example :例如 :

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

I hope to have been able to describe my problem, it's been more than 2 days that I ream disappointed.我希望能够描述我的问题,我感到失望已经超过 2 天了。

Good day to all祝大家有个美好的一天

With a slight modification of the idea I showed in the proposed duplicate:稍微修改一下我在提议的副本中展示的想法:

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]

This gives the result:这给出了结果:

>>> 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.

相关问题 列表的3位数字的所有可能组合永远都不相同 - All possible combinations for 3 digits of list never the same 计算给定列表中所有可能的组合 - Counting all possible combinations in a given list of list 查找具有给定总和的数字列表的所有组合 - Find all combinations of a list of numbers with a given sum 列表中两个元素之和的可能组合 - Possible combinations of the sum of two elements of a list 从给定列表中选择8个元素的所有组合 - Select all the combinations of 8 elements from a given list 如何从另一个元素列表中顺序填充给定长度的列表并递归找到所有可能的组合? - How to sequentially populate a list of given length from another list of elements and recursively find all possible combinations that satisfy? 结合两个列表和 output 列表 1 给定列表 2 的所有可能组合 - Combine two list and output all possible combinations of list 1 given list 2 生成列表中元素的所有可能组合 - Generate all possible combinations of elements in a list 找到给定编号的所有可能排列和组合。 使用 Python 的列表中的元素 - Find all possible permutations and combinations of given no. of elements in a list using Python 如果元素总和为给定数字,则追加到列表中 - appending in list if sum of elements makes given number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM