不重复的变化
Variations without repetition
我一直在寻找有效的方法来检查列表 n 中 k 元素的 sum 是否没有重复,等于 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 = []
大列表随机选择效率不高
我认为 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)
示例:
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 = []
大列表随机选择效率不高
我认为 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)