Apr-09-2019, 10:38 PM
(Apr-09-2019, 10:29 PM)hshivaraj Wrote: List 500 700 1000 1400 2000
target 2300
There inst a direct match but the closest is 1400 + 700 which gives me 2100. And this the right answer.
The closet is 1000 + 1400 which gives 2400
items = (500, 700, 1000, 1400, 2000) target = 2300 from itertools import combinations nearest = target best_match = None for item1, item2 in combinations(items, 2): differance = abs(target - (item1 + item2)) if differance <= nearest: best_match = (item1, item2) nearest = differance print(f'The best match to {target} is {best_match} at {sum(best_match)}')
Output:The best match to 2300 is (1000, 1400) at 2400
Unless the best match must be must be equal to or below the target.items = (500, 700, 1000, 1400, 2000) target = 2300 from itertools import combinations nearest = target best_match = None for item1, item2 in combinations(items, 2): differance = abs(target - (item1 + item2)) if differance <= nearest and (item1 + item2) <= target: best_match = (item1, item2) nearest = differance print(f'The best match to {target} is {best_match} at {sum(best_match)}')
Output:The best match to 2300 is (700, 1400) at 2100