I've encountered a simple python problem to solve: Having lists of 3 categories of items and their corresponding values, print out all combinations across the 3 lists which have lower total value than X. (Code example might be clearer explanation).
I have managed to solve this using zip() and itertools.product() to create the combos, but when it comes to outputting the right combos, I feel like there has to be a better, more pythonic way to express the output by zipping the inner tuples of the products to get the sum of prices without needing to create 2 explicit genrators/list (the use case does not matter in this case I believe). Coming from a Java background, I'm still having problems at times not lapsing into Java-like syntax which is what I definitely want to avoid with Python.
Here is my code:
import itertools
# Print out all possible meal combinations under $30
main_courses = ['beef stew', 'fried fish']
price_main_courses = [28, 23]
desserts = ['ice-cream', 'cake']
price_desserts = [2, 4]
drinks = ['cola', 'wine']
price_drinks = [3, 10]
products = itertools.product(
zip(main_courses, price_main_courses),
zip(desserts, price_desserts),
zip(drinks, price_drinks)
)
for combo in products:
names = (x[0] for x in combo)
price = sum((x[1] for x in combo))
if price <= 30:
print(*names, price)