例如:
如果A = [0.4,2,3,1.4,2.6,6.3]并且目标值是5 / – 0.5,那么我想要的输出是(2,3),(1.4,2.6),(2,(0.4,1.4)等.如果没有找到任何组合,那么该函数应返回0或无或类似的东西.
任何帮助将不胜感激.
解决方法 这是一个递归方法:# 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-tdef 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,A[i+1:],B) B.pop() # drop [a] from possible ListA=[0.4,6.3]combination_in_range(5,0.5,A)总结
以上是内存溢出为你收集整理的python – 在list中查找与给定值相加的值全部内容,希望文章能够帮你解决python – 在list中查找与给定值相加的值所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)