pythonadvanced15 minutes

Fix Bug in Advanced Recursive Directory Size Calculator

Debug and correct a broken Python function designed to recursively compute total file sizes in nested directory structures represented as dictionaries.

Challenge prompt

You are given a Python function that attempts to recursively calculate the total size of files in a nested directory-like dictionary structure. Each directory is represented by a dictionary where keys are names and values are either integers (file sizes in bytes) or nested dictionaries (subdirectories). The function intends to sum all file sizes under a given directory but currently returns incorrect results or throws errors for certain inputs. Your task is to debug and fix the function so that it correctly computes the total file size for any valid nested directory structure.

Guidance

  • Consider how the function differentiates between files (integers) and subdirectories (dictionaries).
  • Check for missing or incorrect recursive calls and aggregation logic.
  • Ensure the function handles edge cases like empty directories or mixed types correctly.

Hints

  • Use the built-in isinstance() function to distinguish between integers and dictionaries.
  • Verify that the recursive call returns a numerical value to be added to the running total.
  • Watch out for the case where the directory dictionary might be empty, which should return zero size.

Starter code

def calculate_directory_size(directory):
    total_size = 0
    for item in directory:
        if type(directory[item]) == dict:
            total_size += calculate_directory_size(item)
        else:
            total_size += directory[item]
    return total_size

Expected output

For input: { 'file1.txt': 1000, 'subfolder': { 'file2.txt': 2000, 'file3.txt': 3000, 'nested': { 'file4.txt': 1500 } }, 'file5.txt': 500 } The function should return: 8000

Core concepts

recursiontype checkingdictionary traversaldebugging

Challenge a Friend

Send this duel to someone else and see if they can solve it.