今天在啄木鸟社区阅读FP相关的文章,wiki.woodpecker.org.cn/moin/fp4python。 在最后,作者写了一个24点计算程序,挺好玩的。

但是算法不是很完整,我在百度Python贴吧上发现了一个比较犀利的程序段,更改了一下。 程序如下:

import itertools

formatList = ["((%f%s%f)%s%f)%s%f", "(%f%s%f)%s(%f%s%f)", 
                "(%f%s(%f%s%f))%s%f", "%f%s(%f%s%f%s%f)",
                "%f%s(%f%s(%f%s%f))"]

opList = itertools.product(['+', '-', '*', '/'], repeat = 3)
def match24(fmt, nums, ops):
    a, b, c, d = nums
    op1, op2, op3 = ops
    expr = fmt % (a, op1, b, op2, c, op3, d)
    try:
        res = eval(expr)
    except ZeroDivisionError:
        return 
    if abs(res - 24) < 0.0001:
        print expr, "= 24"
def calc(numlist):
    for op in opList:
        for fmt in formatList:
            match24(fmt, numlist, op)
if __name__ == '__main__':
    nums = raw_input("please input four numbers:\n")
    seq = [float(i) for i in nums.split(' ')]
    for l in itertools.permutations(seq):
        calc(l)

#END



blog comments powered by Disqus

Published

05 January 2015

Tags