简体   繁体   English

Python,我怎样才能找到这些元素的总和?

[英]Python, how I can find sum of this elements?

Find the sum of n elements of the following row of numbers:求下列数字行的 n 个元素之和:
1, -0.5, 0.25, -0.125... 1、-0.5、0.25、-0.125...
The number of elements (n) is entered from the keyboard.从键盘输入元素的数量 (n)。

This will work:这将起作用:

row = "1, -0.5, 0.25, -0.125, 0.5, -0.14, 0.2, -0.34"
n = int(input())
nth_sum = sum(map(float, row.split(",")[:n]))

You're looking for something like this?你正在寻找这样的东西吗?

l = []
for i in range(int(input())):
    if i%2 ==0:
        l.append(1/2**i)
    else:
        l.append(-(1/2**i))
print(sum(l))

You can use the formula for the sum of a geometric series:您可以将公式用于几何级数的总和:

n = int(input('number: '))
result = -2 * (1 + 1/2 ** n ) / (1 + 1/2) - 2

sum([float(i) for i in input().split(', ')])

Assuming that the user enters a comma-separated (with a trailing space) list of numbers that can be parsed as valid floats.假设用户输入了一个以逗号分隔(带有尾随空格)的数字列表,这些数字可以被解析为有效的浮点数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM