数组中值的总和和条件检查 - Python
Sum of value in array and condition check - Python
我有以下变量:
arr = [50, 100, 100, 100, 200, 200]
inp = 450
在inp
变量中,我从用户那里接收数据,用户可以输入数组中最小值和最大值之间的任意值(50和750)。
我想 return 数组中的值组成的数量等于变量中的值 inp
在这种情况下 inp = 450
有两种变体:50 + 100 + 100 + 200 或 50 + 200 + 200.我只对其中一个感兴趣。
如何继续下面的代码:
import sys
arr = [50, 100, 100, 100, 200, 200]
inp = 450
sum = 0
res = []
for x in arr:
if x == inp:
res = x
print(res)
sys.exit()
sum = sum+x
res.append(x)
if sum == inp:
print(res)
sys.exit()
我循环6次就可以解决问题,但是如果数组的长度发生变化,我就得在源码上进行干预了。我正在寻找递归解决方案。
我会使用 itertools.combinations API。您还可以使用生成器来查找所有值,或者选择在第一个停止:
import itertools
def find_comb_for_sum(data, total):
for i in range(len(data)):
for comb in itertools.combinations(data, i + 1):
if sum(comb) == total:
yield comb
这将找到数组的所有组合,从每个组合的条目数量最少到最多。如果您想执行相反的操作,请反转范围 range(len(data))[::-1]
。
部分测试用例:
arr = [50, 100, 100, 100, 200, 200]
inp = 450
comb = find_comb_for_sum(arr, inp)
print(f"Matching combination for {arr} summing to {inp} is: {next(comb, None)}")
arr = [50, 100, 100, 100, 200, 200]
inp = 444
comb = find_comb_for_sum(arr, inp)
print(f"Matching combination for {arr} summing to {inp} is: {next(comb, None)}")
Matching combination for [50, 100, 100, 100, 200, 200] summing to 450 is: (50, 200, 200)
Matching combination for [50, 100, 100, 100, 200, 200] summing to 444 is: None
我有以下变量:
arr = [50, 100, 100, 100, 200, 200]
inp = 450
在inp
变量中,我从用户那里接收数据,用户可以输入数组中最小值和最大值之间的任意值(50和750)。
我想 return 数组中的值组成的数量等于变量中的值 inp
在这种情况下 inp = 450
有两种变体:50 + 100 + 100 + 200 或 50 + 200 + 200.我只对其中一个感兴趣。
如何继续下面的代码:
import sys
arr = [50, 100, 100, 100, 200, 200]
inp = 450
sum = 0
res = []
for x in arr:
if x == inp:
res = x
print(res)
sys.exit()
sum = sum+x
res.append(x)
if sum == inp:
print(res)
sys.exit()
我循环6次就可以解决问题,但是如果数组的长度发生变化,我就得在源码上进行干预了。我正在寻找递归解决方案。
我会使用 itertools.combinations API。您还可以使用生成器来查找所有值,或者选择在第一个停止:
import itertools
def find_comb_for_sum(data, total):
for i in range(len(data)):
for comb in itertools.combinations(data, i + 1):
if sum(comb) == total:
yield comb
这将找到数组的所有组合,从每个组合的条目数量最少到最多。如果您想执行相反的操作,请反转范围 range(len(data))[::-1]
。
部分测试用例:
arr = [50, 100, 100, 100, 200, 200]
inp = 450
comb = find_comb_for_sum(arr, inp)
print(f"Matching combination for {arr} summing to {inp} is: {next(comb, None)}")
arr = [50, 100, 100, 100, 200, 200]
inp = 444
comb = find_comb_for_sum(arr, inp)
print(f"Matching combination for {arr} summing to {inp} is: {next(comb, None)}")
Matching combination for [50, 100, 100, 100, 200, 200] summing to 450 is: (50, 200, 200)
Matching combination for [50, 100, 100, 100, 200, 200] summing to 444 is: None