import random,time
def getResult(a, b, oper):
if oper == '+':
return a + b
if oper == '-':
return a - b
elif oper == '*':
return a * b
elif oper == '/' :
return a / b
def express1(question, oper1, oper2, oper3):
"""计算((A_B)_C)_D的式"""
r1 = getResult(question[0], question[1], oper1)
r2 = getResult(r1, question[2], oper2)
r3 = getResult(r2, question[3], oper3)
return r3
def express2(question, oper1, oper2, oper3):
"""'计算(A_(B_C))_D的形式"""
r1 = getResult(question[1], question[2], oper2)
r2 = getResult(question[0], r1, oper1)
r3 = getResult(r2, question[3], oper3)
return r3
def express3(question, oper1, oper2, oper3):
"""计算A_(B_C)_D)的形式"""
r1 = getResult(question[1], question[2], oper2)
r2 = getResult(r1, question[3], oper3)
r3 = getResult(question[0], r2, oper1)
return r3
def express4(question, oper1, oper2, oper3):
"""计算A_(B_(C_D))的形式"""
r1 = getResult(question[2], question[3], oper3)
r2 = getResult(question[1], r1, oper2)
r3 = getResult(question[0], r2, oper1)
return r3
def express5(question, oper1, oper2, oper3):
"""计算(A_B)_(C_D)的形式:"""
r1 = getResult(question[0], question[1], oper1)
r2 = getResult(question[2], question[3], oper3)
r3 = getResult(r1, r2, oper2)
return r3
def getsolution(quetion):
"""4个操作数,则有3个操作符,进行全遍历求解"""
global haveQuestion, display
oper = ['+', '-', '*', '/']
for i in range(4):
for j in range(4):
for k in range(4):
if express1(quetion, oper[i], oper[j], oper[k]) == 24:
if display:
print("((%d%c%d)%c%d)%c%d" % (
quetion[0], oper[i], quetion[1], oper[j], quetion[2], oper[k], quetion[3]))
haveQuestion = True
if express2(quetion, oper[i], oper[j], oper[k]) == 24:
if display:
print("(%d%c(%d%c%d))%c%d" % (
quetion[0], oper[i], quetion[1], oper[j], quetion[2], oper[k], quetion[3]))
haveQuestion = True
if express3(quetion, oper[i], oper[j], oper[k]) == 24:
if display:
print("%d%c((%d%c%d)%c%d)" % (
quetion[0], oper[i], quetion[1], oper[j], quetion[2], oper[k], quetion[3]))
haveQuestion = True
if express4(quetion, oper[i], oper[j], oper[k]) == 24:
if display:
print("%d%c(%d%c(%d%c%d))" % (
quetion[0], oper[i], quetion[1], oper[j], quetion[2], oper[k], quetion[3]))
haveQuestion = True
if express5(quetion, oper[i], oper[j], oper[k]) == 24:
if display:
print("(%d%c%d)%c(%d%c%d)" % (
quetion[0], oper[i], quetion[1], oper[j], quetion[2], oper[k], quetion[3]))
haveQuestion = True
haveQuestion=0
display = 0
num=10
for m in range(num):
while True:
quetion = random.choices([i + 1 for i in range(12)], k=4)
getsolution(quetion)
if haveQuestion:
print("——————————共%d题——————————第%d题: %s"%(num,m+1,quetion))
time.sleep(10)
display = 1
print("第%d题:计算24点的方法如下:"%(m+1))
getsolution(quetion)
print()
time.sleep(1)
haveQuestion=False
display = 0
break