题解 | #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')

全部评论

相关推荐

想润的芹菜人狠话不多:把其中一个老总放中间都会得罪另一个
点赞 评论 收藏
分享
三年之期已到我的offer快到碗里来:9硕都比不上9本
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务