RnD
RnD

Reputation: 1182

How to add backwards in Python?

I have a number for example 35. Is there a function that does 35+34+33.....+1 = 630 I know there is cumsum but its more for arrays and not solid numbers.

Upvotes: 2

Views: 454

Answers (2)

Rory Daulton
Rory Daulton

Reputation: 22564

There is not quite a built-in function that does exactly that, but you can combine the sum function with a range object.

result = sum(range(35, 0, -1))

The -1 in that expression makes the range count backwards, so the sum starts with 35, it continues until it reaches 0 then stops (not including the 0 in the sum, though that does not matter here). Of course, the addition operator is associative and commutative, so the order does not matter theoretically. But this does what you asked, in the order you asked. There are, of course, also other ways to get the same result.

In a comment, you seem to say that you want to use the variable maxlen rather than the constant 35. Then just use

result = sum(range(maxlen, 0, -1))

Upvotes: 4

sanyassh
sanyassh

Reputation: 8540

With the power of math you can compute it efficiently:

result = 35 * (35 + 1) // 2  # 630

Upvotes: 6

Related Questions