Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

python - Recursive method to find the minimum number in a list of numbers

Given this sample list:

[5, 3, 9, 10, 8, 2, 7]

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a recursive implementation of 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     

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 minby several orders of magnitude.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...