Skip to content
Advertisement

Python how to find the minimum number of moves for a directory iteration – crawler

I’m working on a Python(3) program in which I have to return the number of moves for a directory iteration by using the input as a list of multiple iterations denotes various actions like:

  • ../ denotes move to the parent folder of the current folder.
  • ./ remain in the same folder
  • x/ move to the child folder named x

Actually, I have to write a Python’s function to return an integer which shows the minimum number of steps to move to the main directory from the current folder. how can I achieve that?

so, here’s an example:

Input:

5
x/
y/
../
z/
./

Output:

2

Explanation: The crawler moves two folders down from the main directory to folder y, moves back up one folder, then moves down to another folder z, thus two moves is the right answer, one of the parent folder x and then to the parent directory and the first integer shows the total number moves. And here’s what I have tried:

def minimumSteps(loggedMoves):
    # Write your code here
    moves = 0
    for i in loggedMoves:
        print(loggedMoves[i:])
        if loggedMoves[i] == './' :
            moves += 1
    print(moves)
    return moves

Advertisement

Answer

You can build a stack of moves: ./ doesn’t do anything, ../ makes you go one level up, so we pop the last move, anything else adds a level.

Note that, as we don’t know the name of the directory we start from, we can only suppose that we can never go higher than it – otherwise, we couldn’t know if we come back down into it.

So, you could do:

def absolute_moves(moves):
    absolute = []
    for move in moves:
        move = move.strip('/') 
        if move == '.':
            continue
        elif move == '..': 
            try:
                # we go one level up
                absolute.pop()
            except IndexError:
                # we tried to go higher than the start dir
                pass # if we suppose we were at the top level
        else:
            absolute.append(move)
    return absolute

moves = ['x/', 'y/', '../', 'z/', './']
shortest = absolute_moves(moves)

print('Shortest path: {}, length: {}'.format(shortest, len(shortest)))
# Shortest path: ['x', 'z'], length: 2
Advertisement