Unnecessary Recursive Calls

Here’s a recursive function that finds the greatest number from an array:

 def​ ​max​(array):
 if​ ​not​ array:
 return​ None
 
 if​ len(array) == 1:
 return​ array[0]
 
 if​ array[0] > max(array[1:]):
 return​ array[0]
 else​:
 return​ max(array[1:])

The essence of each recursive call is the comparison of a single number (array[0]) to the maximum number from the remainder of the array. (To calculate the maximum number from the remainder of the array, we call the very max function we’re in, which is what makes the function recursive.)

We achieve the comparison with a conditional statement. The first half of the conditional statement is as follows:

 if​ array[0] > max(array[1:]):
 return​ array[0] ...

Get A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.