Как найти сумму всех элементов массива питон

На чтение 4 мин Просмотров 4.9к. Опубликовано

Python — это язык программирования, который предоставляет нам различные встроенные функции и методы для работы со списками. Одной из таких операций является нахождение суммы чисел в списке. Это может быть полезным, когда необходимо произвести анализ числовых данных, например, при подсчете среднего значения или нахождении суммы элементов, удовлетворяющих определенным условиям. В этой статье мы рассмотрим различные методы нахождения суммы чисел в списке Python.

Содержание

  1. Методы для нахождения суммы чисел в списке
  2. Использование цикла for
  3. Использование встроенной функции sum()
  4. Использование рекурсии
  5. Обработка исключений при нахождении суммы чисел в списке

Методы для нахождения суммы чисел в списке

Использование цикла for

Цикл for является одним из наиболее простых и часто используемых способов для нахождения суммы чисел в списке. Просто пройдитесь по каждому элементу списка и добавьте его к накопленной сумме.

Вот пример кода, который демонстрирует использование цикла for для нахождения суммы чисел в списке:

numbers = [1, 2, 3, 4, 5]
total = 0

for num in numbers:
    total += num

print("Сумма чисел в списке: ", total)

В этом примере мы создали список чисел от 1 до 5 и присвоили его переменной numbers. Затем мы создали переменную total и присвоили ей начальное значение 0. Затем мы проходим по каждому элементу списка numbers и добавляем его к переменной total. Наконец, мы выводим сумму чисел на экран.

Важно отметить, что мы должны инициализировать переменную total нулевым значением перед выполнением цикла, чтобы иметь место, куда добавлять числа. Если мы попытаемся добавить число к неинициализированной переменной, возникнет ошибка.

Цикл for также может использоваться для нахождения суммы чисел в многомерном списке. В этом случае нам нужно будет использовать вложенный цикл for, чтобы перебрать каждый элемент списка.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
total = 0

for row in matrix:
    for num in row:
        total += num

print("Сумма чисел в многомерном списке: ", total)

В этом примере мы создали многомерный список, содержащий три списка с числами. Затем мы создали переменную total и присвоили ей начальное значение 0. Затем мы используем два вложенных цикла for для перебора каждого элемента списка и добавления его к переменной total. Наконец, мы выводим сумму чисел на экран.

Использование встроенной функции sum()

Использование встроенной функции sum() для нахождения суммы чисел в списке является очень простым и эффективным способом. Функция sum() принимает один аргумент — итерируемый объект, такой как список, и возвращает сумму всех элементов в нем.

Простой пример использования функции sum() для нахождения суммы всех чисел в списке:

my_list = [1, 2, 3, 4, 5]
sum_of_list = sum(my_list)
print(sum_of_list)

Важно отметить, что функция sum() может работать только с итерируемыми объектами, элементы которых могут быть сложены. Если элементы списка не могут быть сложены, будет возбуждено исключение типа TypeError.

Использование рекурсии

Использование рекурсии — это еще один способ нахождения суммы чисел в списке Python. Рекурсия — это процесс вызова функцией самой себя. Для нахождения суммы чисел в списке при помощи рекурсии, необходимо реализовать функцию, которая будет вызывать саму себя до тех пор, пока не достигнет базового случая.

Пример реализации функции для нахождения суммы чисел в списке при помощи рекурсии:

numbers = [1, 2, 3, 4, 5]
result = recursive_sum(numbers)
print(result)

Здесь мы определяем функцию recursive_sum, которая принимает список чисел numbers. Если в списке остается только один элемент, то возвращаем его значение. В противном случае мы возвращаем сумму первого элемента списка и рекурсивного вызова функции для оставшейся части списка.

Хотя использование рекурсии для нахождения суммы чисел в списке может быть удобным и понятным, стоит иметь в виду, что это может привести к переполнению стека вызовов функций при больших списках. Поэтому, в большинстве случаев лучше использовать более эффективные методы, такие как использование встроенной функции sum() или цикла for.

