我正在使用如何像计算机科学家一样思考互动版学习 Python,其中一个练习具有以下要求:
“为程序中的变量分配一个三引号字符串,其中包含您最喜欢的文本段落——可能是一首诗、一段演讲、烤蛋糕的说明、一些鼓舞人心的诗句等。
编写一个函数来计算文本中字母字符(a 到 z 或 A 到 Z)的数量,然后跟踪字母“e”有多少个。您的函数应该像这样打印文本分析:
您的文本包含 243 个字母字符,其中 109 个(44.8%)是 'e'。”
我写的代码(对我来说)似乎完全按照我的要求做,但是当我检查他们的解决方案来测试我的代码时,我得到了不同的结果。
我的代码:
text = ''' "If the automobile had followed the same development cycle as the computer, a
Rolls-Royce would today cost $100, get a million miles per gallon, and explode
once a year, killing everyone inside."
-Robert Cringely'''
lowercase_text = text.lower()
def charCounter(some_text):
e_counter = 0
char_counter = 0
for char in lowercase_text:
if char == 'e':
e_counter = e_counter + 1
else:
char_counter = char_counter + 1
return ("Your text contains " + str(char_counter) + " alphabetic characters, of which " + str(e_counter) + " (" + str((e_counter / char_counter) * 100) + "%)" + "are 'e'.")
我的代码输出:
Your text contains 188 alphabetic characters, of which 25 (13.297872340425531%)are 'e'.
作者提供的解决方案代码:
def count(p):
lows="abcdefghijklmnopqrstuvwxyz"
ups="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numberOfe = 0
totalChars = 0
for achar in p:
if achar in lows or achar in ups:
totalChars = totalChars + 1
if achar == 'e':
numberOfe = numberOfe + 1
percent_with_e = (numberOfe/totalChars) * 100
print("Your text contains", totalChars, "alphabetic characters of which", numberOfe, "(", percent_with_e, "%)", "are 'e'.")
p = '''"If the automobile had followed the same development cycle as the computer, a
Rolls-Royce would today cost $100, get a million miles per gallon, and explode
once a year, killing everyone inside."
-Robert Cringely'''
count(p)
作者解决方案输出的代码:
Your text contains 166 alphabetic characters of which 25 ( 15.060240963855422 %) are 'e'.
有人可以解释我做错了什么吗?我不明白为什么结果会有这种差异。