Search code examples
python-3.xlistnested-liststic-tac-toe

How do I check to see if a nested list is in another list, regardless of order


I'm making tic-tac-toe in python. I have a board, and each of the squares corresponds to a number (0-8) and to help with win conditions, I have this list:

wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]

Whenever one of the players puts down a letter, wherever they placed the letter gets put into a list, so at the end of the game one of their lists might look like this:

player1 = [0, 1, 4, 5, 6]

How do I check if all of the elements of one of the nested lists are in player1 (regardless of order, if possible)?


Solution

  • If you simply want to check if any of the possible winning square lists is equivalent to player1's selected square list, you can do

    any([set(w) == set(player1) for w in wins])
    

    However, it seems to me that it would make more sense to check if any of the winning square lists are contained within player1's moves, meaning not necessarily all of the elements are in player1. You can do this by simply doing

    any([set(w).issubset(set(player1)) for w in wins])