[面试算法]24点计算

小米2017秋招算法工程师笔试的最后一道题:

现在有一幅扑克牌,去掉大小王52张牌。随机选出4张牌,可以任意改变扑克牌的顺序,并填入 + - * / 四个运算符,不用考虑括号,除法按整数操作,计算过程中没有浮点数,问是否能够求值得到给定的数m。

现对这道题进行延申,求任意n个大于0数字的+ - * / 能否求得24点。代码如下:

def twentyFour(lst):
    #当列表内数量为0时,为错误输入,返回False
    if len(lst)==0:return False
    #当列表内只有1个数字且此数为24,返回True
    if len(lst)==1 and lst[0] == 24: 
        return True
    #当列表内只有1个数字且此数字不为24,返回False
    if len(lst)==1 and lst[0] != 24: 
        return False
    #对当前传入的数字做双重循环
    #对列表内每一个数字:
    for i in range(len(lst)):
        #和第i位置之后的数字尝试进行+-*/运算:
        for j in range(i+1,len(lst)-i):
            #拷贝得到lst副本
            newLst = lst[:]
            #对ij位置数据进行求和计算并储存到i位置中
            newLst[i] = lst[i]+lst[j]
            #用于测试输出
            print(str(lst[i])+'+'+str(lst[j]))
            #然后删除j
            del newLst[j]
            #对lst1重复进行此操作,若返回真,则为求得了24点
            if twentyFour(newLst) :return True

            newLst = lst[:]
            newLst[i] = lst[i]-lst[j]
            print(str(lst[i])+'-'+str(lst[j]))
            del newLst[j]
            if twentyFour(newLst) :return True


            newLst = lst[:]
            newLst[i] = lst[i]*lst[j]
            print(str(lst[i])+'*'+str(lst[j]))
            del newLst[j]
            if twentyFour(newLst) :return True

            #注意!分母不能为0
            if lst[j] != 0:
                newLst = lst[:]
                #注意!此处为整除
                newLst[i] = lst[i]//lst[j]
                print(str(lst[i])+'/'+str(lst[j]))
                del newLst[j]
                if twentyFour(newLst) :return True

    return False

print(twentyFour([1,2,3,4]) )
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值