December 2023
Intermediate to advanced
504 pages
11h 43m
English
Thankfully, there’s an easy way to eliminate all these extra recursive calls. We’ll call max only once within our code, and save the result to a variable:
| | def max(array): |
| | if not array: |
| | return None |
| | |
| | if len(array) == 1: |
| | return array[0] |
| | |
| | # Calculate the max of the remainder of the array |
| | # and store it inside a variable: |
| | max_of_remainder = max(array[1:]) |
| | |
| | # Comparison of first number against this variable: |
| | if array[0] > max_of_remainder: |
| | return array[0] |
| | else: |
| | return max_of_remainder |
By implementing this simple modification, we end up calling max a mere four times. Try it out yourself by adding the print("RECURSION") line and running the code.
The trick here is that ...
Read now
Unlock full access