python递归元音计数

时间:2014-11-16 00:37:58

标签: python string recursion

def count_vowels(s):
    if not s:
        return 0
    elif s[0] in VOWELS:
        return 1 + count_vowels(s[1:])
    else:
        return 0 + count_vowels(s[1:])

我看到这段代码非常适合查找字符串中的元音数量。我也理解递归总是需要一个基本案例。我想这个代码的主要问题是第一个if语句实际意味着什么?什么检查?

if not s:
    return 0

如果不是什么?有没有办法在没有那部分的情况下编写代码?

2 个答案:

答案 0 :(得分:2)

这是你从递归中退出的。你的递归必须在某个时间点停止(否则它将永远运行)。

这意味着如果字符串为空 - 返回0(空字符串中没有元音)并停止。

答案 1 :(得分:1)

if not s检查字符串是否为空。空字符串是" false-y" Python中的对象。如果字符串为空,则它不能有任何元音。

我意识到你可能需要在这里使用递归,但这在实践中是更好的方法:

>>> VOWELS = set('aeiou')
>>> def count_vowels(s):
...     return sum(x in VOWELS for x in s)
... 
>>> count_vowels('hello world')
3
相关问题