#!/usr/bin/env python
# encoding: utf-8
"""
@author: 王小滔
@software: PyCharm
@file: 24.py
@time: 2019/10/20 22:50
"""
import itertools
import random
from typing import Any, Tuple
cardNum = [] # 存放随机牌组
listSet = [] # 存放随机牌组对
card_group = () # 调用牌组
symbols = ["+", "-", "*", "/"] # 存放运算符
card_one = 0
card_two = 0
cardThr = 0
cardFor = 0 # 存放卡牌信息
resultOne = 0
resultTwo = 0
resultThr = 0 # 存放运算计算结果
cardValue = [] # 保存结果打印信息
cardResult = [] # 存放运算结果
# 发牌器
def card_fun():
for n in range(4):
cardNum.append(int(random.random() * 100 % 13) + 1)
list_set = list(set(itertools.permutations(cardNum, 4)))
return list_set # 存放A(4,4)种排列方式的列表
# 计算方法
cardList = card_fun() # 将生成的四张牌所有排列顺序放入cardList中
def card_compute():
for m in range(len(cardList)):
card_list = cardList[m]
card1 = card_list[0]
card2 = card_list[1]
card3 = card_list[2]
card4 = card_list[3]
flag = False
# 下面的循环运算体系会有数学上逻辑上的报错,所以用try检测
try:
for s1 in symbols:
result1 = 0
if s1 == "+":
result1 = card1 + card2
elif s1 == "-":
result1 = card1 - card2
elif s1 == "*":
result1 = card1 * card2
elif s1 == "/":
result1 = card1 / card2
for s2 in symbols:
result2 = 0
if s2 == "+":
result2 = result1 + card3
elif s2 == "-":
result2 = result1 - card3
elif s2 == "*":
result2 = result1 * card3
elif s2 == "/":
result2 = result1 / card3
for s3 in symbols:
result3 = 0;
result_else = 0
if s3 == "+":
result3 = result2 + card4
result_else = card3 + card4
elif s3 == "-":
result3 = result2 - card4
result_else = card3 - card4
elif s3 == "*":
result3 = result2 * card4
result_else = card3 * card4
elif s3 == "/":
result3 = result2 / card4
result_else = card3 / card4
# 判断最终结果是否为24
if result3 == 24:
cardValue.append(
"((%s %s %s) %s %s ) %s %s = 24" % (card1, s1, card2, s2, card3, s3, card4))
flag = True
# 括号与括号的运算
elif result3 != 24 and 24 % result1 == 0:
for s4 in symbols:
result3 = 0
if s4 == "+":
result3 = result1 + result_else
elif s4 == "-":
result3 = result1 - result_else
elif s4 == "*":
result3 = result1 * result_else
elif s4 == "/":
result3 = result1 / result_else
if result3 == 24:
cardValue.append("(%s %s %s) %s (%s %s %s) = 24" % (
card1, s1, card2, s4, card3, s3, card4))
flag = True
if flag:
break
# 如果得到结果,就退出3次运算的循环
if flag:
break
if flag:
break
if flag:
break
except ZeroDivisionError:
pass
card_result = set(cardValue)
return card_result
# 执行主体
if __name__ == "__main__":
Compute = card_compute()
print("你手上的卡牌为:%s %s %s %s" % (cardList[0][0], cardList[0][1], cardList[0][2], cardList[0][3]))
print("这组卡牌共有 %s 种算法" % (len(Compute)))
print("---" * 10)
for i in Compute:
print(i)
网友评论