Reputation: 4740
Just looking for a more efficient approach to adding a very large number in a list together. I know I can use the sum() function, but I'm wondering if there is any other better or efficient approach.
nums = list(range(17832931))
ans = sum(nums)
Thanks for your suggestions
Upvotes: 0
Views: 129
Reputation: 125
Okay, so everyone has answered. To sum from 1
to n
, @Nick's answer is the best advise.
But if you just have a iterable and want to sum of it. Just use the sum
function.
Remember not to convert it to list
or tuple
. Just use sum
in the iterable.
Here's what I mean:
nums = range(17832931)
ans = sum(nums)
When you convert the nums
to a list
, it takes O(n) time to do that; which is completely unnecessary.
Example:
nums = range(17832931)
ans = sum(nums) # takes O(n) time
# Total: O(n)
nums = list(range(17832931)) # takes O(n) time
ans = sum(nums) # takes O(n) time
# Total: O( 2n )
In python, there's no other function or method to optimize the sum of values.
However, if you can figure out what kind of values you have, then you do it in O(1) complexity by using some math formula. As @Nick used n(n+1)/2
Upvotes: 0
Reputation: 5788
nums = list(range(17832931))
ans = [*map(lambda N: (N*(N+1))/2, [nums[len(nums)-1]])]
print(ans)
Upvotes: 0
Reputation: 2296
One of the solution could be using Lambda
function. Refer this article
final_sum = sum(map(lambda x: x, list(range(26363637))))
print(final_sum)
# Output : 347520664752066
In the bove solution, I've used a lambda function
and mapped each value using map function and then uses inbuilt function sum
which will add each iterable and will return the sum
Upvotes: 1
Reputation: 1
You can use this approach :
sum = 0
number_list = list(range(26363637))
for number in number_list:
sum += number
print(sum)
Upvotes: 0
Reputation: 147166
If you're just trying to sum the numbers in a range, you can simply use (n-1)*n//2
. For example:
n = 100
print(sum(range(n)))
print((n-1)*n//2)
Output
4950
4950
Upvotes: 5