Lets take a problem statement stating : Take a LIST of integers and find SUM of the numbers of the list.Suppose that you want to calculate the sum of a list of numbers such as: [1,2,3,4,5].In normal mathematical form,we might have solve this problem by using the addition rule of adding a pair of numbers.We might have converted the list into fully parenthesized expression
and solved it using parenthesis rule to get the total of 15.
Now think how can we solve it using a python program?We can solve it using two ways.
def function1(list1): theSum=0 for i in list1: theSum+=i print(theSum)
The function uses variable
theSum to get total of all the numbers in the list by starting with 0 and adding each number in the list.
def listsum(list1): if len(list1) == 1: return list1 else: return list1 + listsum(list1[1:]) print(listsum([1,3,5,7,9]))
This is a recursive algorithm.Here list1 is the sum of the first element of the list (i.e list1) and the sum of rest of the numbers in the list(i.e list1[1:]).
In the code,in line 2 we are checking if the list contains only one element.This is necessary to check because by knowing this we can escape from the function.The sum of the list containinig only one number is the number in the list.
On line 5 of the code function calls itself.This is called recursive function.A recursive function is a function that calls itself.This makes our code more simple.