热线电话:13121318867

登录
2019-01-26 阅读量: 751
递归(如在数学中)添加一个for in range块内的列表

如果我要计算给定文本中元音的使用次数,如何使代码浏览文本以将所有元音标识为列表中的项目,并添加每个元音的计数以获得总元音算,给定的文字可能包含重复的元音?(表示递归,因为我需要将新的第n个y添加到(n-1)y。)

我是初学者,从下面的代码可以看出,我对函数库没有任何了解,但我认为,练习的目的(在移动应用程序中的挑战)是想出一个答案。具有列表,字符串,循环等基本知识

vowels=["a","A","e","E","i","I","o","O","u","U"]

exprs=input("Please type an expression to get a count of the vowels it has: ")

Ind= len(vowels)

eL=list(exprs)

for i in range(Ind):

x=vowels[i]

if x in exprs:

y=eL.count(x)

print("\n\nThe number of times that vowel",x,"occurs in", exprs, "is",y)

print("The vowel",x,"occurs in the given expression at index",str(eL.index(x)) + ".")

我无法找到递归添加y值的方法(在循环外尝试y = 0,然后y = y + eL.count(x),其他一些想法无济于事。)

解决办法:

只想计算vowels列表中每个字母出现在字符串中的次数txt:

vowels = ["a","A","e","E","i","I","o","O","u","U"]

txt = 'hello world abcdef'

frequency = {}

total = 0

for i in txt:

if i in vowels:

frequency[i] = frequency.get(i, 0) + 1

total += 1

print(frequency)

print('total:', total)

这将打印以下内容:

{'e': 2, 'o': 2, 'a': 1}

total: 5

意思是'e'出现两次,依此类推,以及元音的总数。

0.0000
1
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子