Reputation: 19
I have to solve a task for university. I have 4 given lists and I have to count the possible variations of burgers that can be made under some restrictions.
breads = ["Weissbrot", "Vollkorn", "Dinkel", "Speckbrot"]
patties = ["Wildschwein", "Rind", "Halloumi", "Aubergine"]
souces = ["Kaese", "Knoblauch", "Curry"]
toppings = ["Kopfsalat", "Bacon", "Tomate"]
My code so far:
i = "bottom, patty, souce, topping, top"
burger = [i for bottom in breads
for top in breads
for patty in patties
for souce in souces
for topping in toppings
if bottom != top
if i != ("Speckbrot", "Aubergine", "Kaese", "Bacon", "Weissbrot")]
print(len(burger))
The restrictions:
The finished burger needs to have the structure (bottom, patty, souce, topping, top). I safed this under the variable 'i'. Bottom and top must have different bread. I solved this with if bottom != top
.
Mixing Aubergine with Speckbrot, Kaese or Bacon and Halloumi with Speckbrot or Bacon is not allowed. I tried to sovle this with if i != ("Speckbrot", "Aubergine", "Kaese", "Bacon", "Weissbrot")
but its obviously not correct.
Furthermore, if bottom and top are swapped and the rest stays the same this counts as 1 burger and not 2. I have no plan how to solve this yet.
Sorry for the german words, i can translate it if needed.
Many thanks in advance
EDIT: The correct answer is 138 variations.
Upvotes: 0
Views: 62
Reputation: 104712
Your issue is with the variable i
, which doesn't work the way you seem to want it to. It is not a substitute for naming five variables. It's just a string that happens to have the variable names in it.
This would be a valid comprehension, though I suspect the restriction from the last if
clause is a lot more narrow than you want (it forbids exactly one combination).
burger = [(bottom, patty, souce, topping, top)
for bottom in breads
for top in breads
for patty in patties
for souce in souces
for topping in toppings
if bottom != top
if (bottom, patty, souce, topping, top) !=
("Speckbrot", "Aubergine", "Kaese", "Bacon", "Weissbrot")]
Upvotes: 1
Reputation: 256
Using list comprehension, this works
choices = [[b, p, s, t] for b in breads for p in patties for s in souces for t in toppings] #add restrections (if [b,p, s, t] !=)
print (choices)
Upvotes: 0
Reputation: 256
First, in this case you probably shouldn't be using list comprehension. List comprehension is for smaller things, and this is far too messy. This is probably the best way to do it (using for loops). In the code below, count will be the total number and choices are all possible burgers.
choices = []
count = 0
for b in breads:
for p in patties:
for s in souces:
for t in toppings:
temp = [b, p, s, t]
#add restrictions here
choices.append(temp)
count += 1
print (choices, count)
Upvotes: 0