python:如何使用增量数对序列求和

标签 python sum series

n = int(input('Enter n: '))
count = 1
sum = 0
number = 1
while (count <= n):
    sum = sum + number
    count = count + 1
    number = number + 2
print('Sum =', sum)

是否可以对 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 .... + n 使用相同的概念

最佳答案

您可以使用列表理解来使其更加优雅和Pythonic:

def sum_series(start, end):
  return sum([i**2 for i in range(start, end+1)])

print(sum_series(1,10))

输出:

385

或者使用高阶函数:

>>> sum(map(lambda x: x**2, range(1,11)))
385

关于python:如何使用增量数对序列求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49460703/

相关文章:

java - 无法获取数组中的其余数字。 java

mysql - 按不同条件对同一个表中的多列求和,然后按日期分组

php - 处理学校 "letter days"的算法帮助函数。一个 6 天的重复周

matlab - 查找相同值的系列

python - 重命名 Pandas 系列中的某些值

python - 如何在python3上打印当前日期?

python - 使用 Paramiko 传输目录

c++ - 数字总和 C++

python - 将决策树直接转换为png

Python 3直方图: how to get counts and bins with plt. hist(),但不在屏幕上显示直方图?