MediumPro challengePython

Composite

PythonDesign PatternsStructural

Composite lets you treat a single object and a group of objects through
the same interface — classically, files and directories.

Implement File.size() (returns its own size) and Directory.size()
(returns the sum of its children's sizes, recursively — children can
themselves be directories).

solve(tree_spec) builds the tree from a nested dict spec and returns the
total size of the root.

{'type': 'dir', 'name': 'root', 'children': [{'type': 'file', 'name': 'a.txt', 'size': 10}]}
10

Sample tests

Test #1A single file
Input: [{"name":"a.txt","size":10,"type":"file"}]
Output: 10
Test #2Directory with two files
Input: [{"name":"root","type":"dir","children":[{"name":"a.txt","size":10,"type":"file"},{"name":"b.txt","size":20,"type":"file"}]}]
Output: 30
Test #3Empty directory
Input: [{"name":"root","type":"dir","children":[]}]
Output: 0