如何解决我的递归函数总是返回None
这是一个递归函数,尝试返回一个项目出现在列表中的次数。以下是代码:
def count (item,l_ist2): # function that returns the number of times item appears in l_ist
# Base case: item appears 0 times
print (item in l_ist2)
if item in l_ist2 == False:
return 0
# Recursive case
elif item in l_ist2 == True:
l_ist2.remove(item)
print (l_ist2,"\n")
return count (item,l_ist2) + 1
list_for_task_2 = [5,56,2,57,46,5,345,345]
item = int (input ("Choose an item in the list [5,345]: "))
print ("The item",item,"appears",count(item,list_for_task_2),"time(s) in the list above.\n")
以某种方式,输出始终是:“项目5在上面的列表中出现 None
时间。”
在此先感谢可以帮助我回答这个问题的人!
P.S。我的这项任务特别要求递归编写代码。
解决方法
您的递归函数中有一种情况会静默返回None
;这就是造成问题的原因。
此外,您的递归使用python in
每次调用该函数时都会扫描整个序列...这可能不是您打算执行的操作。
我用一种机制代替了它,该机制从序列中弹出一个元素并将其与要计数的项目进行比较。这意味着现在递归的情况是序列是否为空。
def count (item,seq):
"""returns the number of times item appears in seq
"""
if not seq: # is the sequence empty or not
return 0
elif seq.pop() == item: # if not,pop an element and compares it to the item
return count(item,seq) + 1 # add 1 if found
else:
return count(item,seq) # do not add 1 if not found
list_for_task_2 = [5,56,2,57,46,5,345,345]
item = int(input ("Choose an item in the list [5,345]: "))
print("The item",item,"appears",count(item,list_for_task_2),"time(s) in the list above.\n")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。