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?
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.
>>> import random
>>> arr=[random.randint(0,8) for r in xrange(10)]
>>> arr
[8, 2, 5, 1, 2, 4, 0, 3, 1, 1]
>>> def func(arr):
if len(arr) == 1:
return arr[0]
else:
return min(arr[0],func(arr[1:]))
>>> f(arr)
0
NB the recursion isn't really needed here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With