使用递归计算字符串中的元音

Dan*_* Jr 2 python string recursion count

我知道递归是一个函数调用自身的时候,但我无法弄清楚如何让我的函数自我调用以获得所需的结果.我需要简单地计算给函数的字符串中的元音.

def recVowelCount(s):
    'return the number of vowels in s using a recursive computation'
    vowelcount = 0
    vowels = "aEiou".lower()
    if s[0] in vowels:
        vowelcount += 1
    else:
        ???
Run Code Online (Sandbox Code Playgroud)

最后我想出了这个,感谢这里的一些见解.

def recVowelCount(s):
'return the number of vowels in s using a recursive computation'
vowels = "aeiouAEIOU"
if s == "":
    return 0
elif s[0] in vowels:
    return 1 + recVowelCount(s[1:])
else:
    return 0 + recVowelCount(s[1:])
Run Code Online (Sandbox Code Playgroud)

Ósc*_*pez 6

试试这个,这是一个简单的解决方案:

def recVowelCount(s):
    if not s:
        return 0
    return (1 if s[0] in 'aeiouAEIOU' else 0) + recVowelCount(s[1:])
Run Code Online (Sandbox Code Playgroud)

它考虑了元音是大写或小写的情况.它可能不是递归遍历字符串的最有效方法(因为每个递归调用都会创建一个新的切片字符串),但它很容易理解:

  • 基本情况:如果字符串为空,则元音为零.
  • 递归步骤:如果第一个字符是元素,则向解决方案添加1,否则添加0.无论哪种方式,通过删除第一个字符并继续遍历字符串的其余部分来推进递归.

第二步最终将字符串减少到零长度,从而结束递归.或者,可以使用尾递归实现相同的过程- 不是因为CPython没有实现尾递归消除而在性能方面有任何不同.

def recVowelCount(s):
    def loop(s, acc):
        if not s:
            return acc
        return loop(s[1:], (1 if s[0] in 'aeiouAEIOU' else 0) + acc)
    loop(s, 0)
Run Code Online (Sandbox Code Playgroud)

只是为了好玩,如果我们删除解决方案必须递归的限制,这就是我解决它的方式:

def iterVowelCount(s):
    vowels = frozenset('aeiouAEIOU')
    return sum(1 for c in s if c in vowels)
Run Code Online (Sandbox Code Playgroud)

无论如何这工作:

recVowelCount('murcielago')
> 5

iterVowelCount('murcielago')
> 5
Run Code Online (Sandbox Code Playgroud)