Google扔玻璃球面试题

今天得到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.




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值