給你兩個一摸一樣的球,這兩個球如果從一定的高度掉到地上有可能就會摔碎,當然,如果在這個高度以下往下扔,怎麼都不會碎,當然超過這個高度肯定就一定摔碎了。現在已知這個恰巧摔碎高度範圍在一層樓到100層樓之間。如何用最少的試驗次數,用這兩個玻璃球測試出摔碎的樓高。
兩個球,一個用來粗調,一個用來精調,具體做法是這樣的。
首先拿第一個球到10層樓去試,如果沒有摔碎,就去20層樓,每次增加10層樓。如果在某個十層樓摔碎了,比如60層,就知道摔碎的高度在51到60層之間,接下來從51層開始一層層地試驗,這樣就可以保證不出二十次,一定能試出恰巧摔碎的高度。
這是從統計學的角度來說,最完美的策略。從工程學的角度看,這是考察一個人有沒有掌握粗調和精調的方法,就像顯微鏡上有兩個旋鈕,第一個粗調,讓你大致看到圖像,第二個是精調,能讓你看清楚圖像。
stairs = int(input("Please input the total stairs: "))
def steps(step,target):
i = j = 0
while target > 0:
target -= step
i += 1
j = target + step
return i + j
steps_dict = dict()
for j in range(2,int(stairs/2) + 1,1):
sum = 0.0
for i in range(1,stairs + 1,1):
sum += steps(j,i)
print("step: %d, mean steps: %f" % (j, sum/stairs))
steps_dict[j] = sum/stairs
temp_key = ""
temp_steps = stairs
for key in steps_dict.keys():
if temp_steps > steps_dict[key]:
temp_steps = steps_dict[key]
temp_key = key
print("The best step should be %d and the mean steps is %f." % (temp_key, temp_steps))
運行結果:
PS F:\for_project\python> python .\steps_google.py
Please input the total stairs: 100
The best step should be 10 and the mean steps is 11.000000.
PS F:\for_project\python> python .\steps_google.py
Please input the total stairs: 1000
The best step should be 32 and the mean steps is 32.532000.
PS F:\for_project\python> python .\steps_google.py
Please input the total stairs: 200
The best step should be 14 and the mean steps is 15.050000.