zoukankan      html  css  js  c++  java
  • 枚举

    枚举

    计算24点

    import itertools
    
    '''
    测试
    cards = [1, 1, 3, 6]
    四个元素的计算结果为24
    '''
    def twentyfour(cards):
        '''史上最短计算24点代码'''
        for nums in itertools.permutations(cards):  # 四个数(迭代获取所有随机组合)4!个
            for ops in itertools.product('+-*/', repeat=3):  # 三个运算符(可重复!)4**3个
                # 构造三种中缀表达式 (bsd)
                bds1 = '({0}{4}{1}){5}({2}{6}{3})'.format(*nums, *ops)  # (a+b)*(c-d)
                bds2 = '(({0}{4}{1}){5}{2}){6}{3}'.format(*nums, *ops)  # (a+b)*c-d
                bds3 = '{0}{4}({1}{5}({2}{6}{3}))'.format(*nums, *ops)  # a/(b-(c/d))
    
                for bds in [bds1, bds2, bds3]:  # 遍历
                    try:
                        if abs(eval(bds) - 24.0) < 1e-10:  # eval函数
                            return bds
                    except ZeroDivisionError:  #
                        # 零除错误!
                        continue
    
        return 'Not found!'
    
    
    # 测试
    cards = [1, 1, 3, 6]
    
    print(twentyfour(cards))
    View Code
  • 相关阅读:
    15、编写ORM
    14、细说协程
    COOKIE欺骗
    聪明的小羊
    re.S函数 python3
    截断上传
    sql百态01-post
    Why not?
    随机字符的本地爆破
    HTTP协议-请求头,响应头
  • 原文地址:https://www.cnblogs.com/huay/p/11667515.html
Copyright © 2011-2022 走看看