python codekatas solutions | Cell 3 | Cell 5 | Search

The simplify_path function takes a Unix-style file path as input, splits it into tokens, and uses a stack to remove unnecessary directory references, returning the simplified path. The function handles various edge cases, including parent directories (..), multiple parent directories (...), and trailing slashes.

Cell 4

def simplify_path(path):
    """Simplify Unix-style file path."""
    stack = []
    tokens = [t for t in path.split('/') if t != '.' and t != '']
    for token in tokens:
        if token != '..':
            stack.append(token)
        elif stack:
            stack.pop()
    return '/'+'/'.join(stack)

assert simplify_path('/') == '/'
assert simplify_path('/../') == '/'
assert simplify_path('/...') == '/...'
assert simplify_path('/.../') == '/...'
assert simplify_path('/foo/..') == '/'
assert simplify_path('/foo///.//bar//') == '/foo/bar'
print('All passed!')

What the code could have been:

python
def simplify_path(path: str) -> str:
    """
    Simplify Unix-style file path.

    Args:
    path (str): Unix-style file path.

    Returns:
    str: Simplified file path.
    """
    stack = []
    tokens = [t for t in path.split('/') if t!= '.' and t!= '']
    
    # Iterate over each token in the path
    for token in tokens:
        # If the token is '..', pop the last element from the stack if it's not empty
        if token == '..':
            if stack:
                stack.pop()
        # If the token is not '.' or '', add it to the stack
        elif token:
            stack.append(token)
    
    # Join the elements in the stack with '/' and add a '/' at the beginning
    return '/' + '/'.join(stack)


assert simplify_path('/') == '/'
assert simplify_path('/../') == '/'
assert simplify_path('/...') == '/...'
assert simplify_path('/.../') == '/...'
assert simplify_path('/foo/..') == '/'
assert simplify_path('/foo///.//bar//') == '/foo/bar'
print('All passed!')

Code Breakdown

Function: simplify_path(path)

Purpose

Simplifies a Unix-style file path by removing unnecessary directory references.

Parameters

Return Value

The simplified file path.

Step-by-Step Explanation

  1. Split the path into tokens: The path.split('/') function breaks the path into a list of tokens, where each token represents a directory or an empty string.

  2. Initialize a stack: An empty stack is created to store the directory tokens.

  3. Process each token:

  4. Join the stack into a path: The simplified path is constructed by joining the tokens in the stack with / as the delimiter.

  5. Return the simplified path: The simplified path is returned as the result.

Example Use Cases