Jerry Zhou
Jerry Zhou

Reputation: 43

how to find intersections between multiple sets and a list?

So I have multiple sets as win conditions in my tic tac toe game:

    win1 = {1,2,3}
    win2 = {4,5,6}
    win3 = {7,8,9}
    win4 = {1,5,9}
    win5 = {7,5,3}
    win6 = {1,4,7}
    win7 = {2,5,8}
    win8 = {3,6,9}

where each number is a position on the tic tac toe grid. I also have a list that adds every position the O and the X player makes. My current way of checking if a player won is this:

    def checker():
      if (win1 or win2 or win3 or win4 or win5 or win6 or win7 or win8).issubset(jonesO):
        print 'O wins!'
        return 0
      elif (win1 or win2 or win3 or win4 or win5 or win6 or win7 or win8).issubset(jonesX):
        print 'X wins!'
        return 1
      elif (tie).issubset(bob):
        print 'IT IS A TIE!!!!!'
        return 2

but I figured out that the .issubset only checks the first set and nothing else. How do I change it so all the sets in the elif() and if are checked as subsets?

Upvotes: 1

Views: 71

Answers (2)

kishore
kishore

Reputation: 127

isSubSet is costly operation, you should instead use union operator of set.

any(jonesO==jonesO.union(x) for x in (win1, win2, win3, win4, win5, win6, win7, win8))

This condition will return True if any of winning combination is part of moves set else will return False.

Basically, union of two set will return same set if joining set is already a subset of other set

Upvotes: 0

user2390182
user2390182

Reputation: 73498

In Python, a or b or c evaluates to the first of the three that is truthy (if none is truthy, it is the last). In your case that would be the first non-empty set: win1. For your case, you can use any:

if any(x.issubset(jonesO) for x in (win1, win2, win3, win4, win5, win6, win7, win8)):
    print 'O wins!'

Upvotes: 1

Related Questions