• + 0 comments

    I've made a change to my Tree class so that I store parents as a list. But I'm still failing all the same case. I think I'm running into issues with the recurrence of the bendersPlay function, all the parent data is lost when this happens and the code goes into an infinite loop. Here's what I've got so far anyway.

    class Tree:
        def __init__(self, data, parents = []):
            self.branches = []
            self.data = data
            self.parents = parents
    
        def setChildren(self, paths):
            branches = []
            for path in paths:
                if self.data == path[0] and path[1] not in self.parents:
                    branch = Tree(path[1], self.parents + [self.data])
                    branch.setChildren(paths)
                    self.branches.append(branch)
        
        def hasBranches(self):
            if(self.branches):
                return(True)
            else:
                return(False)
        
        def getDepth(self, depth):
            depths = []
            if(self.hasBranches()):
                depth = depth + 1
                for branch in self.branches:
                    depths.append(branch.getDepth(depth))
            if(depths):
                return(max(depths))
            else:
                return(depth)
    
        def getBestMove(self):
            depths = {}
            max_key = 0
            if(self.branches):
                for branch in self.branches:
                    depths[branch.data] = branch.getDepth(0)
                max_key = max(depths, key=depths.get)
            return(max_key)
    
    #
    # Complete the bendersPlay function below.
    #
    def bendersPlay(n, paths, query, player = 'Bumi'):
        #
        # Write your code here.
        #
        if(player == 'Bumi'):
            player = 'Iroh'
        else:
            player = 'Bumi'
        depths = {}
        bestMoves = {}
        for i in query:
            tree = Tree(i)
            tree.setChildren(paths)
            tree.getDepth(0)
            depths[i] = tree.getDepth(0)
            bestMoves[i] = tree.getBestMove()
    
        total = sum(depths.values())
        max_key = max(depths, key=depths.get)
        max_value = max(depths.values()) 
    
        if max_value:
            query[query.index(max_key)] = bestMoves[max_key]
            player = bendersPlay(n, paths, query, player, )
    
        return(player)