2012-10-08 43 views
0

我需要使用遞歸來查找字符串中元音的數量。因此,如果輸入hello,我希望它返回2使用遞歸查找元音的數量

我遇到的問題是要去字符串中的下一個字符。

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

爲什麼它需要使用遞歸?這不是一個遞歸的好例子。 – wim

回答

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

在'aeiou'中用'if'hello'把問題解決了:'' –

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. 遞歸調用
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:]) 
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 - 3ND通話
hon - 4t^h通話
on - 5通話
n - 6通話
-

最後,當字符串爲空,則返回count最後一次通話(空)。

這被稱爲尾遞歸:http://en.wikipedia.org/wiki/Tail_call