Mar*_*ark 3 python algorithm python-2.7
我正在尝试编写简单和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或无或类似的东西.
任何帮助将不胜感激.
看一眼 itertools.combinations
def first_attempt(A=A):
for i in xrange(1,len(A)+1):
print [comb
for comb in list(itertools.combinations(A,i))
if 4.5 < sum(map(float, comb)) < 5.5
]
## -- End pasted text --
In [1861]: %timeit first_attempt
10000000 loops, best of 3: 29.4 ns per loop
Run Code Online (Sandbox Code Playgroud)
输出 -
In [1890]: first_attempt(A=A)
[]
[(2, 3), (2, 2.6)]
[(0.4, 2, 3), (0.4, 2, 2.6), (0.4, 3, 1.4)]
[]
[]
[]
Run Code Online (Sandbox Code Playgroud)