Before publishing a chart, check that its colours have enough contrast for every reader, using the WCAG formula.
What to build
A program that computes the WCAG contrast ratio of two colours and checks the thresholds.
Requirements
- Print
ratio X:1with X to two decimals. - Then print
text AA: passif the ratio is at least 4.5, otherwisetext AA: fail, andgraphics: passif it is at least 3, otherwisegraphics: fail.
Input
One line: two six-digit hex colours.
Output
Three lines.
Constraints
Colours are valid #RRGGBB values in upper or lower case.
Example
Input:
#000000 #FFFFFF
Output:
ratio 21.00:1
text AA: pass
graphics: pass
Why it works
Relative luminance models how bright a colour looks to the eye, weighting green most, and the ratio of the two luminances (with a small offset for ambient light) measures how easily one stands out from the other.
Examples
#000000 #FFFFFF
ratio 21.00:1 text AA: pass graphics: pass
#777777 #ffffff
ratio 4.48:1 text AA: fail graphics: pass
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Linearise each channel: c ÷ 255, then c ÷ 12.92 if c ≤ 0.04045, otherwise ((c + 0.055) ÷ 1.055) ** 2.4.
Hint 2
L = 0.2126 R + 0.7152 G + 0.0722 B, using the linearised channels.
Hint 3
Put the larger luminance first: (L1 + 0.05) ÷ (L2 + 0.05).
Solution
Show one correct solution (try it yourself first)
def channel(c):
c = c / 255
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
def luminance(h):
r, g, b = (int(h[i:i + 2], 16) for i in (1, 3, 5))
return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b)
a, b = input().split()
l1, l2 = sorted([luminance(a), luminance(b)], reverse=True)
ratio = (l1 + 0.05) / (l2 + 0.05)
print(f"ratio {ratio:.2f}:1")
print("text AA:", "pass" if ratio >= 4.5 else "fail")
print("graphics:", "pass" if ratio >= 3 else "fail")