枚举

枚举

计算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
原文地址:https://www.cnblogs.com/huay/p/11667515.html