Python回文帮助:用句子计算回文

时间:2015-10-17 18:54:31

标签: python python-3.x

我在python中创建了一个程序,它基本上告诉用户输入一个单词并告诉他们是否是回文。

我的节目:

def palindrome(word):
    return word == word[::-1]

word = input("Enter a word: ")
word2 = word.lower()

if word2 == "":
    print("You failed to input a word")
elif palindrome(word2) == True:
    print(word2,"is a palindrome!")
else:
    print(word2,"is not a palindrome!")

我需要帮助修改我的程序,以便允许用户输入一个句子并计算句子中单词的数量。当我执行程序时,我希望它在句子中输出回文。

我一直在努力奋斗这几天,我似乎无法弄清楚从哪里开始。非常感谢帮助。另外,我需要修改上面的程序,而不是制作一个完全不同的程序。

1 个答案:

答案 0 :(得分:3)

你需要将字符串拆分成单词,然后使用list comp检查每个单词是否为回文,列表的长度也会给你计数:

def palindrome(word):
    return word == word[::-1]

# split sentence into words and filter out the non palindromes
sentence = [w for w in input("Enter a sentence: ").split() if palindrome(w)]

print(" There are {} palindromes in your sentence\n.".format(len(sentence)))
# print each palindrome from our list
for pal in sentence:
    print("{} is a palindrome".format(pal))

如果您想模仿自己的代码,请在迭代字数列表时保持计数,如果我们有回文,则增加计数:

sentence = input("Enter a sentence: ").split()

count = 0
for w in sentence:
    if palindrome(w):
        count += 1
        print("{} is a palindrome.")
    else:
        print("{}  is not a palindrome.")
print(" There are {} palindromes in your sentence\n.".format(count))

要捕捉单个非字母:

def palindrome(word):
    if len(word) > 1:
        return word == word[::-1]
    return word.isalpha()