抓住薛定谔的猫

Problem 抓住薛定谔的猫

问题描述:

在这里插入图片描述
思路1(注意:失败!):根据x与y之间的距离来决定步数,使得|y-x|最小。
代码如下:

def choose(x,y):
    d = {-1:abs(y-(x-1)),1:abs(y-(x+1)),10:abs(y-(x+10)),2:abs(y-(x*2))}
    #每次返回距离y更近的选择
    return min(d,key=d.get)

x , y = list(map(int,input().split()))
time = 0   #所花时间
while x != y:
    if choose(x,y) == 2:
        x*=2
    else:
        x+=choose(x,y)
    time+=1
print(time)

输出如下:
在这里插入图片描述
错误原因:每次寻找最快逼近y的步长会错失掉很多可能性,所以也反映了一个哲学问题 the fast does not always represent the best,漫漫人生路还是得有快有慢才行。

改进思路:从第一个数字开始 他可以产生四个结果,然后再每一个结果又产生四个结果,直到找到等于y的就结束** (像树一样)

代码如下:

#每次对Lisy中的元素做四个选择操作,返回列表至nums[-1]
def operate(List,digit):
    results = []
    for i in List:
        if i-1 >-1 and i-1 <110000 and digit[i-1] == 0 :
            results.append(i-1)
            digit[i-1] = 1
        if i+1 >-1 and i+1 <110000 and digit[i+1] == 0 :
            results.append(i+1)
            digit[i+1] = 1
        if i+10 >-1 and i-1 <110000 and digit[i+10] == 0 :
            results.append(i+10)
            digit[i+10] = 1
        if i*2 >-1 and i*2 <110000 and digit[i*2] == 0 :
            results.append(i*2)
            digit[i*2] = 1
    return  results

x , y = list(map(int,input().split()))
nums = []
digit = [0 for i in range(110000)]      #未避免数量级过大,而越过已经访问过的数字
nums.append(operate([x],digit))
time = 1
while y not in nums[-1]:            
    nums.append(operate(nums[-1],digit))
    time+=1
print(time)

输出结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值