python想做一个24点游戏,请大神帮我做一个。真的感谢。做出来的。我可以给你钱。需要程序 方
发布网友
发布时间:2022-05-25 00:21
我来回答
共2个回答
热心网友
时间:2023-11-18 00:59
#!python
# vim:fileencoding=utf-8
# =weibo.com/niio=
#2016-04-22
#Theme:Python 24点智商矫正工具
#Memo:python2.7/开箱即用/玩得开薰 XD
######################
from itertools import combinations
import random
def bracket_exp(op, a, b):
return (op, a, b)
def remove_op(ops, op):
tmp = list(ops)
tmp.remove(op)
return tmp
def remove_nums(nums, number_combine):
tmp = list(nums)
for i in number_combine:
tmp.remove(i)
return tmp
def append(res_nums, exp):
tmp = list(res_nums)
tmp.append(exp)
return tmp
def evalexp(e):
if not isinstance(e, tuple):
return int(e)
else:
e1 = evalexp(e[1])
e2 = evalexp(e[2])
if e1 == None or e2 == None:
return None
if e[0] == '+':
return e1 + e2
elif e[0] == '-':
return e1 - e2
elif e[0] == '*':
return e1 * e2
elif e[0] == '/':
if e2 != 0 and e1 % e2 == 0:
return e1 / e2
else:
return None
else:
None
def fmtexp(e):
if not isinstance(e, tuple):
return e
else:
e1 = fmtexp(e[1])
e2 = fmtexp(e[2])
if e[0] == '+':
return '(%s + %s)' % (e1, e2)
elif e[0] == '-':
return '(%s - %s)' % (e1, e2)
elif e[0] == '*':
return '(%s * %s)' % (e1, e2)
elif e[0] == '/':
return '(%s / %s)' % (e1, e2)
else:
None
# r = evalexp(('+', '1', ('*', '4', ('-', '6', '8'))))
# r = fmtexp(('+', '1', ('*', '4', ('-', '6', '8'))))
def iter_all_exp(ops, nums, target):
if len(nums) == 1:
r = evalexp(nums[0])
if r and abs(r - target) < 0.001:
print fmtexp(nums[0]) , '=' + str(target)
return
for number_combine in combinations(nums, 2):
for op in ops:
res_ops = remove_op(ops, op)
res_nums = remove_nums(nums, number_combine)
exp = bracket_exp(op, number_combine[0], number_combine[1])
iter_all_exp(res_ops, append(res_nums, exp), target)
if op == '-' or op == '/':
exp = bracket_exp(op, number_combine[1], number_combine[0])
iter_all_exp(res_ops, append(res_nums, exp), target)
print "正在出题"
q =random.sample([1, 2, 3, 4, 5,6,7,8,9], 4)
print str(q[0])+"_"+ str(q[1])+"_"+str(q[2])+"_"+str(q[3])+"=24"
show=raw_input("题目不一定有解喔!,回车看答案")
if show=="":
iter_all_exp(["+", "-", "/", "*"], [q[0], q[1], q[2], q[3]], 24)
else:
print ""
热心网友
时间:2023-11-18 01:00
题目具体内容呢,没玩过这个游戏呀