如何编写一个递归函数,该函数接受一个列表并返回没有元音的相同列表? [英] How to write a recursive function that takes a list and return the same list without vowels?
问题描述
我应该编写一个递归函数,它接受一个字符串列表或一串字符串列表,并返回没有元音列表(如果找到)。这是我的尝试来解决它:
def noVow(seq):
keys = ['a','如果不是seq或不是isinstance(seq,list):
return
else:
如果按键中的seq [0]:
del seq [0]
return(noVow(seq [0:]))
else:
return(noVow(seq [1: ]))
li = [b,c,d,a]
print(noVow(li))
我知道这个错误在于我的基本情况,但是我无法想出正确的基本情况。注意递归函数必须用纯函数式编程来编写,即不允许使用副作用。
def no_vowel(seq):
如果不是isinstance(seq,list):
raise ValueError('Expected list,got {}'。格式(类型(seq)))
如果不是seq:
返回[]
头,*尾= seq
如果isinstance(头,列表):
return [[no_vowel(head)]] + no_vowel(tail)
else:
如果在'aeiou'头部:
return no_vowel(tail)
else:
return [head] + novowel(tail)
列表中很酷的解包是一个Python 3功能,与功能性编程模式匹配非常相似。
I am supposed to write a recursive function that takes a list of strings or a list of lists of strings and return the list without vowels, if found. Here is my attempt to solve it:
def noVow(seq):
keys = ['a','i','e','o','u','u']
if not seq or not isinstance(seq, list) :
return
else:
if seq[0] in keys:
del seq[0]
return (noVow(seq[0:]))
else:
return (noVow(seq[1:]))
li = ["b", "c", "d","a"]
print (noVow(li))
I am aware that the bug lies in my base case however I can't come up with the right base case.
Note that the recursive function has to be written in pure functional programming i.e. side effects are not allowed.
def no_vowel(seq):
if not isinstance(seq, list):
raise ValueError('Expected list, got {}'.format(type(seq)))
if not seq:
return []
head, *tail = seq
if isinstance(head, list):
return [[no_vowel(head)]] + no_vowel(tail)
else:
if head in 'aeiou':
return no_vowel(tail)
else:
return [head] + novowel(tail)
The cool unpacking of the list is a Python 3 feature, and is very similar to functional programmings pattern matching.
这篇关于如何编写一个递归函数,该函数接受一个列表并返回没有元音的相同列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!