2014-03-03 21 views
-1

我在嘗試在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) 

我可以產生每個商,但我失去了如何有效地找到總和。

+2

SO不是代碼生成器:) – Depado

+0

這是我第一次接觸編程。現在回頭看,這個問題很尷尬。 :-X – user3375537

回答

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 

如果您需要做的是,在一個循環明確,看到@比爾的提示;)

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的答案。 ;)

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

請注意您將會有一些四捨五入的情況發生,並可能得到一個您沒有預料到的答案。

0

這樣做是爲了跟蹤求和。

total = 0 

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

print(total)