2

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)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
joaolell
  • 375
  • 1
  • 5
  • 12
  • but you're overwriting `k` at each iteration, so in the end the result is just `(5*8+17)*2` – Jean-François Fabre Apr 20 '17 at 20:10
  • as mentioned before you are overwriting k in each step, instead of `k=...` you need to do `k += ...` or `k = k + ...` and add the initialization of `k=0` before the loop – Copperfield Apr 20 '17 at 20:50

4 Answers4

3

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
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

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
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
1

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

Frilox
  • 815
  • 2
  • 13
  • 24
0
#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
Prithviraj Mane
  • 230
  • 1
  • 15
  • this is unnecessary complicated, you don't need list or lambdas to solve it, the code of the OP is basically correct save for 2 little things. – Copperfield Apr 20 '17 at 20:47
  • yes, in this case lambda i not necessary but if expression becomes complex where we have iterable datatype then this method will definitely help – Prithviraj Mane Apr 20 '17 at 20:53