A base case is the part of a recursive function where it doesn't call itself. Designing a recursive function requires that you carefully choose a base case and make sure that every sequence of function calls eventually reaches a base case.
example: Calculating the Sum of a List of Numbers
def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])
How would I compute the sum of a list of numbers? If I were a mathematician,I might start by recalling that addition is a function that is defined for two parameters, a pair of numbers. To redefine the problem from adding a list to adding pairs of numbers, I could rewrite the list as a fully parenthesized expression. Such an expression looks like this:
total= (1+(3+(5+(7+9))))total= (1+(3+(5+16)))total= (1+(3+21))total= (1+24)total= 25
listSum(numList)=first(numList)+listSum(rest(numList))
In this equation first(numList) returns the first element of the list and rest(numList) returns a list of everything but the first element.
all recursive algorithms must obey three important laws:
- A recursive algorithm must have a base case.
- A recursive algorithm must change its state and move toward the base case.
- A recursive algorithm must call itself, recursively.