Exercise 2 solution: a font payload budget checker ================================================== Save as budget.py and run with: py budget.py The sizes in FILES are illustrative numbers typed in by hand, not measurements of real fonts. ----- budget.py ----- """Exercise 2 solution: a font payload budget checker. py budget.py """ BUDGET_KB = 100 # total font budget for the page (an arbitrary example target) # file name, format, size in KB (illustrative numbers typed in by hand, not real fonts) FILES = [ ("body-regular", "woff2", 28), ("body-regular", "woff", 36), ("body-bold", "woff2", 29), ("body-bold", "ttf", 74), ("body-italic", "woff2", 30), ("heading-black", "woff2", 34), ("heading-black", "ttf", 88), ] PREFERENCE = ["woff2", "woff", "ttf"] # best first chosen = {} for name, fmt, kb in FILES: best = chosen.get(name) if best is None or PREFERENCE.index(fmt) < PREFERENCE.index(best[0]): chosen[name] = (fmt, kb) total = 0 print(f"{'font':<16}{'format':<8}{'KB':>5}") for name, (fmt, kb) in chosen.items(): print(f"{name:<16}{fmt:<8}{kb:>5}") total += kb print(f"{'total':<24}{total:>5}") if total <= BUDGET_KB: print(f"Within the {BUDGET_KB} KB budget by {BUDGET_KB - total} KB.") else: print(f"Over the {BUDGET_KB} KB budget by {total - BUDGET_KB} KB: drop a style or subset a file.") print("Candidate to drop first:", max(chosen, key=lambda n: chosen[n][1])) ----- output (run on Windows with Python 3.14.0) ----- font format KB body-regular woff2 28 body-bold woff2 29 body-italic woff2 30 heading-black woff2 34 total 121 Over the 100 KB budget by 21 KB: drop a style or subset a file. Candidate to drop first: heading-black How it works ------------ - PREFERENCE.index(fmt) turns "best format first" into a number, so a smaller index wins. Each font keeps only the best format on offer, as a browser would if you listed WOFF2 first in the src list. - The total is then compared with the budget, and if it is over, the biggest remaining file is suggested as the first thing to drop or subset. Ideas to extend it: read real file sizes with os.path.getsize, count requests as well as kilobytes, or add a second budget for the number of files.