题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
import operator
import sys
for line in sys.stdin:
a = line.strip().split()
a=[int(i) for i in a]
ops=[operator.add,operator.sub,operator.mul,operator.truediv]
All=[]
n=4
C=[]
def calc(a,A,C,deep):
if deep==3:
# print(C)
if A[3]==24:
return True
else:
return False
# select 2
for i in range(deep,n):
for j in range(i+1,n):
for op in ops:
#new
A_j=A[j]
A_i=A[i]
A_deep=A[deep]
if op ==operator.truediv or op ==operator.sub:
S=[[i,j],[j,i]]
else:
S=[[i,j]]
for i_hat,j_hat in S:
if op==operator.truediv and A[j_hat]==0:
...
else:
# C.append([A[i],op,A[j]])
A[j]=op(A[i_hat],A[j_hat])
#swap
A[i],A[deep]=A[deep],A[i]
if calc(0,A,C,deep+1):
return True
#recover
A[j],A[i],A[deep]=A_j,A_i,A_deep
# C.pop()
return False
success=False
res=calc(0,a,C,0)
if res:
success=True
if success:
print('true')
else:
print('false')

