[英]how to find 3 Numbers with Sum closest to a given number
我正在尝试为该问题编写简单的代码。 如果我得到一个数组和数字,我需要找到它们的总和接近给定数字的 3 个数字。
我考虑过首先弹出最后一个数字(第一个数字),然后我将有一个没有这个数字的新数组。 所以现在我寻找第二个需要小于总和目标的数字。 所以我只取较小的数字,第二个=总和-第一个数字(但我不知道如何选择它。
最后一个数字将是third=sum-first-second
我尝试编写代码,但它不工作而且它非常基本
def f(s,target):
s=sorted(s)
print(s)
print(s[0])
closest=s[0]+s[1]+s[2]
m=s[:-1]
print(m)
for i in range(len(s)):
for j in range(len(m)):
if (closest<=target-m[0]) and s[-1] + m[j] == target:
print (m[j])
n = m[:j] + nums[j+1:]
for z in range (len(z)):
if (closest<target-n[z]) and s[-1]+ m[j]+n[z] == target:
print (n[z])
s=[4,2,12,3,4,8,14]
target=20
f(s,target)
如果您知道要在此处更改什么。 请告诉我谢谢
这是我的解决方案,我试图最大化代码的性能而不重复任何组合。 如果您有任何问题,请告诉我。 祝你好运。
def find_3(s,target):
to_not_rep=[] #This list will store all combinations without repetation
close_to_0=abs(target - s[0]+s[1]+s[2]) #initile
There_is_one=False #False: don't have a combination equal to the target yet
for s1,first_n in enumerate(s):
for s2,second_n in enumerate(s):
if (s1==s2) : continue #to not take the same index
for s3,third_n in enumerate(s):
if (s1==s3) or (s2==s3) : continue #to not take the same index
val=sorted([first_n,second_n,third_n]) #sorting
if val in to_not_rep :continue #to not repeat the same combination with diffrent positions
to_not_rep.append(val)#adding all the combinations without repetation
sum_=sum(val) #the sum of the three numbers
# Good one
if sum_==target:
print(f"Found a possibility: {val[0]} + {val[1]} + {val[2]} = {target}")
There_is_one = True
if There_is_one is False: #No need if we found combination equal to the target
# close to the target
# We know that (target - sum) should equal to 0 otherwise :
# We are looking for the sum of closet combinations(in abs value) to 0
pos_n=abs(target-sum_)
if pos_n < close_to_0:
closet_one=f"The closet combination to the target is: {val[0]} + {val[1]} + {val[2]} = {sum_} almost {target} "
close_to_0=pos_n
# Print the closet combination to the target in case we did not find a combination equal to the target
if There_is_one is False: print(closet_one)
所以我们可以测试它:
s =[4,2,3,8,6,4,12,16,30,20,5]
target=20
find_3(s,target)
#Found a possibility: 4 + 4 + 12 = 20
#Found a possibility: 2 + 6 + 12 = 20
#Found a possibility: 3 + 5 + 12 = 20
另一个测试:
s =[4,2,3,8,6,4,323,23,44]
find_3(s,target)
#The closet combination to the target is: 4 + 6 + 8 = 18 almost 20
这是一个返回所有可能性的简单解决方案。 对于您的情况,它在 0.002019 秒内完成
from itertools import combinations
import numpy as np
def f(s, target):
dic = {}
for tup in combinations(s, 3):
try:
dic[np.absolute(np.sum(tup) - target)].append(str(tup))
except KeyError:
dic[np.absolute(np.sum(tup) - target)] = [tup]
print(dic[min(dic.keys())])
使用itertools.combinations
获取数字的所有组合,而无需替换一定长度(在您的情况下为三个)。 然后取sum和target之差的绝对值最小的三元组。 min
可以带一个key
参数来指定传递给 function 的迭代的顺序。
from typing import Sequence, Tuple
def closest_to(seq: Sequence[float], target: float, length: int = 3) -> Tuple[float]:
from itertools import combinations
combs = combinations(seq, length)
diff = lambda x: abs(sum(x) - target)
return min(combs, key=diff)
closest_to([4,2,12,3,4,8,14], 20) # (4, 2, 14)
这不是最快或最有效的方法,但它在概念上简单而简短。
像这样的东西?
import math
num_find = 1448
lst_Results = []
i_Number = num_find
while i_Number > 0:
num_Exp = math.floor(math.log(i_Number) / math.log(2))
lst_Results.append(dict({num_Exp: int(math.pow(2, num_Exp))}))
i_Number = i_Number - math.pow(2, num_Exp)
print(lst_Results)
在数字序列中:例如 1、2、4、8、16、32、64、128、256、512、1024、2048 等...
前一个数字的总和永远不会大于下一个。 这给了我们组合的可能性,例如:数字:1448,除了前面的数字之和没有其他组合:8 + 32 + 128 + 256 + 1024
然后你找到总和接近提供的数字的数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.