Python: Recursive function to find the largest number in the list

前端 未结 10 645
长情又很酷
长情又很酷 2020-12-10 21:04

I\'m trying to do a lab work from the textbook Zelle Python Programming

The question asked me to \"write and test a recursive function max() to find the

相关标签:
10条回答
  • 2020-12-10 21:20

    I post a different solution approach of the problem. Most of the answers manipulate the list using the slice operator in each recursive call. By the time the exercise does not provide a strict function prototype to be used, I also pass as function parameter the length of the list.

    Suppose that we try to find and return the maximum element from a sequence S, of n elements.

    Function prototype: Max(S, n)

    Base case: If S contains only one item, return it. (Obviously the only item in the sequence is the max one.)

    Recur: If not the base case, call Max each time for one less item, that is call Max(S, n-1). We then store the returning value to a variable called previous that indicate the previous element from the sequence and check that value with the next element in the sequence, which is the right most element in the current recursive call, and return the max of these values.

    A recursion trace of the above procedure is given in the following figure. Suppose we try to find the max from a list that contains [5, 10, 20, 11, 3].

    Note: To help you further, keep in mind that we recursively iterate the list from the right most element to the left most one.

    Finally here is the working code:

    def find_max_recursively(S, n):                                                
        """Find the maximum element in a sequence S, of n elements."""             
        if n == 1:  # reached the left most item                                   
            return S[n-1]                                                          
        else:                                                                      
            previous = find_max_recursively(S, n-1)                                
            current = S[n-1]                                                       
            if previous > current:                                                 
                return previous                                                    
            else:                                                                  
                return current                                                     
    
    
    if __name__ == '__main__':                                                     
        print(find_max_recursively([5, 10, 20, 11, 3], 5)) 
    

    Note: The recursive implementation will work by default only with sequences of 1000 most elements.

    To combat against infinite recursions, the designers of Python made an intentional decision to limit the overall number of function activations that can be simultaneously active. The precise value of this limit depends upon the Python distribution, but a typical default value is 1000. If this limit is reached, the Python interpreter raises a RuntimeError with a message, maximum recursion depth exceeded.

    Michael T. Goodrich (2013), Data Structures and Algorithms in Python, Wiley

    To change the default value do:

    import sys
    sys.setrecursionlimit(1000000)
    
    0 讨论(0)
  • 2020-12-10 21:21

    The basic approach is this.

    1. If the list contains only a single element, that element is the max. Return it immediately.
    2. Otherwise, the list contains multiple elements. Either the first element in the list is the maximum, or it is not.
    3. The maximum of the first element is simply the first element in the list.
    4. Recursively call Max on the rest (all but first element) to find the maximum of those elements.
    5. Compare the results from step 3 and 4. The result is the number that is greater. Return it.

    Right now you have some syntax errors. For example, you have two else clauses for a single if, and the indentation looks funny. You can only have one else for an if block. But if you follow these instructions, you should have a working algorithm.

    0 讨论(0)
  • 2020-12-10 21:27

    here is one more approach to solve above problem

    def maximum(L):
        if len(L) == 1:
            return L[0]
        else:
            return max(L[0],maximum(L[1:]))
    

    so example input and output:

    L= [2,4,6,23,1,46]
    print maximum(L)
    

    produces

    46
    
    0 讨论(0)
  • 2020-12-10 21:30

    Your understanding of how recursion works seems fine.

    Your if-block is messed up, you have two elses to one if and the alignment is out. You need to remove your first else and un-indent everything below the if one level. eg:

    def Max(list):
        if len(list) == 1:
            return list[0]
        else:
            m = Max(list[1:])
            return m if m > list[0] else list[0]
    
    def main():
        list = eval(raw_input(" please enter a list of numbers: "))
        print("the largest number is: ", Max(list))
    
    main()
    
    0 讨论(0)
提交回复
热议问题