Python之计算24点

完整的代码如下:

# -*- coding: utf-8 -*-
import itertools

#with brackets
def with_brackets(lst, ops_lst):
    for op in ops_lst: #无括号时的运算情形
        expr1 = '('+lst[0]+op[0]+lst[1]+')'+op[1]+lst[2]+op[2]+lst[3]
        expr2 = '('+lst[0]+op[0]+lst[1]+op[1]+lst[2]+')'+op[2]+lst[3]
        expr3 = lst[0]+op[0]+'('+lst[1]+op[1]+lst[2]+')'+op[2]+lst[3]
        expr4 = '('+lst[0]+op[0]+lst[1]+')'+op[1]+'('+lst[2]+op[2]+lst[3]+')'

        for expr in [expr1, expr2, expr3, expr4]:
            try:
                t=eval(expr)
            except: #作除法时,跳过分母为0时的情形
                pass

            if abs(t-24) < 0.001:#float型数值计算存在微小的误差
                return expr
    return 0

#返回4个数计算24的方法
def hasMethod(numbers, ops_lst):
    for lst in itertools.permutations(numbers):
        lst = list(map(lambda x:str(x), lst))
        #without brackets
        for op in ops_lst:
            expr = lst[0]+op[0]+lst[1]+op[1]+lst[2]+op[2]+lst[3]
            if abs(eval(expr)-24) < 0.001:
                return expr
        #with brackets
        expr = with_brackets(lst, ops_lst)
        if expr != 0:
            return expr

    return 0

#返回4个数计算24的方法,无方法时返回"No Method"
def cal_24(numbers):
    ops = ['+','-','*','/']
    ops_lst = [[i,j,k] for i in ops for j in ops for k in ops]

    expr = hasMethod(numbers, ops_lst)
    if expr != 0:
        return expr
    else:
        return 'No method!'

#所有情况的计算24点的办法,并输出到文本文件
def main():

    outfile=open("H:\\24dian.txt","w")
    numbers_lst = [[i,j,k,l] for i in range(1,14) for j in range(1,14)\
                             for k in range(1,14) for l in range(1,14)]

    for numbers in numbers_lst:
        a = list(map(lambda x: str(x), numbers))
        methodInfo = "[%s,%s,%s,%s]: %s\n"%(a[0],a[1],a[2],a[3],cal_24(numbers))
        outfile.write(methodInfo)

    outfile.close()    

main() 

输出的文件如下:
这里写图片描述
所有的情况可查看文件:https://gitee.com/Jclian91/24DianJiJiSuan



本次分享到此结束,欢迎大家交流与批评~~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值