2024-05-15 22:34:34 发布
网友
我想用python计算文本文件中的回文数。但我写的这个程序给我的是0而不是2 文本文件:
Tattarrattat was coined by writer James Joyce in a book called Ulysses. Aibohphobia is a joke term used to describe the fear of palindromes.
课程:
你的代码有两个错误。首先,一行的字数通常不是100。其次,大写字母不等于相应的小写字母。以下是您程序的修正版本:
count = 0 # x is never a good name with open('palindrome_test.txt','r') as text: for line in text: words = line.lower().split() #split the lowercased line into words for w in words: if w == w[::-1]: count += 1 #increment
请注意,单词“a”也是一个回文(它在文本中出现两次)。在
可以用列表理解替换for循环,以获得更美观的程序:
你的代码有两个错误。首先,一行的字数通常不是100。其次,大写字母不等于相应的小写字母。以下是您程序的修正版本:
请注意,单词“a”也是一个回文(它在文本中出现两次)。在
可以用列表理解替换for循环,以获得更美观的程序:
^{pr2}$相关问题 更多 >
编程相关推荐