我正在尝试编写一些简单和Pythonic的代码,以从列表中识别出一些值的组合,这些组合在一定的公差范围内总和为定义的值。
例如:
如果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或不返回或类似的内容。
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)
任何帮助将不胜感激。
这是一种递归方法:
# 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)