python 24点

Posted on 2020-10-17 20:14  黑炽  阅读(226)  评论(0编辑  收藏  举报
 1 #事先声明,这里的 + - * / 按照的是 出现顺序直接计算,并没有考虑优先级
 2 def operator(a, op, b):
 3     if op == '+':
 4         return a+b
 5     elif op == '-':
 6         return a-b
 7     elif op == '*':
 8         return a*b
 9     else:
10         return a/b
11 
12 list_operator = ['+', '-', '*', '/']
13 card1, card2, card3, card4 = map(int, input('请输入四个扑克牌的大小: ').split(' '))
14 list_card = [card1, card2, card3, card4]
15 list_total = []#所有已经满足24点的式子
16 list_check = []#需要检查是否存在的式子
17 flag = 0#用来表示是否出现重复式子
18 
19 for i in range(len(list_card)):
20     for j in range(len(list_card)):
21         if i != j:
22             for t1 in range(len(list_operator)):
23                 sum1 = operator(list_card[i], list_operator[t1], list_card[j])
24                 for k in range(len(list_card)):
25                     if k != j and k != i:
26                         for t2 in range(len(list_operator)):
27                             sum2 = operator(sum1, list_operator[t2], list_card[k])
28                             for g in range(len(list_card)):
29                                 if g != k and g != i and g != j:
30                                     for t3 in range(len(list_operator)):
31                                         flag = 0#只在最后一个地方 清零即可,因为这里是必须经过的
32                                         list_check = []#把check列表也清空
33                                         sum3 = operator(sum2, list_operator[t3], list_card[g])
34                                         if sum3 == 24:
35                                             list_check.append(list_card[i])
36                                             list_check.append(list_operator[t1])
37                                             list_check.append(list_card[j])
38                                             list_check.append(list_operator[t2])
39                                             list_check.append(list_card[k])
40                                             list_check.append(list_operator[t3])
41                                             list_check.append(list_card[g])
42                                             #用来检查是否有重复的式子
43                                             for v in range(len(list_total)):
44                                                 if list_check == list_total[v]:
45                                                     flag = 1
46                                                     break
47                                             if flag == 1:#如果存在,那么就直接跳过这次输出
48                                                 break
49                                             print(list_card[i], list_operator[t1], list_card[j], list_operator[t2],
50                                                   list_card[k], list_operator[t3], list_card[g])
51                                             list_total.append(list_check)#在total列表的最后加上新式子
52 
53 
54 
55