Обработка исключений при нахождении суммы чисел в списке

При работе с данными, особенно с пользовательским вводом, всегда есть вероятность получения ошибочных данных. Для обработки ошибок при нахождении суммы чисел в списке можно использовать конструкцию try-except.

При использовании описанных выше методов для нахождения суммы чисел в списке возможны следующие ошибки:

  1. TypeError — возникает, если элемент списка не является числом.
  2. ValueError — возникает, если в списке есть пустые строки или нечисловые значения.

Для обработки этих ошибок можно использовать конструкцию try-except. Например, чтобы обработать ошибку TypeError, мы можем использовать следующий код:

numbers = [1, 2, 3, '4', 5]

total = 0
for num in numbers:
    try:
        total += num
    except TypeError:
        print(f"Элемент {num} не является числом")
print(f"Сумма чисел в списке: {total}")

В результате выполнения данного кода мы получим следующий вывод:

Элемент 4 не является числом
Сумма чисел в списке: 11

Обработка ошибок позволяет избежать прерывания работы программы при возникновении ошибок и предоставляет возможность корректно обработать их в процессе выполнения программы.

A simple way is to use the iter_tools permutation

# If you are given a list

numList = [1,2,3,4,5,6,7]

# and you are asked to find the number of three sums that add to a particular number

target = 10
# How you could come up with the answer?

from itertools import permutations

good_permutations = []

for p in permutations(numList, 3):
    if sum(p) == target:
        good_permutations.append(p)

print(good_permutations)

The result is:

[(1, 2, 7), (1, 3, 6), (1, 4, 5), (1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 1, 7), (2, 3, 
5), (2, 5, 3), (2, 7, 1), (3, 1, 6), (3, 2, 5), (3, 5, 2), (3, 6, 1), (4, 1, 5), (4, 
5, 1), (5, 1, 4), (5, 2, 3), (5, 3, 2), (5, 4, 1), (6, 1, 3), (6, 3, 1), (7, 1, 2), 
(7, 2, 1)]

Note that order matters — meaning 1, 2, 7 is also shown as 2, 1, 7 and 7, 1, 2. You can reduce this by using a set.

Given an array of integers, find the sum of its elements.

Examples:

Input : arr[] = {1, 2, 3}
Output : 6
Explanation: 1 + 2 + 3 = 6

Input : arr[] = {15, 12, 13, 10}
Output : 50

Method 1: Iterating through the array and adding each element to the sum variable and finally displaying the sum.

Python3

def _sum(arr):

    sum = 0

    for i in arr:

        sum = sum + i

    return(sum)

if __name__ == "__main__":

    arr = [12, 3, 4, 15]

    n = len(arr)

    ans = _sum(arr)

    print('Sum of the array is ', ans)

Output

Sum of the array is  34

Time complexity: O(n), 
Auxiliary Space: O(1)

Method 2: Using the built-in function sum(). Python provides an inbuilt function sum() which sums up the numbers in the list.

Syntax: 

sum(iterable) 

iterable: iterable can be anything list, tuples or dictionaries, but most importantly it should be numbered.

Python3

arr = [12, 3, 4, 15]

ans = sum(arr)

print('Sum of the array is ', ans)

Output

Sum of the array is  34

Time complexity: O(n) 
Auxiliary Space: O(1)

Method 3: Using the reduce method. Array.reduce() method is used to iterate over the array and get the summarized result from all elements of array.

Syntax:

reduce( function, Array );

Python

from functools import reduce

def _sum(arr):

    sum = reduce(lambda a, b: a+b, arr)

    return(sum)

arr = []

arr = [12, 3, 4, 15]

n = len(arr)

ans = _sum(arr)

print('Sum of the array is ', ans)

Output

('Sum of the array is ', 34)

Time complexity : O(n)
Auxiliary Space : O(1)

Example: Using enumerate function 

Python3

list1 = [12, 3, 4, 15];s=0

for i,a in enumerate(list1):

  s+=a

print(s)

Time complexity: O(n)
Auxiliary Space: O(1)

