小米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]) )