i've a list of items, with price and amount needed.
[ [ "Sacred Foundry", 12.69, 2 ], [ "Bloodstained Mire", 26.55, 2 ], [ "Wooded Foothills", 25.97, 2 ], [ "Verdant Catacombs", 14.54, 2 ], [ "Fury", 32.64, 4 ] ]
i would like to get all combination from items in that list for a certain amount of money
if i have 100€, i could buy 3 fury, or 2 fury and a wooded foothills and a sacred foundry ...
def find_combinations(items, target_sum, result_type='full'):
items = sorted(items, key=lambda x: x[1], reverse=True)
results = []
closest_diff = float('inf')
closest_combination = []
def backtrack(start, target_sum, combination):
nonlocal closest_diff
nonlocal closest_combination
if target_sum < 0:
return
if target_sum == 0:
results.append(combination)
return
if start == len(items):
return
for i in range(start, len(items)):
for j in range(1, items[i][2] + 1):
if target_sum - items[i][1] * j >= 0:
backtrack(i + 1, target_sum - items[i][1] * j, combination + [(items[i][0], j)])
if abs(target_sum - items[i][1] * j) < closest_diff:
closest_diff = abs(target_sum - items[i][1] * j)
closest_combination = combination + [(items[i][0], j)]
backtrack(0, target_sum, [])
if len(results) > 0:
results = [results[0]]
elif len(closest_combination) > 0:
results = [closest_combination]
else:
return []
if result_type == 'full':
return results
elif result_type == 'most_items':
return [max(results, key=lambda x: sum(map(lambda y: y[1], x)))]
elif result_type == 'most_expensive':
return [max(results, key=lambda x: sum(map(lambda y: y[0][1] * y[1], x)))]
else:
return results
it tried this, with some help from different website and chatgpt but it seems to only return one result.
thanks