I have a script below that gives the closest 2 values to a given sum. It also iterates through a list of given sums and after each iteration removes the numbers that have already been used.
I need to modify this script so that it produces a necessary amount of values closest to each sum, rather than 2. The script needs to accept float values and cannot re-use values. Effectively it needs to pick the most efficient set closest to target, update the set to remove values used, then move on to next target etc..
With pairs it it doesn't work very well for specific use cases/sets that require 3 numbers or 4 etc. to actually get closest to the sum. I need this script to also be able to accept float values, which this script currently does.
Any suggestions would be much appreciated. Also if someone knows a better script for this, please let me know.
import sys
def find_closese_sum(numbers, target):
start = 0
end = len(numbers) - 1
result = sys.maxint
result_tuple = None
while start < end:
if numbers[start] + numbers[end] == target:
print 0, (numbers[start], numbers[end])
return
elif numbers[start] + numbers[end] > target:
if abs(numbers[start] + numbers[end] - target) < result:
result = abs(numbers[start] + numbers[end] - target)
result_tuple = (numbers[start], numbers[end])
end -= 1
else:
if abs(numbers[start] + numbers[end] - target) < result:
result = abs(numbers[start] + numbers[end] - target)
result_tuple = (numbers[start], numbers[end])
start += 1
for i in result_tuple:
numbers.remove(i)
return result_tuple
if __name__ == "__main__":
target = [14,27,39]
numbers = [1,5,5,10,7,8,11,13,66,34]
print numbers
numbers = sorted(numbers)
for i in target:
result_shown = find_closese_sum(numbers, i)
print result_shown