Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 823
Padmal Avatar asked Dec 03 '25 23:12

Padmal


2 Answers

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.

like image 195
Sebastian Wozny Avatar answered Dec 07 '25 07:12

Sebastian Wozny


>>> 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.

like image 26
0x90 Avatar answered Dec 07 '25 05:12

0x90