Xs and Os Referee

题目

Xs and Os Referee

思路

横竖6种,斜着两种,分别判断是否一致,一致且不为空则返回其值,都不满足则返回平局

我的代码

def checkio(game_result: list) -> str:
    result = 'D'
    #斜着2种
    if game_result[0][0] == game_result[1][1] == game_result[2][2] and game_result[0][0] != '.':
        result = game_result[0][0]
        return result
    if game_result[2][0] == game_result[1][1] == game_result[0][2] and game_result[2][0] != '.':
        result = game_result[2][0]
        return result    
    #横竖6种
    for i in range(3):
        if game_result[i][0] == game_result[i][1] == game_result[i][2] and game_result[i][0] != '.':
            result = game_result[i][0]
            break
        if game_result[0][i] == game_result[1][i] == game_result[2][i] and game_result[0][i] != '.':
            result = game_result[0][i]
            break

    return result

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert checkio([
        "X.O",
        "XX.",
        "XOO"]) == "X", "Xs wins"
    assert checkio([
        "OO.",
        "XOX",
        "XOX"]) == "O", "Os wins"
    assert checkio([
        "OOX",
        "XXO",
        "OXX"]) == "D", "Draw"
    assert checkio([
        "O.X",
        "XX.",
        "XOO"]) == "X", "Xs wins again"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

clear code

def checkio(result):
    rows = result
    cols = map(''.join, zip(*rows))
    diags = map(''.join, zip(*[(r[i], r[2 - i]) for i, r in enumerate(rows)]))
    lines = rows + list(cols) + list(diags)

    return 'X' if ('XXX' in lines) else 'O' if ('OOO' in lines) else 'D'

speedy code

和我的方法一样,分8种场景判断

def checkio(game_result):
    for i in range(3):
        if (game_result[i][0] in ['O', 'X']) and (game_result[i][0] == game_result[i][1] == game_result[i][2]):
            return game_result[i][0]
        if (game_result[0][i] in ['O', 'X']) and (game_result[0][i] == game_result[1][i] == game_result[2][i]):
            return game_result[0][i]
    if (game_result[1][1] in ['O', 'X']) and ((game_result[0][0] == game_result[1][1] == game_result[2][2]) or (game_result[0][2] == game_result[1][1] == game_result[2][0])):
        return game_result[1][1]
    return "D"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值