Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?
Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user.
When you wrote the total function, we mentioned that R already has sum to do this; sum is much faster than the interpreted for loop because sum is coded in C to work with a vector of numbers. Many of R's functions work this way; the loop is hidden from you in C.
sum() function in Python Sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers.
You can use sum() to sum the values of an array.
a = [1,9,12]
print sum(a)
Well, I don't know if it is faster but you could try a little calculus to make it one operation. (N*(N+1))/2 gives you the sum of every number from 1 to N, and there are other formulas for solving more complex sums.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With