Approach: Divide and conquer

  1. Define a function that takes an array and two indices low and high.
  2. If low == high, return the element at that index.
  3. Calculate the midpoint of the array as mid = (low + high) // 2.
  4. Recursively find the sum of the left subarray as left_sum = sum_of_array(arr, low, mid).
  5. Recursively find the sum of the right subarray as right_sum = sum_of_array(arr, mid+1, high).
  6. Return the sum of the left and right subarrays as left_sum + right_sum.

Python3

def sum_of_array(arr, low, high):

    if low == high:

        return arr[low]

    mid = (low + high) // 2

    left_sum = sum_of_array(arr, low, mid)

    right_sum = sum_of_array(arr, mid+1, high)

    return left_sum + right_sum

arr = [1, 2, 3]

print(sum_of_array(arr, 0, len(arr)-1))

arr = [15, 12, 13, 10]

print(sum_of_array(arr, 0, len(arr)-1))

Time complexity: O(n log n), where n is the number of elements in the array.

Auxiliary space: O(log n), where n is the number of elements in the array. 

Please refer complete article on Program to find sum of elements in a given array for more details!

METHOD 5:Using counter method.

APPROACH:

This program finds the sum of an array using the Counter class from the collections module in Python. The Counter class is used to count the occurrences of elements in the input array. The program then iterates over the items in the counter and calculates the sum of the array.

ALGORITHM:

1.Import the collections module.
2.Initialize the input array arr.
3.Create a Counter object c from the input array.
4.Initialize a variable sum to 0.
5.Iterate over the items in c using the items() method.
6.Multiply the key (element) with its count (value) and add it to the sum variable.
7.Print the sum of the array.

Python3

from collections import Counter

arr = [12, 3, 4, 15]

c = Counter(arr)

sum = 0

for key, value in c.items():

    sum += key * value

print("Sum of the array is", sum)

Output

Sum of the array is 34

Time Complexity:

The time complexity of this program is O(n) where n is the length of the input array. This is because we need to iterate over all the elements in the array once to create the Counter object and then iterate over the items in the counter once to calculate the sum.

Space Complexity:

The space complexity of this program is O(n) where n is the length of the input array. This is because we need to create a Counter object to store the counts of elements in the array, which can take up to n space in the worst case. We also need a constant amount of extra space for the sum variable and the loop variables.

Last Updated :
26 Apr, 2023

Like Article

Save Article

Lists are very commonly used to store sequences of values (for example, numbers) in Python. When working with lists, it can be handy to know how to quickly get the sum of values in a list. For example, you have a list of your recorded footsteps in the last seven days and you want to know the total sum. In this tutorial, we will look at how to get the sum of the elements in a list in Python with the help of some examples.

How to get the sum of a list of numbers in Python?

sum of elements in a python list

You can use the python built-in sum() function to get the sum of list elements. Alternatively, you can use a loop to iterate through the list items and use a variable to keep track of the sum.

Let’s look at the above-mentioned methods with the help of some examples.

Using sum() to get the total in a list

The built-in sum() function in Python is used to return the sum of an iterable. To get the sum total of a list of numbers, you can pass the list as an argument to the sum() function.

# create a list
ls = [10, 15, 20, 25]
# sum of list elements
sum(ls)

Output:

70

We get the sum of the values in the list as a scaler value.

Note that the sum() function may result in loss of precision with extended sums of floating-point numbers. For example –

# create a list
ls = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
# sum of list elements
sum(ls)

Output:

0.8999999999999999

As an alternative, you can use the math standard library’s fsum() function to get an accurate sum of floating-point numbers and prevent loss of precision.

import math

# create a list
ls = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
# sum of list elements
math.fsum(ls)

Output:

0.9

We get the accurate result this time. For more on the fsum() function, refer to its documentation.

Using loop to get the sum

Alternatively, you can use the straightforward method of iterating through the list elements and keeping track of the sum.

# create a list
ls = [10, 15, 20, 25]
# use a loop to get the sum
total = 0
for item in ls:
    total += item
print(total)

Output:

