循环的新手问题

时间:2014-03-03 15:46:56

标签: python sum range

我试图在Python中执行以下任务时已经死了(3。)请帮忙。

编写一个循环,计算以下一系列数字的总和:1/30 + 2/29 + 3/27 +⋯+ 29/2 + 30/1。

for numerator in range(1, 31, 1):
    denominator = (31 - numerator)
    quotient = numerator / denominator
    print(quotient)

我可以产生每个的商,但是如何有效地找到总和却迷失了。

4 个答案:

答案 0 :(得分:4)

效率:

In [794]: sum(i*1.0/(31-i) for i in range(1, 31)) # i*1.0 is for backward compatibility with python2
Out[794]: 93.84460105853213

如果你必须明确地循环,请参阅@Bill的提示;)

答案 1 :(得分:0)

你快到了,所以我会给你一些提示。

# initialize a total variable to 0 before the loop

for numerator in range(1, 31, 1):
    denominator = (31 - numerator)
    quotient = numerator / denominator
    print(quotient)
    # update the total inside the loop (add the quotient to the total)

# print the total when the loop is complete

如果你想看到更多的Pythonic(idomatic)解决方案,请参阅zhangxaochen的回答。 ;)

答案 2 :(得分:0)

total = 0
for numerator in range(1, 31, 1):
    denominator = (31 - numerator)
    quotient = numerator / denominator
    print(quotient)
    total += quotient
print/return(total)

请注意,您将进行一些四舍五入,并可能得到您不期望的答案。

答案 3 :(得分:0)

这样做是为了跟踪总和。

total = 0

for numerator in range(1, 31, 1):
    denominator = (31 - numerator)
    quotient = numerator / denominator
    total = total + quotient

print(total)