【问题标题】:Python Palindrome Help: Count palindromes in a sentencePython Palindrome Help: 计算一个句子中的回文数
【发布时间】:2015-10-17 18:54:30
【问题描述】:

我在 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!")

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

我已经为此苦苦挣扎了好几天,似乎不知道从哪里开始。帮助将不胜感激。另外,我需要修改我上面的程序,而不是制作一个完全不同的程序。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您需要将字符串拆分为单词,然后使用列表组合检查每个单词是否为回文,列表的长度也会为您提供计数:

    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()
    

    【讨论】:

    • 我认为你需要添加 def palindrome(word): return word == word[::-1] if len(word) >1 else None
    • @paddu,这表明 ai 等不是回文,你有引用支持吗?
    • 是的,试试上面代码的值“我的句子有一个回文 - 公民”,看看结果
    • 是的,这更有意义。如果有机会,请进行适当的编辑。
    • 同意。感谢您花时间解释。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多