|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# @Author: lock |
| 3 | +# @Date: 2017-06-09 22:48:14 |
| 4 | +# @Last Modified by: lock |
| 5 | +# @Last Modified time: 2017-06-10 01:48:16 |
| 6 | +# -*- coding: utf-8 -*- |
| 7 | +import optparse |
| 8 | +import itertools |
| 9 | +import random |
| 10 | + |
| 11 | + |
| 12 | +# 洗牌 |
| 13 | +def shuffle(n, m=-1): |
| 14 | + if m == -1: |
| 15 | + m = n |
| 16 | + l = range(n) |
| 17 | + for i in range(len(l) - 1): |
| 18 | + x = random.randint(i, len(l) - 1) |
| 19 | + l[x], l[i] = l[i], l[x] |
| 20 | + if i == m - 1: |
| 21 | + break |
| 22 | + return [l[idx] for idx in range(n) if idx >= 0 and idx < m] |
| 23 | + |
| 24 | + |
| 25 | +# 生成4张牌 |
| 26 | +def Get4Card(): |
| 27 | + card = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] * 4 |
| 28 | + cardidxs = shuffle(52, 4) |
| 29 | + return [card[idx] for idx in cardidxs] |
| 30 | + |
| 31 | + |
| 32 | +def GenAllExpr(card_4, ops_iter): |
| 33 | + try: |
| 34 | + while True: |
| 35 | + l = list(ops_iter.next()) + card_4 |
| 36 | + its = itertools.permutations(l, len(l)) |
| 37 | + try: |
| 38 | + while True: |
| 39 | + yield its.next() |
| 40 | + except StopIteration: |
| 41 | + pass |
| 42 | + except StopIteration: |
| 43 | + pass |
| 44 | + |
| 45 | + |
| 46 | +def CalcRes(expr, isprint=False): |
| 47 | + opmap = {'+': lambda a, b: a + b, '-': lambda a, b: a - b, '*': lambda a, b: a * b, |
| 48 | + '/': lambda a, b: a / (b + 0.0)} |
| 49 | + expr_stack = [] |
| 50 | + while expr: |
| 51 | + t = expr.pop(0) |
| 52 | + if type(t) == int: |
| 53 | + expr_stack.append(t) |
| 54 | + else: |
| 55 | + if len(expr_stack) < 2: |
| 56 | + return False |
| 57 | + else: |
| 58 | + a = expr_stack.pop() |
| 59 | + b = expr_stack.pop() |
| 60 | + if isprint: |
| 61 | + print a, t, b, '=', opmap[t](a, b) |
| 62 | + try: |
| 63 | + expr_stack.append(opmap[t](a, b)) |
| 64 | + except ZeroDivisionError: |
| 65 | + return False |
| 66 | + return expr_stack[0] |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + parser = optparse.OptionParser('usage -n 1,2,3,4') |
| 71 | + parser.add_option('-n', dest='nums', type='string', help='specify num list') |
| 72 | + (options, args) = parser.parse_args() |
| 73 | + nums = options.nums |
| 74 | + if nums is None: |
| 75 | + input_card = Get4Card() |
| 76 | + else: |
| 77 | + input_card = [int(x) for x in nums.split(',')] |
| 78 | + card = input_card |
| 79 | + if len(input_card) != 4: |
| 80 | + print(parser.usage) |
| 81 | + exit(0) |
| 82 | + print card |
| 83 | + ops = itertools.combinations_with_replacement('+-*/', 3) # 一个24点的计算公式可以表达成3个操作符的形式 |
| 84 | + allexpr = GenAllExpr(card, ops) # 数和操作符混合,得到所有可能序列 |
| 85 | + for expr in allexpr: |
| 86 | + res = CalcRes(list(expr)) |
| 87 | + if res and res == 24: |
| 88 | + CalcRes(list(expr), True) # 输出计算过程 |
| 89 | + print "Success" |
| 90 | + break |
0 commit comments