我正在尝试编写一个递归程序,它返回一个非元音单词的字母串。我的代码现在打印出“大学”的所有非元音,但永远不会结束。有什么想法吗?
def removeVowels9(aString):
if len(aString) == 0:
return newString
else:
newString = aString[1:len(aString) + 1]
firstLetter = aString[0]
#print(firstLetter)
if firstLetter in "aeiouAEIOU":
return removeVowels9(newString)
else:
newString = newString + firstLetter
print(newString)
return removeVowels9(newString)
答案 0 :(得分:6)
显然,你永远不会遇到基本情况,因为你会得到一个NameError
(newString
尚未定义)。
为什么呢?让我们来看看你的第三个案例:
else: # starts with consonant
newString = newString + firstLetter # add first letter to the end?
return removeVowels9(newString) # repeat
一旦你删除了所有元音,这就会继续循环辅音,正如你应该从输出中看到的那样:
>>> removeVowels9("University")
iversityn
ersitynv
sitynvr
itynvrs
ynvrst # all vowels gone
nvrsty
vrstyn
rstynv
stynvr
tynvrs
ynvrst # just keeps looping
...
这是最小的修复:
>>> def removeVowels9(aString):
if len(aString) == 0:
return aString # aString, not newString
else:
newString = aString[1:len(aString) + 1]
firstLetter = aString[0]
#print(firstLetter)
if firstLetter in "aeiouAEIOU":
return removeVowels9(newString)
else:
return firstLetter + removeVowels9(newString) # add first letter back at start, after processing rest
>>> removeVowels9("University")
'nvrsty'
但这可能更整洁:
def remove_vowels(s):
"""Recursively remove vowels from the input."""
if not s: # empty string
return s
elif s[0] in "aeiouAEIOU": # first character is vowel
return remove_vowels(s[1:]) # skip first character and process rest
return s[0] + remove_vowels(s[1:]) # return first character and process rest
其中:
>>> remove_vowels("University")
'nvrsty'
请注意与变量名等的the style guide的兼容性。