Write a Python function that receives a list of dictionaries, each containing an energy consumption value in kWh and its source type (e.g., "grid", "renewable"), and returns the total COâ‚‚ emissions in metric tons using the appropriate emission factor for each source.
technical screen · 3-5 minutes
How to structure your answer
CIRCLES framework: Clarify inputs, Identify scope, Review data types, Calculate emissions, Communicate results, Evaluate edge cases, Summarize solution. Step‑by‑step: 1) Define emission factors dictionary; 2) Validate list and dict keys; 3) Iterate or vectorize to multiply kWh by factor; 4) Sum results; 5) Convert kWh to metric tons; 6) Return float.
Sample answer
To solve this, I first defined a dictionary mapping source types to emission factors (kg COâ‚‚/kWh). I validated the input list to ensure each element is a dictionary with required keys. Using a list comprehension, I multiplied each consumption value by its corresponding factor, handling missing or unknown sources by logging a warning and defaulting to a neutral factor. I summed the weighted emissions, converted the total from kg to metric tons, and returned the result as a float. I included unit tests covering typical, edge, and error cases, and documented the function with type hints and docstrings for maintainability. This approach ensures accurate, scalable, and auditable emissions calculations.
Key points to mention
- • Emission factor mapping per source type
- • Input validation and error handling
- • Unit conversion from kg to metric tons
- • Scalability (vectorized operations)
- • Documentation and testing
Common mistakes to avoid
- ✗ Hardcoding emission factors without reference
- ✗ Ignoring unit consistency (kWh vs kg CO₂)
- ✗ Not validating input data types