Sum from 1 to n, 2 to n, … n in python

2019-09-21 20:07发布

问题:

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 out what's wrong.

n=int(input())
sum=0
m=0
factorial=1

for i in range(1, n + 1):
    factorial *= i
    sum=factorial-m
    print(sum)

回答1:

One reasonably simple approach:

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

15
14
12
9
5


回答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 in range(series.size + 1):
    print(series[:i].sum())

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



标签: python sum