#!/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)
Python实现24算法
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 狄克斯特拉算法介绍 Dijkstra(迪杰斯特拉)算法是典型的单源最短路径算法,用于计算一个节点到其他所有节点的最...
- 随着科技的快速发展和存储技术的飞速提升,使得我们生活在了数据的海洋,各行各业都积累着海量数据。我们如何利用这些数据...