70

We get the sum of the values in the list.

You might also be interested in –

  • Python – Find Average of values in a List
  • Python – Get median of a List
  • Find Mode of List in Python

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

To find the sum of numbers in an iterable in Python, we can

  • Use the built-in sum() function
  • Use a loop
  • Use recursion

In today’s post, we’ll discuss how to use each of the methods above and highlight some of the things to take note when using the built-in sum() function.

For our practice question, we’ll work on a function that accepts multiple inputs (of various data types) and returns the sum of all numerical inputs.

Here are some concepts we’ll cover in today’s post:

  • How to find sum of numbers in an iterable in Python
  • How to use recursion
  • The difference between the sum() and fsum() functions

Using the built-in sum() function

The easiest way to find the sum of numbers in an iterable is to use a built-in function called sum(). This function accepts two arguments – the iterable to sum and an optional value to add to the sum. Its syntax is as follows:

sum(iterable, value_to_add)

If the function is unable to sum the numbers in the iterable, it throws a TypeError exception. Let’s look at some examples:

Finding sum of numbers in a list, set, dictionary and tuple

#Sum numbers in a list
myList = [1, 2, 3.5, 2.1, 6]
print(sum(myList))

#Sum numbers in a set
mySet = {1, 5, 2.7, 8}
print(sum(mySet))

#Sum numbers in a dictionary
myDict = {1:101, 2:102, 3:103, 4:104}
print(sum(myDict))

#Sum numbers in a tuple
myTuple = (1, 2, 6.7, 1.1, 5)
print(sum(myTuple))

If you run the code above, you’ll get the following output:

14.6
16.7
10
15.799999999999999

The sum() function adds the numbers in an iterable and returns the result.

For instance, in the first example, the function adds the numbers in myList (1 + 2 + 3.5 + 2.1 + 6) and returns 14.6 as the result.

In the second example, the function adds the numbers in mySet (1 + 5 + 2.7 + 8) and returns 16.7 as the result.

In the third example, we pass a dictionary to the sum() function. When we do that, the function sums the keys of the dictionary, not the values. Hence, we get 1 + 2 + 3 + 4 = 10 as the result.

Finally, in the fourth example, the function sums the values in myTuple and returns the result. However, notice that the result is not exact? Instead of getting 1 + 2 + 6.7 + 1.1 + 5 = 15.8, we get 15.799999999999999.

This is not due to a bug in our code or in Python. Rather, it has to do with the way floating-point numbers (i.e. numbers with decimal parts) are represented in our computers. We’ve seen another example of this issue previously when we learned to square a number in Python.

If you are interested in finding out more about how floating-point numbers work, you can check out the following website: https://docs.python.org/3/tutorial/floatingpoint.html

If you need to ensure that you always get an exact result when finding the sum of floating-point numbers, you can use another function called fsum(). We’ll discuss this function in a later section.

Passing a second argument to the sum() function

Next, let’s look at an example of how the second argument for the sum() function works.

If we do not pass any value for the second argument, the sum() function simply adds the numbers in the iterable and returns the result. However, if we pass a value for the second argument, the function adds the value of the argument to the sum of numbers in the iterable. Let’s look at an example:

myList = [1, 2, 3.5, 2.1, 6]

#Without second argument
print(sum(myList))

#With second argument
print(sum(myList, 1000))

If you run the code above, you’ll get the following output:

14.6
1014.6

Passing invalid arguments to the sum() function

Last but not least, let’s look at what happens when we pass an invalid argument to the sum() function.

When that happens, the function throws a TypeError exception. Examples of invalid arguments include passing a string to the function, or passing a list that includes strings as elements.

For instance, the examples below will all give us a TypeError exception if we try to run them.

myString = '123456'
print(sum(myString))

myStrList = [1, 2, 3, '4', 5]
print(sum(myStrList))

myList = [1, 2, 3.5, 2.1, 6]
print(sum(myList, '100'))

myList2 = [1, 2, 3, 4, [1, 5]]
print(sum(myList2))

