我一直在研究这个回文程序,并且非常接近完成它。接近到它让我有点发疯的地步哈哈。该程序应该检查每个“短语”以确定它是否是回文,并返回一个小写版本,如果它实际上是回文,则删除空格和标点符号。否则,如果不是,它应该返回 None。我只是在将测试数据带入函数时遇到问题。我似乎想不出正确的处理方法。这可能很简单......有什么想法吗?谢谢!
import string
def reverse(word):
newword = ''
letterflag = -1
for numoletter in word:
newword += word[letterflag]
letterflag -= 1
return newword
def Palindromize(phrase):
for punct in string.punctuation:
phrase= phrase.replace(punct,'')
phrase = str(phrase.lower())
firstindex = 0
secondindex = len(phrase) - 1
flag = 0
while firstindex != secondindex and firstindex < secondindex:
char1 = phrase[firstindex]
char2 = phrase[secondindex]
if char1 == char2:
flag += 1
else:
break
firstindex += 1
secondindex -= 1
if flag == len(phrase) // (2):
print phrase.strip()
else:
print None
def Main():
data = ['Murder for a jar of red rum',12321, 'nope', 'abcbA', 3443, 'what',
'Never odd or even', 'Rats live on no evil star']
for word in data:
word == word.split()
Palindromize(word)
if __name__ == '__main__':
Main()