Problem

Write a recursive Python function findMaxValMaxLoc() that takes an input list of numbers and returns, as a tuple, both the maximum value and the position (index) of maximum value in the input list. Your function should return None if the input array is an empty list. For example,

findMaxValMaxLoc([1,2,-3,4.5,2,-1])
(4.5, 3)
findMaxValMaxLoc([]) is None
True

Solution

Python
def findMaxValMaxLoc(array):

    lenArray = len(array)

    if lenArray>1:
        maxVal, maxLoc = findMaxValMaxLoc(array[1:])
        if array[0]>maxVal:
            return array[0], 0
        else:
            return maxVal, maxLoc + 1
    elif lenArray==1:
        return array[0], 0
    else: # lenArray < 1
        return None

Comments