我已经用相同的行为编写了两个不同的函数。哪个更像Python?

2024-05-05 05:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python非常陌生,最近一直在练习编写简单函数。下面的两个函数都检查字符串是否为回文。是一种方法比另一种更“Pythonic”,还是我的问题没有意义,因为还有另一种更好的方法可以做到这一点

def is_palindrome_recursive(word):
    if len(word) == 1:
        return True
    elif len(word) == 2:
        if word[0] == word[1]:
            return(True)
        else:
            return(False)
    elif word[0] != word[-1]:
        return False
    else:
        return is_palindrome_recursive(word[1:-1])
def is_palindrome_while(word):
    while len(word) > 2:
        if word[0] != word[-1]:
            return False
        else:
            word = word[1:-1]
    if len(word) == 1:
        return True
    elif word[0] == word[1]:
        return True
    else:
        return False

最后,对于堆栈溢出,这是一个合适的问题,还是属于一个更主观的论坛