import itertools import random import re # 计算出结果的函数 def solution(data): for i in itertools.permutations(data): for j in itertools.product(['+', '-', '*', '/'], repeat=3): li = [ f'(({i[0]}{j[0]}{i[1]}){j[1]}{i[2]}){j[2]}{i[3]}', f'({i[0]}{j[0]}{i[1]}){j[1]}({i[2]}{j[2]}{i[3]})', f'({i[0]}{j[0]}({i[1]}{j[1]}{i[2]})){j[2]}{i[3]}', f'{i[0]}{j[0]}(({i[1]}{j[1]}{i[2]}){j[2]}{i[3]})', f'{i[0]}{j[0]}({i[1]}{j[1]}({i[2]}{j[2]}{i[3]}))' ] for k in li: try: if eval(k) == 24: print(f'{k}=24') return True except ZeroDivisionError: pass return False #机器给人出题 def A2(): poke = [str(random.randint(1, 13)), str(random.randint(1, 13)), str(random.randint(1, 13)), str(random.randint(1, 13))] poke = sorted(poke) print(poke) expr = input("输入运算式:") li = re.split('[\+\-\*\/\(\)]', expr) li = sorted(li)[-4:] if len(li) == 4: if li == poke: if eval(expr) == 24: print("正确!") else: print('错误!') else: print("检测到错误,exit") else: print("请遵守规则") #人给机器出题 def A1(): print("规则:\n一、输入四个1-13的数字\n二、各个数字之间要使用空格") print("请给机器出题:") topic = input().split() for i in topic: i = int(i) if 1 <= i <= 13: topic = sorted(topic) flag = solution(topic) if flag: print("\n得出") break elif not flag: print("无法得出") break else: print("请输入1-13的数字") break #框架 while True: print("1.给机器出题") print("2.机器出题") print("3.退出") print("选择序号:") cmd = input() while True: if cmd == '1' or '2' or '3': break else: print("数据不规范,请重新输入!") if cmd == '1': A1() elif cmd == '2': A2() elif cmd == '3': break else: pass input("按回车退出")
python经典小游戏:24速算(案例)
最新推荐文章于 2024-07-08 16:02:16 发布