如何在Python中处理带有空格的回文?
我正在尝试使用双端队列检查 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在开始函数逻辑之前,您必须删除空格:
You have to remove white spaces before starting the logic of the function: