為什么這不起作用?:
def recursiveVowels(str):
vowels = ['a','e','i','o','u']
vowels_count =0
if len(str) == 0:
return vowels_count
elif str[0] in vowels:
vowels_count = 1
total_vowels = vowels_count recursiveVowels(str[1:])
# check if no of vowels are more than half the length of string
return total_vowels > (len(str)/2)
這將回傳False。
print(recursiveVowels("Targeiout"))
但如果我這樣做,它作業正常:
def recursiveVowels(str):
vowels = ['a','e','i','o','u']
vowels_count =0
if len(str) == 0:
return vowels_count
elif str[0] in vowels:
vowels_count = 1
total_vowels = vowels_count recursiveVowels(str[1:])
return total_vowels
# made a seperate function just to check if vowels are more than consonants
def isVowelsMore(str):
vowels = recursiveVowels(str)
return (len(str)/2) < vowels
這將回傳True:
print(isVowelsMore("Targeiout"))
需要一些概念上的清晰度。
uj5u.com熱心網友回復:
您的第一次遞回回傳布林值,因此當您呼叫此行時
total_vowels = vowels_count recursiveVowels(str[1:])
實際發生的是
total_vowels = vowels_count False
或者
total_vowels = vowels_count True
這意味著 total_vowels 值最多為 vowels_count 1(如果 recursiveVowels(str[1:]) 回傳 True),這意味著它最多為 2,因此對于任何長度超過 4 的字串,您的函式將回傳 false
希望我能提供幫助,請隨時在評論中要求任何澄清:)
uj5u.com熱心網友回復:
我同意其他人的觀點,即你的函式的第二個版本是要走的路,但我會這樣寫:
def isVowelsMore(string):
vowels = {'a', 'e', 'i', 'o', 'u'}
def recursiveVowels(string, index=0):
vowels_count = 0
if index >= len(string):
return vowels_count
if string[index] in vowels:
vowels_count = 1
return vowels_count recursiveVowels(string, index 1)
vowels = recursiveVowels(string)
return len(string) / 2 < vowels
添加該index變數是為了避免在每次遞回呼叫時創建一個新字串——您可以繼續這樣做并仍然使用上述框架。我還將您list的元音轉換為 aset以提高性能。我重命名了您的str變數,因為這是一個不應重新定義的 Python 內置名稱。
uj5u.com熱心網友回復:
在您的第一個示例中,您將回傳一個布林值。當與大于或小于一起使用時,False 被解釋為 0,True 被解釋為 1。(有關布林值如何成為整數子型別的更多資訊,請參閱有關數字型別的檔案)。
因此,您的第一個遞回函式是基于 ... 添加 1 或 0 total_vowels > (len(str)/2),這顯然不是您想要的。
我建議使用帶有包裝函式的第二個版本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/493072.html
