How to improve performance of this code?

前端 未结 7 766
一生所求
一生所求 2020-11-21 06:54

Thanks to some help from people here, I was able to get my code for Tasmanian camels puzzle working. However, it is horribly slow (I think. I\'m not sure because this is my

7条回答
  •  借酒劲吻你
    2020-11-21 07:29

    Well, I can't really say quite where your algorithm is running astray, but I just went ahead and made my own. In the interest of doing the simplest thing that could possibly work, I used a bastardized version of Dijkstra's algorithm, where open nodes are visited in arbitrary order, without consideration of distance. This means I don't have to come up with a heuristic.

    """ notation: a game state is a string containing angle
        brackets ('>' and '<') and blanks
     '>>> <<<'
    
     """
    
    def get_moves(game):
        result = []
        lg = len(game)
        for i in range(lg):
            if game[i] == '>':
                if i < lg-1 and game[i+1] == ' ': # '> ' -> ' >'
                    result.append(game[:i]+' >'+game[i+2:])
                if i < lg-2 and game[i+1] != ' ' and game[i+2] == ' ': # '>< ' -> ' <>'
                    result.append(game[:i]+' '+game[i+1]+'>'+game[i+3:])
            if game[i] == '<':
                if i >= 1 and game[i-1] == ' ': # ' <' -> '< '
                    result.append(game[:i-1]+'< '+game[i+1:])
                if i >= 2 and game[i-1] != ' ' and game[i-2] == ' ': # ' ><' -> '<> '
                    result.append(game[:i-2]+'<'+game[i-1]+' '+game[i+1:])
        return result
    
    
    
    def wander(start, stop):
        fringe = [start]
        paths = {}
    
        paths[start] = ()
    
        def visit(state):
          path = paths[state]
          moves = [move for move in get_moves(state) if move not in paths]
          for move in moves:
              paths[move] = paths[state] + (state,)
          fringe.extend(moves)
    
        while stop not in paths:
          visit(fringe.pop())
    
        print "still open: ", len(fringe)
        print "area covered: " , len(paths)
        return paths[stop] + (stop,)
    
    if __name__ == "__main__":
        start = '>>>> <<<<'
        stop = '<<<< >>>>'
        print start, "   -->   ", stop
        pathway = wander(start,stop)
        print len(pathway), "moves: ", pathway
    

提交回复
热议问题