'Checking if a list is inside another list (regardless of order) in Python
I'm trying to build a slot machine game where you get 10 coins for getting 3 cherries (in any order) and I have an if statement like this:
#slotresult has the format ['x','x','x','x']
threecherries= ["cherry","cherry","cherry"]
if set(threecherries).issubset(slotresult):
print("Nice! You have won 10 coins!")
The problem is that it says 'You have won 10 coins!' when only one or more cherries appears in the slotresult, but I want it to only say this when there are three cherries there in any order.
I've also tried alternatives but they won't match if the result is like:
['cherry','lemon','cherry','cherry] as the 'cherries' aren't all next to each other!
Could anyone help me with this?
Solution 1:[1]
You can use list.count.
if slotresult.count('cherry') == 3:
print("Nice! You have won 10 coins!")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Unmitigated |
