Как найти сумму индексов питон

Usually, we require to find the sum of index, in which the particular value is located. There are many method to achieve that, using index() etc. But sometimes require to find all the indices of a particular value in case it has multiple occurrences in list. Lets discuss certain ways to do so.

Method #1 : Naive Method + sum() We can achieve this task by iterating through the list and check for that value and just append the value index in new list and print that. This is the basic brute force method to achieve this task. The sum() is used to perform sum of list. 

Python3

test_list = [1, 3, 4, 3, 6, 7]

print ("Original list : " + str(test_list))

res_list = []

for i in range(0, len(test_list)) :

    if test_list[i] == 3 :

        res_list.append(i)

res = sum(res_list)

print ("New indices summation : " + str(res))

Output : 

Original list : [1, 3, 4, 3, 6, 7]
New indices summation : 4

Time complexity: O(n) where n is the length of the test_list. The code uses a for loop to traverse the list and perform the necessary operation
Auxiliary space: O(m), where m is the number of occurrences of the element being searched in the list. This is because the space complexity is determined by the size of the res_list, which grows as the number of occurrences of the element being searched increases.

Method #2: Using list comprehension + sum() List comprehension is just the shorthand technique to achieve the brute force task, just uses lesser lines of codes to achieve the task and hence saves programmers time. The sum() is used to perform sum of list. 

Python3

test_list = [1, 3, 4, 3, 6, 7]

print ("Original list : " + str(test_list))

res_list = [i for i in range(len(test_list)) if test_list[i] == 3]

res = sum(res_list)

print ("New indices summation : " + str(res))

Output : 

Original list : [1, 3, 4, 3, 6, 7]
New indices summation : 4

Time complexity: O(n), where n is the length of the input list ‘test_list’, because the program loops over the input list once to find the indices of the elements equal to 3, and the length of the list is n.
Auxiliary space: O(m), where m is the number of indices where the element is 3. This is because the program creates a new list ‘res_list’ containing these indices, and the size of this list is proportional to the number of occurrences of the element 3 in the input list.

Method#3: Using reduce and lambda function With these function we can perform this task. We can use reduce to iterate over the list range and with lambda function checks if element is define value or not if then we add result with index of element else leave result. 

Python3

from  functools import reduce

Tlist = [1, 3, 4, 3, 6, 7]

print ("Original list : " + str(Tlist))

rang = len(Tlist)

res = reduce(lambda x, y : x + y if (Tlist[y] == 3) else x, range(rang), 0 )

print ("New indices summation : " + str(res))

Output:

Original list : [1, 3, 4, 3, 6, 7]
New indices summation : 4

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary space: O(m), where m is the number of indices

Method #4: Using for loop, without sum()

Python3

test_list = [1, 3, 4, 3, 6, 7]

print ("Original list : " + str(test_list))

res=0

for i in range(0, len(test_list)) :

    if test_list[i] == 3 :

        res+=i

print ("New indices summation : " + str(res))

Output

Original list : [1, 3, 4, 3, 6, 7]
New indices summation : 4

Method 5: Using numpy

  • Convert the list to a numpy array:
    The first step is to convert the original list to a numpy array using the np.array() function. This allows us to use numpy functions to manipulate the data.
  • Use the where() function to find the indices of the element:
    Next, we use the np.where() function to find the indices where the target element (in this case, 3) occurs in the numpy array. The where() function returns a tuple of arrays, one for each dimension of the input array. Since we’re working with a 1-dimensional array, we only need the first element of the tuple, which contains the indices.
  • Sum the indices:
    We then use the np.sum() function to sum the indices where the element occurs. This gives us the desired result.

Python3

import numpy as np

test_list = [1, 3, 4, 3, 6, 7]

print("Original list: " + str(test_list))

arr = np.array(test_list)

indices = np.where(arr == 3)[0]

res = np.sum(indices)

print("New indices summation: " + str(res))

Output:

Original list: [1, 3, 4, 3, 6, 7]
New indices summation: 4

Time Complexity: O(n + m)

  • Converting the list to a numpy array takes O(n) time, where n is the length of the list.
  • The np.where() function takes O(n) time to find the indices where the target element occurs in the numpy array.
  • The np.sum() function takes O(m) time to sum the indices, where m is the number of indices returned by np.where().
  • Therefore, the overall time complexity of the numpy approach is O(n + m).

