我想code了一些简单和Python的识别值的组合,从列表中该款项为定义的值,在一定的耐受性。
I'm trying to code up something simple and pythonic to identify combinations of values from a list which sum to a defined value, within some tolerance.
例如:
如果 A = [0.4,2,3,1.4,2.6,6.3]
和目标值为 5 +/- 0.5
,那么我想输出(2,3),(1.4,2.6),(2,2.6),(0.4,2,3),(0.4,3,1.4 )
等,如果没有组合找到那么函数应该返回0或无,或类似的东西。
if A=[0.4,2,3,1.4,2.6,6.3]
and the target value is 5 +/- 0.5
, then the output I want is (2,3), (1.4,2.6), (2,2.6), (0.4,2,3), (0.4,3,1.4)
etc. if no combinations are found then the function should return 0 or none or something similar.
任何帮助将是很大的AP preciated。
Any help would be greatly appreciated.
下面是一个递归的方法:
Here's a recursive approach:
# V is the target value, t is the tolerance
# A is the list of values
# B is the subset of A that is still below V-t
def combination_in_range(V, t, A, B=[]):
for i,a in enumerate(A):
if a > V+t: # B+[a] is too large
continue
# B+[a] can still be a possible list
B.append(a)
if a >= V-t: # Found a set that works
print B
# recursively try with a reduced V
# and a shortened list A
combination_in_range(V-a, t, A[i+1:], B)
B.pop() # drop [a] from possible list
A=[0.4, 2, 3, 1.4, 2.6, 6.3]
combination_in_range(5, 0.5, A)
上一篇:除去加权有向图周期周期