今天得到app的一片文章中提到了一些面試題,其中有一Google面試題如下:
給你一個一摸一樣的球,這兩個球如果從一定的高度掉到地上有可能就會摔碎,當然,如果在這個高度以下往下扔,怎麼都不會碎,當然超過這個高度肯定就一定摔碎了。現在一直這個恰巧摔碎高度範圍在一層樓到100層樓之間。如何用最少的試驗次數,用這兩個玻璃球測試出摔碎的樓高。
文中給的答案是:
兩個球一個用來做粗調,一個用來做精調。首先哪一個球到10層樓去試,如果沒有摔碎,就去20層樓,每次增加10層樓。如果在某個十層摔碎了,比如60層,這就知道摔碎的高度在51-60層之間,接下來從51層開始一層層的試驗,這樣就可以保證不出20次,一定能測出恰巧摔碎玻璃球的高度。
那該如何確定粗調的step呢?於是寫了一段代碼,試驗下如何選取合適的step,使得平均試驗次數最少。
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.