Stacks

Previous part

Guided exercise: Let's write a short program that reads the input and prints the fully-qualified directory at each step.

cd /
cd a
cd b
cd ..
cd c
cd d
cd ..
cd ..
cd ..
cd e

Let's first observe the a natural way to solve this by hand. We start at the first line: cd /

Ok, we are in directory /

Next, the second line: cd a

Ok, we are in directory /a

The third line: cd b

We are in directory /a/b

The fourth line: cd ..

We go up one directory, back to /a

On and on we go. When we see cd directory, we append directory to the end of the path. When we see cd .., we remove one segment from the end of the path. Let's model this in python

INPUT = """cd /
cd a
cd b
cd ..
cd c
cd d
cd ..
cd ..
cd ..
cd e"""

path_segments = []

for line in INPUT.splitlines():
  # in this example, cmd is always "cd"
  cmd, directory = line.split(' ')

  if directory == "..":
    path_segments.pop()
  else:
    path_segments.append(directory)

  print("/".join(path_segments))

In computer science terms, we call path_segments a stack. A stack is a data structure that holds many elements, like a list, but only allows us to modify it by adding a new element to the end or removing the last element.

Stacks have numerous applications; here we have stumbled onto one of them. Stacks are useful for remembering where you've been while exploring a hierarchy, like a directory tree

If the computer science talk is still a little unclear, don't worry. As long as you understand the code, you're qualified to move on to the next exercise.