How to sum up values of a for range function in python

Question:

Basically i want to sum up the result of the expression k=5x+17 but with different x, like (k=53+17) + (k=5*4+17) and so on… so far my code looks like the following.The result needs to be Σ which goes from the range (3,9).

for x in range(3,9):
    k=5*x+17
    k+=k
print(k)
Asked By: joaolell

||

Answers:

you’re overwriting k at each iteration, so in the end the result is just (5*8+17)*2

To perform such a sum, with x varying between 3 and 8 (9 is not included) so it in a generator comprehension and pass the result to sum, you’ll avoid the nasty side-effects like you just created.

result = sum(5*x+17 for x in range(3,9))

(of course if you want to include 9 you have to range from 3 to 10), so depending on the upper boundary, you get 267 or 329

You can also do that without using sum at all using the n*(n+1)//2 formula for sum of integers from 1 to n and adapting it a la project euler to reduce complexity:

start = 3
end = 9 # inclusive
result = ((end*(end+1))//2 - ((start-1)*(start))//2)*5 + (end-start+1)*17

Remembering that the sum of integers between 1 and n is n*(n+1)/2 and using some basic summation equalities, you can calculate the result directly:

>>> (3 + 9 - 1) * (9 - 3) // 2 * 5 + 17 * (9 - 3)
267
Answered By: Eric Duminil

For a range from i to j and an expression a*x+b, you can do:

a*(j-i)*(i+j-1)//2 + b*(j-i)

Because what you want is:

Σax+b = aΣx + Σb

Answered By: Frilox
#Use this simple code
l=[]
for x in range(3,9):
    y = lambda x :5*x+17
    l.append(y(x))

l =sum(l)
print l
Answered By: Prithviraj Mane
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.