[原创]24点

duweifu posted @ 2011年3月10日 19:43 in Scrawl with tags python 24点 , 699 阅读

下了python3.1,写了一个24点的程序练手。

#! /usr/bin/env python
#coding=utf-8
import operator
import itertools
import functools

def compute(a, b, c, d, total):
    for guess_num in itertools.permutations([a,b,c,d], 4):
        for guess_op in itertools.product(['+','-','*','/'],repeat=3):
            tmp_list = [(num, op) for (num, op) in itertools.zip_longest(guess_num, guess_op, fillvalue='')]
            expression = functools.reduce(operator.add, map(lambda x : x[0] + x[1],tmp_list))
            res = eval(expression)
            if abs(float(res) - float(total)) < 0.001:
                print(expression + ' = ' + total)
                return
    print("None.")
       
if __name__ == '__main__':
    compute('2','11','9','8','24')

 

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter