In a nutshell, I would like to know how to compare lists in this situation... I am creating a tic tac toe game and would like to test if the player has won or not.
WinningPossibilities = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
ThePlayersList = []
So, let's assume [ThePlayerList] has 4 things saved to it
WinningPossibilities = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
# Right Here
#| |
#V V
ThePlayersList = [1,2,3,4]
How would I compare "if" the [ThePlayerList] is "In" [WinningPossibilities}, because clearly, the player has won, it would look like this;
X | X | X
-----------
X | |
-----------
| |
Originally I was thinking of typing;
if ThePlayerList in WinningPossibilities:
print("The Player has won")
But it did not seem to work, I can't compare [1,2,3,4] to [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]] and see if it matches.
CodePudding user response:
One way to ask this is: is it the case that for any
of the WinningPossibilities
all
the numbers are in ThePlayersList
. This translates pretty closely to python:
WinningPossibilities = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
ThePlayersList = [1,2,3,4]
has_won = any(all(n in ThePlayersList for n in win) for win in WinningPossibilities)
# True
This is nice since the order doesn't matter: a list like ThePlayersList = [4,2,3,1]
should still win even though that order doesn't appear in the winning possibilities.
And since order doesn't matter, you could simplify this a bit by using sets instead of lists:
WinningPossibilities = [{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{1, 4, 7},
{2, 5, 8},
{3, 6, 9},
{1, 5, 9},
{3, 5, 7}]
ThePlayersList = {1,2,3,4}
has_won = any(win.issubset(ThePlayersList) for win in WinningPossibilities)