Shopping List Program
Assume youโre given 5 EUR to buy vegetables for the week in the supermarket. The unit prices in cents are the following:
Tomato: 50,
Onion: 100,
Salad: 129,
Garlic: 45,
Pepper: 155,
Cucumber: 350
Write a Python program that prints out the combination of vegetables you can buy with the 5 EUR exactly. The program should display the vegetable and its price.
1 EUR corresponds to 100 cents.
Steps
- Define the unit prices of the vegetables in cents.
- Calculate the budget in cents (5 EUR * 100).
- Create a list of tuples where each tuple represents a vegetable and its price.
- Use the itertools library to find all combinations of vegetables that sum up to the budget.
- Print out the valid combinations
Solutions
import itertools
# Prices in cents
prices = {
"Tomato": 50,
"Onion": 100,
"Salad": 129,
"Garlic": 45,
"Pepper": 155,
"Cucumber": 350
}
budget = 500 # in cents
# Generate all combinations
all_combinations = []
for i in range(1, len(prices) + 1):
for combo in itertools.combinations(prices.items(), i):
if sum(item[1] for item in combo) == budget:
all_combinations.append(combo)
# Print combinations
if all_combinations:
for combination in all_combinations:
print("Combination:")
for veg, price in combination:
print(f"{veg}: {price} cents")
print()
else:
print("No exact combination found.")
Expected Output
Combination: Tomato: 50 cents Onion: 100 cents Cucumber: 350 cents