Skip to content
Advertisement

How to use recursion to give the minimum integer in a list using python?

I am trying to write a recursive function called my_minimum that receives a list of integers as parameter and returns the minimum stored in the list. I am able to get the user to input integers separated by a space. However, it gives me a number totally unrelated to what I am trying to achieve.

For example if user list was: 67 89 45 34 23 3 45 67 78, it should give me give me 3 instead of 23.

def my_minimum(A, n):
    # if size = 0 means whole list
    # also if it has been traversed
    if (n == 1):
        return A[0]
    return min(A[n - 1], my_minimum(A, n - 1))

# Driver Code
if __name__ == '__main__':
    input_string= input("Enter a list element separated by space: ")
    A  = input_string.split()
    n = len(A)
    print(my_minimum(A, n))

Advertisement

Answer

This is a string comparison issue, not an issue with your recursion. The string "3" compares as greater than the string "23", just like "B" sorts after "AA" in lexicographical order.

Try converting your strings to integers if you want integer ordering:

A  = list(map(int, input_string.split()))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement