簡體   English   中英

如何找到總和最接近給定數字的3個數字

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM