使用递归从字符串中删除元音

时间:2016-11-24 14:18:57

标签: python recursion

我想让我目前有递归的代码,以便查看每个字母并将其返回到空列表。到目前为止,我有这个,并希望使其递归。任何帮助表示赞赏。

VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")

def vowelRemoval(aString):

    if len(aString) == 0:
        return aString
    newString = ""
    for letter in aString:
        if letter not in VOWELS:
            newString += letter

    print(newString)

3 个答案:

答案 0 :(得分:3)

这是一种以递归方式从字符串中删除元音的方法:

def remove_vowels(s):
    if not s: 
        return s
    elif s[0] in "aeiouAEIOU": 
        return remove_vowels(s[1:]) 
    return s[0] + remove_vowels(s[1:]) 

print(remove_vowels("I have an apple"))

输出:

hv n ppl

答案 1 :(得分:1)

vowels = ['a', 'e', 'i', 'o', 'u']

def rem_vowels(word, new_word=''):
    if word == '':
        return new_word

    if word[0] not in vowels:
        new_word += word[0]

    return rem_vowels(word[1:], new_word)

w = rem_vowels('hello')

答案 2 :(得分:0)

字符串是列表和元组之类的序列。

这是一个递归版本,为了清晰起见,而不是速度:

VOWELS = 'aeiouyAEIOUY'


def vowelRemoval(s):
    if len(s) == 0:
        return ''
    c = '' if s[0] in VOWELS else s[0]
    return c + vowelRemoval(s[1:])

print(vowelRemoval('Hello World!'))

离开

Hll Wrld!