I am trying to write a function that gets a list of numbers and an integer and returns a tuple that containing pair of numbers from the list whose sum is the must closest to the number the function received. for example: closest([10,22,28,29,30,40], 54) --> (22,30) It is important for me to do this in loop and in time complexity of O(n). The problem with my code is that the loop does not want to rerun the list end for any value I take from the beginning of the list... I would appreciate help :) Thanks for the helpers!
def closest(lst, x):
max_num = 0
cur = lst[0]
final = 0
my_tup = ()
for num in lst[::-1]:
max_num = cur + num
if max_num <= x:
if max_num > final:
final = max_num
my_tup = (cur, num)
else:
cur = lst[1]
return my_tup
print(closest([10,22,28,29,30,40], 54)) ---> return: (22,29)