Skip to content Skip to sidebar Skip to footer

Sum From 1 To N, 2 To N, ... N In Python

I was trying to get a series of sum from 1 to n, 2 to n, ..., and n For example, if n=5, then the result should be 15 14 12 9 5 Please comment for the code below. I can't figure ou

Solution 1:

One reasonably simple approach:

n = 5
s = sum(range(n+1))
for i inrange(n):
    s -= i
    print(s)

15141295

Solution 2:

I think you're confused with the logic of your problem, but if you want to get the sum from 1 to n you can do the following:

import numpy as np
series = np.arange(1, n)
for i inrange(series.size + 1):
    print(series[:i].sum())

if n = 5, the output will be: 0, 1, 3, 6, 10

Post a Comment for "Sum From 1 To N, 2 To N, ... N In Python"