CMU Coding Bootcamp
1COMPONENT_LENGTH = 3
2
3
4def blend(c1: int, c2: int) -> int:
5 """Get the median of 2 numbers."""
6 return round((c1 + c2) / 2)
7
8
9def splitColors(rgb: int) -> tuple[int, int, int]:
10 """Split an RGB value into its components."""
11 (r, g, b) = [
12 int(str(rgb).zfill(3 * COMPONENT_LENGTH)[i : i + COMPONENT_LENGTH])
13 for i in range(0, 3 * COMPONENT_LENGTH, COMPONENT_LENGTH)
14 ]
15 return (r, g, b)
16
17
18def blendColors(rgb1: int, rgb2: int) -> int:
19 """Blend two colors represented as RGB values."""
20 (r1, g1, b1) = splitColors(rgb1)
21 (r2, g2, b2) = splitColors(rgb2)
22 (r3, g3, b3) = [
23 blend(r1, r2),
24 blend(g1, g2),
25 blend(b1, b2),
26 ]
27 # Pad with leading zeros
28 (final_r, final_g, final_b) = [str(x).zfill(COMPONENT_LENGTH) for x in (r3, g3, b3)]
29 # Compose components and cast to integer
30 return int(final_r + final_g + final_b)
31
32
33print("Testing blendColors()...", end="")
34assert blendColors(204153050, 104000152) == 154076101
35assert blendColors(220153102, 151189051) == 186171076
36assert blendColors(153051153, 51204) == 76051178
37assert blendColors(123456789, 123456789) == 123456789
38assert blendColors(0, 0) == 0
39print("Passed!")