在数字列表中找到最小数字的递归方法 [英] Recursive method to find the minimum number in a list of numbers
本文介绍了在数字列表中找到最小数字的递归方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于此示例列表:
[5, 3, 9, 10, 8, 2, 7]
如何使用递归求最小数?答案是2
.
How to find the minimum number using recursion? The answer is 2
.
我在做递归练习时在试卷中发现了这一点.我想不出解决这个问题的方法.要找到它,我是否必须先对列表进行排序,然后递归地无事可做.谁能告诉我路径?
I found this in a question paper while I was doing recursion exercises. I can't figure out a way to solve this. To find it, do I have to sort the list first and then there's nothing to do recursively. Can any one show me a path?
推荐答案
这是min
的递归实现:
l=[5, 3, 9, 10, 8, 2, 7]
def find_min(l,current_minimum = None):
if not l:
return current_minimum
candidate=l.pop()
if current_minimum==None or candidate<current_minimum:
return find_min(l,candidate)
return find_min(l,current_minimum)
print find_min(l)
>>>
2
考虑到这不应在实际程序中使用,而应视为练习.性能会比内置的min
差几个数量级.
Take into account that this should not be used in real programs and should be treated as an exercise. The performance will be worse than the built-in min
by several orders of magnitude.
这篇关于在数字列表中找到最小数字的递归方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文