Auxiliary Space: O(n + m)

  • Converting the list to a numpy array requires O(n) auxiliary space to store the numpy array.
  • The np.where() function returns an array of indices, which requires O(m) auxiliary space to store.
  • The np.sum() function requires constant auxiliary space.
  • Therefore, the overall auxiliary space complexity of the numpy approach is O(n + m).

Method #6: Using enumerate and for loop, without sum()

Use enumerate and a for loop to iterate over the list and calculate the sum of indices where the element occurs

Python3

test_list = [1, 3, 4, 3, 6, 7]

print("Original list: " + str(test_list))

indices_sum = 0

for i, x in enumerate(test_list):

    if x == 3:

        indices_sum += i

print("New indices summation: " + str(indices_sum))

Output

Original list: [1, 3, 4, 3, 6, 7]
New indices summation: 4

Time complexity: O(n) because it iterates over the entire list once. 
Auxiliary space: O(1) because it only uses a constant amount of extra memory to store the sum of indices.

Method #7: Using itertools:

Algorithm :

  1. Initialize the input list test_list with some values.
  2. Initialize a variable res to 0.
  3. Use the enumerate() function from the itertools module to create an iterator that yields pairs of (index, value) tuples for each element in the list.
  4. Use a generator expression with the sum() function to calculate the sum of the indices where the value is equal to 3.
  5. Print the sum value res.

Python3

import itertools

test_list = [1, 3, 4, 3, 6, 7]

print("Original list: " + str(test_list))

res = sum(idx for idx, val in enumerate(test_list) if val == 3)

print("New indices summation: " + str(res))

Output

Original list: [1, 3, 4, 3, 6, 7]
New indices summation: 4

The time complexity : O(N), where N is the length of the input list. This is because we need to iterate over the entire list once to check each element and its index.

The auxiliary space :O(1), as we are only using a constant amount of extra memory to store the index sum.

Last Updated :
28 Mar, 2023

Like Article

Save Article

import numpy as np
from itertools import product

a =[[1,2,3],[4,5,6],[3,3,3]]
p_t = np.array(a)
num_products = 3

rslt1 = sum (p_t[i, j] for i,j in product(range(num_products), repeat=2))

rslt2= sum (p_t[i, j] for i in range(num_products) for j in range(num_products))

Output:

rslt1
Out[79]: 30

rslt2
Out[80]: 30

For your first attempt, you can actually use itertools.product.

For your second attempt, Actually, your sum (p_t[i, j] for i in range(num_products) for j in range(num_products)) works from my side.


Generally, below two are equivalent when it comes to the product of two list

In [88]: [(i,j) for i in range(2) for j in range(3)]
Out[88]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]

In [89]: [x for x in product(range(2), range(3))]
Out[89]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]

#python #list #indexing #sum

#python #Список #индексирование #сумма

Вопрос:

Представьте:

 str = input( Muchos numeros separados por ',' : )
list = str.split(', ')

total = list(0)   list(1)   list(2) ... (Number of indexes in the anwer)
 

Как я могу заставить его суммировать все индексы списка?

Комментарии:

1. почему вы пытаетесь сложить строки вместе, когда у вас уже есть полная строка?

2. Никогда не используйте имена для ваших переменных, которые уже определены как встроенные, например str , и list потому, что эти встроенные будут перезаписаны. («Никогда» означает: если вы не можете представить очень, очень, очень вескую причину для этого)

Ответ №1:

Сначала сопоставьте int , затем sum :

 print(sum(map(int,input("Muchos numeros separados por ',' :").split(', '))))
 

Ответ №2:

Просто перебирая список, вы можете найти сумму всех элементов в списке:

 mylist = [1,2,3,4,5];
sum = 0;
for i in mylist: # i will be 1,2,3,4,5 each loop
  sum =i;
print(sum); # sum = 15
 

Если это не тот ответ, который вы ищете, можете ли вы лучше описать свою проблему?

Комментарии:

1. Это выдает мне ошибку: sum =i; TypeError: неподдерживаемые типы операндов для =: ‘int’ и ‘str’

Ответ №3:

 a = list(map(int, input("Enter list values:").split()))
sum1 = 0
for x in a: # iterating over the list
    sum1  = x
print(sum1)
 

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.

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

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