Reputation: 63
I am trying to create a simple function that will take the summation numbers given an integer from 0. For example, If the user inputs the integer 3, the results would be 6, since 0 + 1 + 2 + 3 = 6.
What is the best/most efficient way to do this?
Eventually I want to create a loop that will do this for a list, where the user inputs the list [4, 5, 6] and the function would return [10, 15, 16].
Thanks in advance!
Upvotes: 0
Views: 1002
Reputation: 895
time complexity: O(n)
def get_sum(a):
return [n * (n + 1) / 2 for n in a]
if __name__ == '__main__':
print get_sum([4, 5, 6])
result: [10, 15, 21]
https://en.wikipedia.org/wiki/Triangular_number
Upvotes: 1
Reputation: 24052
There exists a closed form solution which has constant time (rather than linear time), which will be vastly faster than any iterative solution. The //
divide operator forces an integer result (in case you're using Python 3).
def mysum(n):
return n*(n+1)//2
If you want to apply this to a list, you can use map
:
def mysum2(li):
return map(mysum, li)
Or you can do it directly, without using mysum
(this will be fastest):
def mysum2(li):
return [n*(n+1)//2 for n in li]
The closed-form solutions will work on much larger values than the iterative solutions. For example:
>>> mysum2([4, 5, 6, 10000000000000])
[10, 15, 21, 50000000000005000000000000]
>>>
The solutions that use sum
will never return a result for a case like this.
Upvotes: 2
Reputation: 1325
The summation function would be useful here.
def findsum(x):
# The 0 is optional, but it makes it clear that you are starting from 0.
return sum(range(0, x + 1))
So for example:
>>> findsum(6)
21
Upvotes: 0
Reputation: 1423
For a single input, you can use
def summer(n):
# Create a list of numbers from 0 to n.
# The range function is an end-exclusive range
return sum(range(n+1))
For multiple inputs, use the map
function
def multisummer(ns):
return map(summer, ns)
Upvotes: 1