• + 0 comments

    So this is my function and a class for a tree data structure (python3). It works for the sample case but none of the other cases. I can't see why this wouldn't work.

    class Tree:
        def __init__(self, data):
            self.branches = []
            self.data = data
    
        def setChildren(self, paths):
            branches = []
            for path in paths:
                if self.data == path[0]:
                    branch = Tree(path[1])
                    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)
                # fptr.write('Branch Depths[' + str(self.data) + ']: ' + str(depths) + '\n')
            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()
    
        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)