給定一個數字“p”,開發一個邏輯并撰寫一個 Python 程式來確定倒數之和 (1 1/2 1/3 ??? 1/n) 中的最小整數“n”,使總和大于'p'。列印 'n' 的值和總和 's'。
例如,當 p=3 時,倒數的和繼續相加,直到 s 的值變得大于 3 即 n 為 11
p=int(input())
new=0
for i in range(1,1000000):
term=1/i
sum1=new term
new=sum1
if sum1>p:
print(i,sum1)
break
我對如何設定范圍上限有疑問。我如何決定在這里面放什么?
uj5u.com熱心網友回復:
我對如何設定范圍上限有疑問。我如何決定在這里面放什么?
很高興您認識到這是代碼中的潛在問題!答案是:您不知道可能需要運行此回圈多少次。因此無法確定上限是多少。
for當您知道要回圈多少次時,回圈很有用。當您不確定應該回圈多少次時,是否可以使用另一種回圈?
uj5u.com熱心網友回復:
您可以使用while True帶有停止條件的無限回圈:
import itertools
p = 3
n, total = 0, 0
while True:
n = 1
total = 1 / n
if total > p:
break
print(n) # 11
另一種方法是使用itertools.count生成無限for回圈,并在滿足條件時停止它(通過break或return):
import itertools
def first_greater(p):
total = 0
for i, x in enumerate(itertools.count(1), start=1):
total = 1 / x
if total > p:
return i
print(first_greater(3)) # 11
更精簡的版本(或“函式式編程”方法):您可以使用itertools.countwith itertools.dropwhile(or itertools.takewhile)
import itertools
p = 3
series = itertools.accumulate(1 / x for x in itertools.count(1))
greaters = itertools.dropwhile(lambda x: x[1] <= p, enumerate(series, start=1))
print(next(greaters)[0]) # 11
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362957.html
下一篇:乘以2-Python