The first three examples fail as the sum() function does not work with strings. If we pass a string to the function, the function throws an exception. The last example fails as myList2 contains a nested list.

Using a loop

Now that we are familiar with the built-in sum() function, let’s proceed to discuss how we can use a loop to find the sum of numbers in an iterable.

The code below shows an example of using a for loop to sum the numbers in a list:

myList = [1, 2, 3.5, 2.1, 6]
sum = 0

for i in myList:
    sum += i

print(sum)

On lines 1 and 2, we declare and initialize two variables – myList and sum.

Next, we use a for loop to iterate through myList. For each element in myList, we add its value to sum (on line 5).

After we finish iterating through myList, we use the print() function (outside the for loop) to print the value of sum.

If you run the code above, you’ll get

14.6

as the output.

Using a for loop gives us more flexibility in terms of what we want to sum. For instance, if we use the built-in sum() function to sum the elements in a dictionary, it returns the sum of the keys in the dictionary. If we want to sum the values instead, we can use a for loop:

myDict = {1:101, 2:102, 3:103, 4:104}
sum = 0

for i in myDict:
    sum += myDict[i]

print(sum)

When we use a for loop to iterate through a dictionary, Python accesses the key of the items in the dictionary, not the value. For instance, in the for loop above, i stores the keys of the items in myDict.

If we want to sum the values of the items, we need to add myDict[i] (instead of i) to sum, as shown in line 5 above.

If you run the code above, you’ll get the following output:

410

The loop sums the values in myDict. Hence, we get 101 + 102 + 103 + 104 = 410 as the output.

Using recursion

Next, let’s discuss the final method to find the sum of numbers in an iterable. This method involves using recursion. We’ve discussed recursion multiple times in previous posts. If you are not familiar with recursion, you should definitely check out some of those posts (e.g. here and here).

Technically speaking, using recursion is kind of unnecessary in this case, as using the built-in sum() function or a simple loop is much more straightforward. However, recursion can be a very powerful technique for solving more complex questions like a Sudoku or permutation problem. Hence, it helps to see more examples of how recursion works, especially with easier questions like the current one.

As mentioned previously, recursion can be used to solve problems where solution to the problem relies on solving smaller instances of the same problem.

When it comes to finding the sum of numbers in an iterable, suppose we have a list with five numbers. We can find the sum of all five numbers by adding the first number to the sum of the remaining four numbers (a smaller instance of the same problem).

This can be easily implemented using recursion.

myList = [1, 2, 3.5]

def sumRec(iterToSum):
    if len(iterToSum) > 1:
        return iterToSum [0] + sumRec(iterToSum [1:])
    else:
        return iterToSum [0]

print(sumRec(myList))

Here, we first declare and initialize a list called myList.

Next, we define a function called sumRec() (from lines 3 to 7) that has one parameter – iterToSum.

Inside the function, we check if the length of iterToSum is greater than 1 (line 4). If it is, we add the first element in iterToSum (i.e. iterToSum [0]) to the result of sumRec(iterToSum[1:]) and return the sum (line 5).

sumRec(iterToSum[1:]) represents a smaller instance of sumRec(iterToSum).

While the latter sums all numbers in iterToSum, the former sums all elements except the first (as the slice [1:] selects all elements starting from index 1 to the end of the list).

We keep calling the sumRec() function recursively until the length of the list we pass to it is no longer greater than 1. When that happens, we have what is known as a base case (lines 6 and 7).

A base case is the case the stops the recursion. When the length of the list to sum is no longer greater than 1, we do not need to use recursion to find the sum of the elements in the list. As there is only one element in the list now, the sum is simply the number itself. For instance, the sum of [12] is simply 12.

Once we reach the base case, the recursion stops and the result is returned to the caller of each recursive call. This gives us the result of the sum of all numbers in the list.

To see how this works, let’s suppose we call the sumRec() function with [1, 2, 3.5] as the argument.

The recursive calls and return values are shown in the diagram below:

recursive function to find sum of numbers in iterable

