

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Recursion
incomplete
2: Recursion Review
incomplete
3: Zipmap
incomplete
4: Recursion Quiz
incomplete
5: Nested Sum
incomplete
6: Recursion Review
incomplete
7: Recursion on a Tree
incomplete
8: Dangers of Recursion
incomplete
9: Recursion Practice
incomplete
10: Recursion Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Recursion is hard for all new developers. If you're struggling, that's okay! Take your time. That's why we're doing a few extra practice problems.
In Doc2Doc, users can process files or entire directories. We need to know the total size of those files and directories (measured in bytes).
Due to the nested nature of directories, we represent a root directory as a list of lists. Each list represents a directory, and each number represents the size of a file in that directory. For example, here's a directory that contains 2 files at the root level, then a nested directory with its own two files:
root: list[int | list] = [1, 2, [3, 4]]
print(sum_nested_list(root))
# 10
Here's a more complex example:
root
├── scripts.txt (5 bytes)
├── characters (dir)
│ ├── zuko.txt (6 bytes)
│ └── aang.txt (7 bytes)
└── seasons (dir)
├── season1 (dir)
│ ├── the_avatar_returns.docx (8 bytes)
│ └── the_southern_air_temple.docx (9 bytes)
└── season2_notes.txt (10 bytes)
Which would be represented as:
root: list[int | list] = [5, [6, 7], [[8, 9], 10]]
print(sum_nested_list(root))
# 45
Complete the sum_nested_list function. It takes a nested list of integers as input and should return the total size of all files in the list. It's a recursive function.
Here's some pseudocode to help you get started:
isinstance function can tell you if an item is an integer or a list:
isinstance(5, list)
# False
isinstance([5, 6], list)
# True