使用递归来查找元音的数量

时间:2012-10-08 04:26:29

标签: python recursion

我需要使用递归来查找字符串中的元音数量。因此,如果输入hello,我希望它返回2

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

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

4 个答案:

答案 0 :(得分:4)

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

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 i in 'aeiou':

会问if 'hello' in 'aeiou':,这不是很有用。每次递归调用函数时,您需要检查if i[0] in 'aeiou' i[0]每个字母"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:])

答案 1 :(得分:2)

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. 递归通话

答案 2 :(得分:1)

首先,不清楚你传递的是什么论点     def countVowels(my_string): 可能是一个更好的开始方式

接下来你需要一个基本案例

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

然后你需要你的递归

 elif my_string[0] in "aeiou":
     return 1 + countVowels(my_string[1:])
 else:
      return 0 + countVowels(my_string[1:])

答案 3 :(得分:0)

def find_vowels(word=None, count=0):
    if word:
        if word[0] in ('A','E','I','O','U','a','e','i','o','u'):
            count += 1
        return find_vowels(word=word[1:], count=count)
    else:
        return count

find_vowels('python is awesome')

find_vowels函数有两个参数 - 一个是word,这是要查找的实际字符串。另一个是count,其中包含元音的总出现次数。 count的初始值设置为0.

如果word为空,则函数将返回计数值。这是在word完全检查元音时的情况。  if word:

以下块包含实际逻辑。在word中重复检查第一个字符。如果它是元音,count参数会递增。

return find_vowels(word=word[1:], count=count)是递归发生的地方。使用word=word[1:]我们会对第一个字符进行切片,因为它已被检查过。

示例

word ='Python'

word的值在后续调用中的显示方式:

Python - 第一次通话
ython - 第二次通话
thon - 第3次致电 hon - 第四次通话
on - 第5次通话
n - 第6次致电 - 最后一次通话(空)

最后,当字符串为空时,返回count

这称为尾递归:http://en.wikipedia.org/wiki/Tail_call