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)
2
  • but you're overwriting k at each iteration, so in the end the result is just (5*8+17)*2 Commented Apr 20, 2017 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 Commented Apr 20, 2017 at 20:50

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

1 Comment

@joaolell please remember to accept an answer if it solved your question.
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

Comments

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

Comments

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

2 Comments

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.
yes, in this case lambda i not necessary but if expression becomes complex where we have iterable datatype then this method will definitely help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.