Python 如何编写从列表中递归删除字符实例的函数?
我必须写一个函数,它接受一个列表,char得到一个列表,其中所有的char实例都被删除了 我只是在子列表方面没有什么进展。我用Java编程已经有一段时间了,但我对python还是新手 我的代码:Python 如何编写从列表中递归删除字符实例的函数?,python,Python,我必须写一个函数,它接受一个列表,char得到一个列表,其中所有的char实例都被删除了 我只是在子列表方面没有什么进展。我用Java编程已经有一段时间了,但我对python还是新手 我的代码: def my_remove(the_char, the_list): if the_list == []:#works return the_list if isinstance(the_list[0],list): #if the first element in
def my_remove(the_char, the_list):
if the_list == []:#works
return the_list
if isinstance(the_list[0],list): #if the first element in the list is, itself, a list
#remove the character from the first element/list and move on to other list elements in the main list
else:
print 'else'
return the_list
print 'regular return'
return the_list
有两种情况需要处理:
导入doctest
def删除(字、字符):
"""
>>>移除([['swan']、['elephant']、'snake']、'e')
[['swan'],['lphant'],'snak']
>>>移除(['swan'、[['elephant']]、['snake']]、'e')
['swan',['lphant']],['snak']]
"""
如果存在(单词、列表):
如果word=[]:
返回[]
头,尾=字[0],字[1:]
返回[删除(头部,字符)]+删除(尾部,字符)
如果存在(单词、str):
如果word='':
返回“”
头,尾=字[0],字[1:]
如果head==char:
返回删除(尾部,字符)
返回头部+移除(尾部,字符)
doctest.testmod()
这个递归问题(以及大多数问题)的关键在于理解-
在编号的注释中-
my\u remove
的结果与在列表尾部调用my\u remove
的结果组合起来,list[1://code>
my\u remove
my\u remove
组合您的问题明确指出不能使用helper函数。这很可能是一个糟糕的编程老师的表现。助手函数可以从程序中去除复杂性,从而获得一个无复杂性的头脑 给出了一些处理列表的通用函数-
def isEmpty(l):
return len(l) == 0
def isList(l):
return isinstance(l, list)
def head(l):
return l[0]
def tail(l):
return l[1:]
我们可以用更丰富的语义编写my_remove
,它可以立即将意图传达给读者-
def my_remove(x, lst):
if isEmpty(lst):
return lst
elif isList(head(lst)):
return my_remove(x, head(lst)) \
+ my_remove(x, tail(lst))
elif head(lst) == x:
return my_remove(x, tail(lst))
else:
return [ head(lst) ] + my_remove(x, tail(lst))
当然,输出是相同的-
print(my_remove('z', input))
# ['a','b','c','d']
这些助手可以进一步改进,以防止程序员误用。也就是说,提出一个
运行时警告是一个让你知道你在归纳推理中犯了错误的好方法-
def isEmpty(l):
return isList(l) and len(l) == 0
def isList(l):
return isinstance(l, list)
def head(l):
if isEmpty(l):
raise RuntimeWarning('head called on empty list')
else:
return l[0]
def tail(l):
if isEmpty(l):
raise RuntimeWarning('tail called on empty list')
else:
return l[1:]
你知道如何用Java编写递归函数吗?据我所知,Python中的结构基本相同。您必须编写递归函数吗?在收到答案后,请不要从根本上改变这个问题。我已回滚您的编辑。请不要通过破坏您的帖子为其他人做更多的工作。通过在Stack Exchange(SE)网络上发布,您已经在下授予SE分发内容的不可撤销权利(即,无论您未来的选择如何)。根据SE政策,分发非故意破坏版本。因此,任何故意破坏行为都将恢复原状。请参阅:。如果允许删除,在帖子下方左侧有一个“删除”按钮,但它只在浏览器中,而不是在移动应用程序中。如果你有不同的问题(用不同的语言…),只需简单地回答即可。完全改变一个问题,你不尊重那些花时间和精力回答原来问题的人。看看@user633183在他的答案中投入了多少。如果你完全改变这个问题,他所有的工作都是徒劳的……注意,如果任何元素(word
)既不是list
也不是str
,那么这个函数可以返回None
,除非它将列表展平。如何让列表中充满子列表?在elif isList(head(lst)):…
中,将my_remove(…)+my_remove(…)
大小写更改为[my_remove(…)]+my_remove(…)
def isEmpty(l):
return isList(l) and len(l) == 0
def isList(l):
return isinstance(l, list)
def head(l):
if isEmpty(l):
raise RuntimeWarning('head called on empty list')
else:
return l[0]
def tail(l):
if isEmpty(l):
raise RuntimeWarning('tail called on empty list')
else:
return l[1:]