在尝试完成我的一所大学时,我遇到了其中一项练习,即计算我必须收到的文本中每个单词的字母,直到所有字母的总和 >= 1000,但它永远不会达到 1000,即使文字有1000多条。
首先,我认为这可能是因为我没有收到完整的消息,但在查看和弄乱我创建的不同函数之后(它们都没有解决问题),似乎我的计数器函数不起作用。 (这个计数器函数返回一个数字数组,稍后我将其转换为字符串)
有什么我没有得到的东西会弄乱我的代码吗?
def letterCounter(text):
counter = 0
indice = 0
lettTotal = 0
totalCount = []
while True:
if text[indice] == " ":
totalCount.append(counter)
counter = 0
indice += 1
else:
counter += 1
lettTotal += 1
indice += 1
if lettTotal >= 1000:
break
return totalCount
编辑: -样本 输入:
权威的东西设计达到讲教授工人执行未来因素警察春天生活寻求具体容易什么很多继续主席区军事可能重要提及行动床政府所有积极反映产品计划检查绘画下降酒吧一般重量任何政策控制系列超过气体蓝色旅行肯定形式护理商业手术语提供确定结构分数产生人无论百老师行为花园百红色出现与股票公民学校答案股票作为起始数字手臂真实自己率通知下发低形式避免任务获得婴儿卡任何人深建议成人游戏顺序道路能重警察文化减少老师第三这样的他她只是你与前面选择报告相机确定选择妻子一般百现土地将猜测在皮肤线从来没有朋友从包含边缘接受作为列表民事下降成本报纸任何部分活动新无臂个人声明基本建立每个数字主要留下吃看到扔权威差异最后看到晚上跨婴儿公司所以来源对待计算机工厂如何跨新闻只是她我希望不包括新闻似乎很难在低但风格的父母图片清晰的主题在真正的办公室老板期间但转可以战争从来没有看到长单元格所以列出当前顶部她结束可能兴趣课程列表数字开始最小风险需要网络提及落地摄像机他自己如何根据女孩行为通过实践分析进入下一个区域中央原因手下的行为整体情况细节知识成功的机构任务外行攻击证明十个参与者身体女人宗教她应该朋友蓝色虽然抛出声称深项目问谁几个最终国家候选人服务官员东月操作和平十街损失种类准备攻击经验机构走向课程晚餐建立影响最终上升找到到达持有了解其他故事接近公民主要六区树有时选择应用数据学生试用讨论生产国家丈夫质量最终眼睛在美丽失去居士之间因此仍然高层管理事实颜色这样
输出:
[9,5,6,5,5,9,6,9,6,6,6,6,4,4,8,4,4,3,8,5,4,8,3,6, 7, 3, 3, 10, 3, 8, 7, 7, 4, 5, 8, 4, 3, 7, 6, 8, 2, 6, 7, 6, 4, 3, 4, 4, 4, 4, 4, 10, 4, 4, 5, 9, 9, 5, 7, 6, 8, 7, 5, 7, 7, 3, 6, 7, 3, 6, 4, 5, 7, 6, 6, 5, 2, 5, 6, 3, 4, 7, 4, 6, 5, 4, 3, 4, 5, 4, 3, 4, 4, 6, 4, 7, 5, 4, 5, 4, 4, 5, 6, 7, 6, 7, 5, 4, 2, 3, 4, 4, 4, 5, 4, 6, 6, 4, 6, 4, 7, 7, 7, 4, 4, 5, 6, 4, 4, 5, 6, 4, 7, 4, 6, 2, 4, 5, 4, 4, 9, 8, 7, 8, 3, 2, 3, 10, 9, 4, 5, 3, 6, 4, 4, 3, 3, 5, 9, 10, 4, 3, 5, 6, 4, 4, 7, 2, 6, 5, 8, 5, 3, 6, 4, 4, 3, 2, 4, 7, 7, 4, 4, 9, 5, 3, 3, 5, 6, 7, 5]
总和=999,没有达到应有的1000
这里的其他解决方案可能可以解决您的作业,但让我们看看它首先失败的原因。
请注意,在循环的第一部分中,您将关闭空格字符以附加当前计数。然而,在计算最后一个单词时,您总是会达到字母总数限制。一旦您从循环中
break
,您就无法添加最后一个单词(正在计数的单词)。
如果您在将单词添加到计数后重新排列函数以检查字母总数,那么您将不会丢失最后一个单词。
while True:
if text[index] == " ":
total_counts.append(counter)
counter = 0
index+= 1
if total_letters >= 1000:
break
else:
counter += 1
total_letters += 1
index += 1
然后在跳出循环之前将附加字数统计。
如果您使用的文本参数包含用空格分隔的单词,您可以像下面这样做
def countLetters(sentence):#split your sentence to get the individual words
words=sentence.split(" ")
store=[]#declare an array to hold the length of each word
summation=0 #variable to hold the total number of letters in the text
for word in words:
store.append(len(word))
summation+=len(word) #pile up the total number of letters
if(summation>=1000):
break #break out of the word iteration loop
for i in range(len(words)):#print the words alongside the length of each
print(words[i],store[i])
您可以使用
list comprehension
来实现您的目标:
[len(w) for w in s.split()]
获取其
sum()
:
sum([len(w) for w in s.split()])
s = 'authority stuff Design reach speak professor worker Executive future factor police spring live seek specific Easy What lot continue chair area military may matter Mention act bed Government all positive reflect Product plan Check Painting drop bar general weight anything to policy Control series over gas blue trip sure form care commercial hand term offer determine structure score Produce Person whatever someone among hundred teacher act garden hundred red appear With stock Citizen school answer stock as start number arm real himself Rate notice Under hair low Form avoid task get baby card anyone deep suggest adult Game order road able heavy Police culture reduce teacher third such he She Just your with ahead pick report camera sure choose wife general Hundred present land will Guess within skin Line never friend from Contain edge accept as list Civil drop cost newspaper anything section activity New no arm individual Statement base Build per figure main stay Eat See throw Authority difference last see night across baby firm Company So source treat computer plant how across news just her me hope without include news seem difficult after low yet style parent picture clear subject during true office owner but turn can war never see long cell so list current top her end May interest course list figure start least risk need network mention Floor camera inside he Himself how under Girl Behavior Through Practice analysis enter region very next Behavior under central cause hand Whole situation detail knowledge Successful institution task lay attack Prove ten participant Physical woman religious Her should friend Blue though throw claim deep item Ask who Several finally national candidate serve officer East month operation peace Ten street loss kind prepare attack against experience Institution toward course Dinner build impact final Rise find arrive hold Understand Others story close citizen main six region tree sometimes choice apply data student trial get food discuss production country husband quality finally eye in beautiful lose lay Sister whom thus between still Top management Fact color such'
sum([len(w) for w in s.split()])
1794