[英]How do I handle Palindrome with spaces in python?
I'm trying to check if a string is palindrome in python using deque.我正在尝试使用双端队列检查 python 中的字符串是否为回文。 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?但是下面的代码只是检查一个没有空格的字符串,我怎样才能将它调整为处理带空格的字符串的代码呢? eg: It only works if I write the input as "BORROWORROB" but not when it's "BORROW OR ROB"例如:它仅在我将输入写为“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)))
You have to remove white spaces before starting the logic of the function:在开始 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)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.