一位初学者在学习 Python 时遇到一个练习题,要求将一段文本存储在变量中,并编写一个函数计算文本中字母 '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'.")
print(charCounter(lowercase_text))
使用以上代码得出的结果是:
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'.
- 解决方案
问题出在 ursprünglicher 代码的 for 循环中,它没有检查字符是否为字母数字,并且将空格也计算在内。此外,'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 not char.isalpha():
continue
# 将总字符计数器加 1
char_counter += 1
# 如果字符为 'e',则将 'e' 计数器加 1
if char == 'e':
e_counter += 1
return ("Your text contains " + str(char_counter) + " alphabetic characters, of which " + str(e_counter) + " (" + str((e_counter / char_counter) * 100) + "%)" + "are 'e'.")
print(charCounter(lowercase_text))
使用修复后的代码得出的结果是:
Your text contains 166 alphabetic characters, of which 25 (15.060240963855422%) are 'e'.
这与给定的解决方案代码的结果相同。