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

全部评论

相关推荐

去B座二楼砸水泥地:不过也可以理解,这种应该没参加过秋招
点赞 评论 收藏
分享
11-09 01:22
已编辑
东南大学 Java
高级特工穿山甲:羡慕,我秋招有家企业在茶馆组织线下面试,约我过去“喝茶详谈”😢结果我去了发现原来是人家喝茶我看着
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务