Python 中连续出现 13 次相同字符的列表

3

到目前为止,我的代码是这样的:

while True:
    """
    determines if there is a list of x's or o's in a horizontal row
    """
    game = list(input())
    if len(game) == 0:
        print("We should now check for vertical or diagonal winners!")
    elif game[0] == game[1]:
        if game[1] == game[2]:
            if game[2] == game[3]:
                if game[3] == game[4]:
                    if game[4] == game[5]:
                        if game[5] == game[6]:
                            if game[6] == game[7]:
                                if game[7] == game[8]:
                                    if game[8] == game[9]:
                                        if game[9] == game[10]:
                                            if game[10] == game[11]:
                                                if game[11] == game[12]:
                                                    if game[12] == "o":
                                                        print("Player o won")
                                                    else:
                                                        print("Player x won")
                                                else:
                                                    del game[0:12]
                                            else:
                                                del game[0:12]
                                        else:
                                            del game[0:12]
                                    else:
                                        del game[0:12]
                                else:
                                    del game[0:12]
                            else:
                                del game[0:12]
                        else:
                            del game[0:12]
                    else:
                        del game[0:12]
                else:
                    del game[0:12]
            else:
                del game[0:12]
        else:
            del game[0:12]
    else:
        del game[0:12]

我觉得一定有更短的写法。我只想到了一种确定水平赢家的方法。我不知道如何解决垂直或对角线赢家的问题。我还测试了这段代码,当x在第二行获胜时,它没有打印出x获胜,所以我想知道我的错误在哪里?

非常感谢任何帮助!谢谢。


5
你学过循环吗?如果没有,现在是一个学习的好时机。 - Scott Hunter
为什么这被标记为“递归”? - Scott Hunter
@ScottHunter 因为从算法的角度来看,最简单的解决方案是递归吗? - m.wasowski
我真的不太理解你目前的代码(你说得对,肯定有更简单的方法来做到这一点,但由于我无法完全弄清楚你想要做什么,所以现在我只能告诉你del关键字不能用于字符串。) - train1855
  1. 首先将其转换为矩阵(列表的列表);
  2. 注意,检查列表lst中的所有字符是否都等于ch(我们称此函数为all_are(lst, char))与说lst[0] == ch and all_are(lst[1:], ch)是相同的;因此您可以通过递归来解决这个问题。
- m.wasowski
2个回答

2
你非常需要学习正则表达式!这似乎很像一道作业题,但既然其他人已经在回答了,我会给你最快的答案。Regex可能比你用纯python编写的任何代码都要快,因为它使用了编译的c代码。你可以直接使用正则表达式从输入字符串中轻松测试水平或垂直匹配。
import re

# find 13 x's or o's in a row that begin some multiple of 13 characters from the beginning of the input string
horizMatch_regex = re.compile("^(.{13})*(xxxxxxxxxxxxx|ooooooooooooo)")
# find 13 x's or o's that appear with exactly 12 characters in between, which corresponds to columns.  Requires lookahead (?=) 
verticalMatch_regex = re.compile("(x(.{12})(?=x)){12}|(o(.{12})(?=o)){12}")
# slightly trickier - you need 4 separate match groups to test for each possible diagonal.  There are a variety of ways to do that, but here's one
diagonalMatch_regex = re.compile("(^(x.{13}){12}x)|(^(o.{13}){12}o)|((x.{11}){13}.$)|((o.{11}){13}.$)")

if horizMatch_regex.search(input_str):
    print("We have a horizontal tic tac toe!")

if verticalMatch_regex.search(input_str):
    print("We have a vertical tic tac toe!")

if diagonalMatch_regex.search(input_str):
    print("We have a diagonal tic tac toe!")

# string with horizontal, vertical, and diagonal tic tac toe's
input_str = "xooooooooooooxxxxxxxxxxxxxxoxoooooooooxxxxxxxxxxxxxoxoooxoooooooxxxxxxxxxxxxxoxoooooxoooooxxxxxxxxxxxxxoxoooooooxoooxxxxxxxxxxxxxoxoooooooooxoxxxxxxxxxxxxxoxooooooooooox"

We have a horizontal tic tac toe!
We have a vertical tic tac toe!
We have a diagonal tic tac toe!

好的...嗯,那是一个很好的观点。但我的想法是,如果我解释了,解决对角线就太容易了。不过我可能会直接发布整个答案,因为我太软弱了。 - KCzar
“正则表达式比你用纯Python写的任何东西都要快,因为它使用了编译的C代码”这种说法是错误的。某些正则表达式可能会遇到问题(例如灾难性回溯),而Python本身在正则表达式和其他领域中也大量使用C库。 - TigerhawkT3
显然,正则表达式可能会很慢,但我是针对这个问题而言的。我在我的答案中进行了澄清。 - KCzar
如果这是解决此问题的最快方法,那并不是因为它访问了C库。Python的许多部分都这样做。 - TigerhawkT3
当然会,但是针对这个问题的正则表达式允许你在Python解释器中花费非常少的时间 - 我只用了3行Python代码,其余的都是用C完成的。 - KCzar

2
使用一个二维列表和一些循环。
instring = 'oooooooooooooxxxxxxxxxxxxoooooooooooooxxxxxxxxxxxxxoooooooooooooxxxxxxxxxxxxxoooooooooooooxxxxxxxxxxxxxoooooooooooooxxxxxxxxxxxxxoooooooooooooxxxxxxxxxxxxxooooooooooooox'

board = []
for x in range(13):
    board.append(instring[x::13])
board = list(zip(*board))

如果一行有获胜者,请打印出获胜者:
>>> for row in range(13):
...     if len(set(board[row]))-2: print(board[row][0])
...
o

如果某列有获胜者,打印出获胜者。
>>> for row in range(13):
...     if len(set(list(zip(*board))[row]))-2: print(board[row][0])
...

如果反斜杠形状的对角线有赢家,打印出赢家:
>>> if len(set(board[i][i] for i in range(13)))==1:
...     print(board[0][0])
...

如果斜线形成的 / 或者 \ 方向有获胜者,输出获胜者:
>>> if len(set(board[i][i] for i in range(-1, -14, -1)))==1:
...     print(board[0][12])
...

这段代码对我来说无法正常工作。你使用的是哪个版本的Python呢?"row"在此上下文之外是不可访问的:any(len(set(board[row]))-2 for row in range(13))。 - KCzar
很奇怪,昨天这个还能用,但现在不行了。我会修改一下。 - TigerhawkT3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接