我现在用的是如何看待一个计算机科学家互动版,和练习一个具有以下要求学习的Python:需要帮助搞清楚什么是错我的Python代码
“分配给一个变量在你的编写一个三重引号的字符串,其中包含您最喜欢的文本段落 - 可能是一首诗,演讲,烘烤蛋糕的指示,一些励志诗句等。
编写一个函数来计算字母字符数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'.")
我的代码输出:通过笔者的解决方案
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 188 alphabetic characters, of which 25 (13.297872340425531%)are 'e'.
解决方案代码
Your text contains 166 alphabetic characters of which 25 (15.060240963855422 %) are 'e'.
有人可以请解释我做错了什么?我不明白为什么结果会有这种差异。
请花一些时间来学习如何在Stack Overflow上设置你的帖子的格式。 –