谷歌面试题:两个玻璃球摔碎的楼层高度

原文链接:https://blog.csdn.net/hao050523/article/details/79283993

给你两个一摸一样的球,这两个球如果从一定的高度掉到地上有可能就会摔碎,当然,如果在这个高度以下往下扔,怎么都不会碎,当然超过这个高度肯定就一定摔碎了。现在已知这个恰巧摔碎高度范围在一层楼到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.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章