2024-10-01 11:23:44 发布
网友
我需要使用递归来查找字符串中元音的个数。所以如果输入了hello,我希望它返回2。在
hello
2
我遇到的问题是转到字符串中的下一个字符。在
def recVowelCount(i): count = 0 if i in 'aeiou': count +=1 reVowelCount(i) else: reVowelCount(i) return count
这里有一种使用递归的方法:)
def recVowelCount(i, chars_to_find='aeiou'): if not chars_to_find: return 0 return i.count(chars_to_find[0]) + recVowelCount(i, chars_to_find[1:])
现在,代码中的问题是
会问if 'hello' in 'aeiou':,这不是很有用。您需要检查if i[0] in 'aeiou',其中{}将是每次递归调用函数时"hello"的每个字母
if 'hello' in 'aeiou':
if i[0] in 'aeiou'
"hello"
从简单的案例开始。如果输入字符串为空会发生什么情况?你只需返回0对吗?在
0
def recVowelCount(i): if not i: return 0
所以我们完成了一半。现在您需要考虑在i不是空的情况下会发生什么。如果第一个字符是元音,我们将计数1,然后将字符串的其余部分递归地传递到函数中
i
1
def recVowelCount(i): if not i: return 0 if i[0] in 'aeiou': count = 1 else: count = 0 return count + recVowelCount(i[1:])
好吧。。可以重构一点
def recVowelCount(i): if not i: return 0 count = 'aeiou'.count(i[0]) return count + recVowelCount(i[1:])
最后呢
def recVowelCount(i): if not i: return 0 return 'aeiou'.count(i[0]) + recVowelCount(i[1:])
首先,不清楚你通过的是什么论点 def countVowels(my_string): 可能是一个更好的开始
def countVowels(my_string):
接下来你需要一个基本情况
if len(my_string) == 1: if my_string in "aeiou": return 1 else:return 0
那么你需要递归
def recVowelCount(s): ''' Return number of vowels in string s''' if len(s) == 0: return 0 letter = s[0] if letter in 'aeiou': return 1 + recVowelCount(s[1:]) return recVowelCount(s[1:]) print recVowelCount('hello')
任何递归程序都有3个基本步骤:
这里有一种使用递归的方法:)
现在,代码中的问题是
^{pr2}$会问}将是每次递归调用函数时
if 'hello' in 'aeiou':
,这不是很有用。您需要检查if i[0] in 'aeiou'
,其中{"hello"
的每个字母从简单的案例开始。如果输入字符串为空会发生什么情况?你只需返回
0
对吗?在所以我们完成了一半。现在您需要考虑在
i
不是空的情况下会发生什么。如果第一个字符是元音,我们将计数1
,然后将字符串的其余部分递归地传递到函数中好吧。。可以重构一点
最后呢
首先,不清楚你通过的是什么论点
def countVowels(my_string):
可能是一个更好的开始接下来你需要一个基本情况
那么你需要递归
^{pr2}$任何递归程序都有3个基本步骤:
相关问题 更多 >
编程相关推荐