-1

公式 我一直在寻找有效的方法来检查列表nk元素的总和是否等于x值。我认为也许在 numpy 和 intertools 库中会有所帮助。

例子:

list = [1, 0, 1, 3, 4, 2, 2]
temp = list.copy()
x = 10
result = []
import random

while sum(result) != x:
    try:
        a = random.choice(temp)
        result.append(a)
        temp.remove(a)
    except IndexError:
        temp = list.copy()
        result = []
        if sum(result) > 10:
            result = []

这对于大列表的随机选择效率不高。

4

1 回答 1

0

我认为这itertools.combinations就是你所需要的

from itertools import combinations

l = [1, 0, 1, 3, 4, 2, 2]
x = 10

for i in range(len(l)):
    for c in combinations(l, i):
        if sum(c) == x:
            print(c)
于 2018-08-19T20:45:47.777 回答