Unit 4 Session 1 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What is the structure of the input?
"name"
key and a "materials"
key containing a list of strings.Q: What is the output?
Q: What should the function return if no brands use any materials?
Q: Are there any constraints on the input, such as the presence of the "materials"
key in each dictionary?
"name"
key and a "materials"
key with corresponding values.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate through the list of brands, and for each brand, iterate through its materials. Count the occurrences of each material using a dictionary.
1) Initialize an empty dictionary called `material_count`.
2) For each `brand` in `brands`:
a) For each `material` in `brand["materials"]`:
i) If the `material` is already in `material_count`, increment its count.
ii) If the `material` is not in `material_count`, add it with a count of 1.
3) Return the `material_count` dictionary.
**⚠️ Common Mistakes**
- Forgetting to correctly initialize the material count when encountering a material for the first time.
- Assuming that all brands will have materials without verifying.
def count_material_usage(brands):
material_count = {}
for brand in brands:
for material in brand["materials"]:
if material in material_count:
material_count[material] += 1
else:
material_count[material] = 1
return material_count