用递归法求元音个数

2024-10-01 11:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用递归来查找字符串中元音的个数。所以如果输入了hello,我希望它返回2。在

我遇到的问题是转到字符串中的下一个字符。在

 def recVowelCount(i):
    count = 0
    if i in 'aeiou':
        count +=1
        reVowelCount(i)
    else:
        reVowelCount(i)
        return count

Tags: 字符串inhelloreturnifdefcount字符
3条回答

这里有一种使用递归的方法:)

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:])

现在,代码中的问题是

^{pr2}$

会问if 'hello' in 'aeiou':,这不是很有用。您需要检查if i[0] in 'aeiou',其中{}将是每次递归调用函数时"hello"的每个字母

从简单的案例开始。如果输入字符串为空会发生什么情况?你只需返回0对吗?在

def recVowelCount(i):
    if not i:
        return 0

所以我们完成了一半。现在您需要考虑在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): 可能是一个更好的开始

接下来你需要一个基本情况

 if len(my_string) == 1:
    if my_string in "aeiou": return 1
    else:return 0

那么你需要递归

^{pr2}$
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个基本步骤:

  1. 基本情况
  2. 你需要朝着基本情况前进
  3. 递归调用

相关问题 更多 >