S2Q1 · Sum of Squares of Even Numbers¶
⚡ Quick Reference
Function: sum_of_squares_of_even(nums: list) -> int
Core idea: filter even numbers, square each one, sum them all.
Key rules:
- Even → x % 2 == 0
- Square → x**2
- Sum everything matching the condition
Problem Statement¶
Problem
Write a function sum_of_squares_of_even(nums) that returns the sum of squares of all even numbers in nums.
Example:
[1, 2, 3, 4, 5, 6]
56
Even numbers: 2, 4, 6 → squares: 4, 16, 36 → sum: 56
Solution approaches¶
def sum_of_squares_of_even(nums: list) -> int:
evens = filter(lambda x: x % 2 == 0, nums)
return sum(map(lambda x: x**2, evens))
filter selects even numbers; map squares them; sum totals them. Clean functional pipeline.
Explicit list comprehension - same result as the generator but materialises the list in memory first. For large lists, the generator approach is more memory-efficient.
Key takeaways¶
sum(x**2 for x in lst if cond)
The standard pattern for "filter then transform then sum". The condition goes inside the generator - no separate filter step needed.
Generator vs list comprehension
sum(x**2 for x in ...) uses a generator - values are computed one at a time without building a full list. sum([x**2 for x in ...]) builds the list first. For large inputs, generators use less memory.
filter + map + sum pipeline
Three separate operations chained together. Each function does one thing - filter selects, map transforms, sum aggregates. This separation of concerns makes each step independently readable.