简体   繁体   中英

I want to call the element inside a tuple of tuples for my function

I want to get True when one of the lines of a tictactoe game is full:

teste5=('O','X','X',' ',' ',' ',' ',' ',' ')
teste6=('X','X','X',' ',' ',' ',' ',' ',' ')

def vencedor_linha(t):
    tl1=(t[0],t[1],t[2])
    tl2=(t[3],t[4],t[5])
    tl3=(t[6],t[7],t[8])
    tl=(tl1,tl2,tl3)
    if tl[0:][0:]=='X':
        return True
    elif tl[0:][0:]=='O':
        return True
    else:
        return False

so vencedor_linha(teste5) -> True and vencedor_linha(teste6) -> False

Problem is: it gives me vencedor_linha(teste5) -> False , because I can't get the if 's to work correctly.

PS. I can't use lists so don't bother telling me to. :p

If you want to check that 3 different values are equal to something, you need to use all() or 3 different == conditions; checking if a slice is equal to one value doesn't make any sense.

You want something like:

def vencedor_linha(t):
    tl1=(t[0],t[1],t[2])
    tl2=(t[3],t[4],t[5])
    tl3=(t[6],t[7],t[8])
    tl=(tl1,tl2,tl3)
    for row in tl:
        if all(x == 'X' for x in row) or all(x == 'O' for x in row):
            return True
    return False

(This checks all 3 rows; it's unclear to me whether your original code is only trying to check the first row.)

A one liner that uses itertools like pretty much everything that does something clever with iterables:

from itertools import groupby
def vencedor_linha(t):
    return any(reduce(lambda x,y:x if x==y and x in ['X','Y'] else False,
        (r[1] for r in row[1])) for row in groupby(enumerate(t),lambda (i,v):i/3))

Basically: enumerate(t) returns an iterator where each element is of the form (index of element in t, element in t)

groupby(iterable, keyfunction) returns an iterator where each element is of the form (value, iterator over the elements of iterable for which keyfunction applied to that element returns value)

reduce(function,iterable): Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). (from the python docs)

any(iterable) returns True if any of the elements of the iterable evaluate to True, False otherwise.

So we break your tuple into rows with groupby, calculate if each row is homogeneous and only contains 'X' or 'Y' with reduce, and return True if that is True for any of those rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM