Skip to content

Instantly share code, notes, and snippets.

@beala
Created September 14, 2012 15:46
Show Gist options
  • Save beala/3722767 to your computer and use it in GitHub Desktop.
Save beala/3722767 to your computer and use it in GitHub Desktop.
def find_order(cur_order, menu, valid_orders):
# Try every item in the menu.
for selection in menu:
new_order = cur_order + [selection]
# Try again if the current item blows the budget.
if sum(new_order) > 15.05:
continue
# If the order costs 15.05, then it meets our contraints.
elif sum(new_order) == 15.05:
valid_orders.append(new_order)
# If money left in the budget add more by recursing
elif sum(new_order) < 15.05:
valid_orders = find_order(new_order, menu, valid_orders)
# Exhausted all the branches here. Return valid orders
return valid_orders
valid_orders = find_order([], [2.15,2.75,3.35,3.55,4.20,5.80,6.55], [])
# Remove duplicates
for order in valid_orders:
order.sort()
no_dups = set()
for order in valid_orders:
no_dups.add(tuple(order))
# Print orders
for order in no_dups:
print order
@beala
Copy link
Author

beala commented Sep 14, 2012

Output:

(2.15, 2.15, 4.2, 6.55)
(2.15, 3.55, 3.55, 5.8)
(2.15, 2.15, 2.15, 2.15, 2.15, 2.15, 2.15)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment