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:

JavaScript

Output:

JavaScript

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:

JavaScript

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:

JavaScript
Advertisement