Finding sum of all numbers in list – Python

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

 (1+(2+(3+(4+5))))

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.

Solution 01:

def function1(list1):
        theSum=0
        for i in list1:
            theSum+=i
        print(theSum)

Explanation:

                        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.

Solution 02:

def listsum(list1):

      if len(list1) == 1:

           return list1[0]

      else:

           return list1[0] + listsum(list1[1:])

print(listsum([1,3,5,7,9]))

Explanation:

This is a recursive algorithm.Here list1 is the sum of the first element of the list (i.e list1[0]) and the sum of rest of the numbers in the list(i.e list1[1:]).

                                      listSum(list1)=first(list1)+listSum(rest(list1))

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s