skip to Main Content

I have a program like this one:

one_tuple = ((0, 1, 2),
             (3, 4, 5),
             (6, 7, 8),
             (0, 3, 6),
             (1, 4, 7),
             (2, 5, 8),
             (0, 4, 8),
             (2, 4, 6))
def function():
    for tuples in one_tuple:
        for variables in tuple:
           see if ceratin conditions are true....

this is an artificial intelligence for a program called “Tic tac toe” and this part checks every winning combination, nested for loops seemed like the easiest solution for that (that’s why sub tuples have 3 elements) and I need to go through each element and check them (for example if a sub tuple has 2 noughts or 2 crosses and 1 empty field then it needs to append that field to a list, in my example the program will never know if someone can win by taking that empty field)

2

Answers


  1. You can use all for each sub-tuple to check your condition for each element of that tuple. For example, say you want to check if all the elements of the tuple are greater than 2

    def foo(tup):
        for sub in tup:
            if all(i > 2 for i in sub):
                print("all greater than two")
    
    >>> foo(one_tuple)
    all greater than two
    all greater than two
    
    Login or Signup to reply.
  2. Use a dict for the board and store winning combinations. if two out of three positions are filled we know the remaining position is a winning one. This is a quick example of the logic where one_tuple is replaced by winning combs:

    from collections import OrderedDict
    
    # 8 potential winning combs for 9 item board
    winning_combs = [(0, 1, 2), (0, 3, 6), (0, 4, 8), (3, 4, 5), (6, 7, 8), (1, 4, 7), (2, 5, 8), (2, 4, 6)]
    # set all to False for an empty board
    board = OrderedDict((k, False) for k in range(10))
    board[0] = True # simulate two moves 0 and 1 are set 
    board[1] =  True
    # anywhere we find two positions taken in a potential winning combo we will return the key/position
    opps = [k for tup in winning_combs if sum(board[t] for t in tup) == 2 for k in tup if not board[k]]
    print(opps) # returns 2 the potential winning position
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search