Line 9 starts by calling sumRec([1, 2, 3.5]), which in turn calls sumRec([2, 3.5]), which calls sumRec([3.5]).

sumRec([3.5]) is the base case. It returns 3.5 to its caller sumRec([2, 3.5]).

sumRec([2, 3.5]) (which is not a base case) in turn returns 2 + sumRec([3.5]) = 2 + 3.5 = 5.5 to its caller sumRec([1, 2, 3.5]).

sumRec([1, 2, 3.5]) (which is also not a base case) returns 1 + sumRec([2, 3.5]) = 1 + 5.5 = 6.5 to its caller line 9.

Therefore, if you run the code above, you’ll get

6.5

as the output.

That’s it. That’s how recursion can be used to help us find the sum of numbers in an iterable. You may need to read through this section more than once to fully appreciate how recursion works.

Working with floating-point numbers

We’ve covered three main ways to find the sum of numbers in an iterable in Python. Now, let’s move on to a topic we skipped previously.

In the previous section, we learned to use the built-in sum() function to sum numbers in an iterable. While this function is very easy to use, we saw that it does not always return an exact value. For instance, when we pass the tuple (1, 2, 6.7, 1.1, 5) to the function, we get 15.799999999999999 as the output.

If it is crucial for us to get an exact answer when finding the sum of numbers in an iterable, we should use another built-in function – fsum().

This function is available in the math module.

Let’s look at an example:

import math

myTuple = (1, 2, 6.7, 1.1, 5)

#Using sum()
print(sum(myTuple))

#Using fsum()
print(math.fsum(myTuple))

If you run the code above, you’ll get the following output:

15.799999999999999
15.8

The fsum() is very similar to the sum() function. The main difference is that the fsum() function gives an exact output while the sum() function does not always do that.

Another difference is the fsum() does not have a second optional argument. Other than that, the two functions are very similar.

That’s it. We are now ready to proceed to the practice question for today.

Practice Question

Today’s practice question requires us to write a function called mySum() that prompts users to enter a list of values, separated by commas. The values entered can be of any data type. For instance, they can be text, symbols, or numbers. The function needs to return the sum of all the numbers entered. This sum should be rounded off to 2 decimal places.

Expected Results

To test your function, you can run the function and enter the following inputs:

1, 2, 3.1, 4, hello, [2, 3], #, $

The function should return 10.1 as the result.

Suggested Solution

The suggested solution is as follows:

Click to see the suggested solution

def mySum():
    userInput = input('Pleae enter the values, separated by commas: ')
    myList = userInput.split(',')

    result = 0

    for i in myList:
        try:
            result += float(i)
        except:
            pass

    return round(result, 2)

sumOfNumbers = mySum()
print(sumOfNumbers)

In the code above, we first define a function called mySum() on line 1.

Inside the function, we use the built-in input() function to prompt users for an input. This function prompts users for an input and returns the input as a string. We store this string in a variable called userInput.

Next, we use a built-in function called split() to split userInput into a list of substrings, using a comma (https://docs.python.org/3/library/stdtypes.html#str.split) as the delimiter. If the input string is '1, 2, 3, 4, 5', we’ll get ['1', ' 2', ' 3', ' 4', ' 5'] as the result, which we store in a variable called myList.

Next, we declare and initialise a variable called result.

We then use a for loop to iterate through myList.

Inside the for loop, we use a try-except statement to try converting i to a float. If that can be done, we add the value of the resulting float to result (line 9).

On the other hand, if i cannot be converted to a float, the float() function throws an exception and the except block is executed. Inside the except block (lines 10 to 11), we use the pass statement to indicate that we do not want to do anything when i cannot be converted to a float.

After we finish iterating through all the elements in myList, we use the round() function to round the sum to 2 decimal places and use the return statement to return the result.

With that, the function is complete.

Понравилась статья? Поделить с друзьями:
  • Как составить сочинение про мою школу на английском
  • Как составить европротокол для страховой
  • Как найти бездомных кошек
  • Как найти проекцию вектора ускорения на ось
  • Как в инстаграмме найти архивированное видео