如何在Python中处理带有空格的回文?

发布于 2025-01-17 06:08:40 字数 683 浏览 3 评论 0原文

我正在尝试使用双端队列检查 python 中的字符串是否为回文。但是下面的代码只是检查一个不带空格的字符串,如何将其调整为也处理带空格的字符串的代码?例如:仅当我将输入写为“BORROWORROB”时才有效,但当输入为“BORROW OR ROB”时则无效

from pythonds.basic import Deque
def isPalindrome(word):
    if word is None:
        return False
    if len(word) <= 1:
       return True

    DQ = Deque()
    for w in word:
        DQ.addRear(w)

    while (DQ.size() > 1):
        front = DQ.removeFront()
        rear = DQ.removeRear()
        if front != rear:
            return False
    return True


def readInput():
    inp = input("Enter string: ")
    return inp

word = readInput()
print ("Is \"{}\" a palindrome: {}".format(word, isPalindrome(word)))

I'm trying to check if a string is palindrome in python using deque. But the code below just checks a string with no space, how can I adjust it to a code which handles strings with spaces as well? e.g: It only works if I write the input as "BORROWORROB" but not when it's "BORROW OR ROB"

from pythonds.basic import Deque
def isPalindrome(word):
    if word is None:
        return False
    if len(word) <= 1:
       return True

    DQ = Deque()
    for w in word:
        DQ.addRear(w)

    while (DQ.size() > 1):
        front = DQ.removeFront()
        rear = DQ.removeRear()
        if front != rear:
            return False
    return True


def readInput():
    inp = input("Enter string: ")
    return inp

word = readInput()
print ("Is \"{}\" a palindrome: {}".format(word, isPalindrome(word)))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

誰ツ都不明白 2025-01-24 06:08:40

在开始函数逻辑之前,您必须删除空格:

from pythonds.basic import Deque
def isPalindrome(word):
    word = word.replace(" ", "")
    if word is None:
        return False
    if len(word) <= 1:
       return True

    DQ = Deque()
    for w in word:
        DQ.addRear(w)

    while (DQ.size() > 1):
        front = DQ.removeFront()
        rear = DQ.removeRear()
        if front != rear:
            return False
    return True


def readInput():
    inp = input("Enter string: ")
    return inp

word = readInput()
print ("Is \"{}\" a palindrome: {}".format(word, isPalindrome(word)))

You have to remove white spaces before starting the logic of the function:

from pythonds.basic import Deque
def isPalindrome(word):
    word = word.replace(" ", "")
    if word is None:
        return False
    if len(word) <= 1:
       return True

    DQ = Deque()
    for w in word:
        DQ.addRear(w)

    while (DQ.size() > 1):
        front = DQ.removeFront()
        rear = DQ.removeRear()
        if front != rear:
            return False
    return True


def readInput():
    inp = input("Enter string: ")
    return inp

word = readInput()
print ("Is \"{}\" a palindrome: {}".format(word, isPalindrome(word)))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文