Python Standard Library Quiz: datetime, Decimal and Enums
Test yourself: 12 questions and three programs on Python's math, statistics, Decimal and random, datetime and zoneinfo, collections, text tools and enums.
- Course: Python study plan
- Module: The standard library in depth
- Kind: Checkpoint — cleared at 70%
- Reading time: 22 min
- Runtime: CPython 3.11
Checkpoint — The standard library in depth is the checkpoint that closes the The standard library in depth module: a graded quiz and whole-program exercises, passed at 70%.
Instructions
This checkpoint covers the whole module: math, statistics, Fraction, Decimal and seeded random; datetime arithmetic, parsing and formatting, aware datetimes and zoneinfo; deque, Counter arithmetic, OrderedDict for an LRU cache, ChainMap and namedtuple; textwrap, difflib, string.Template and the deeper re features; and enums with auto, IntEnum, StrEnum and Flag.
How it works. Twelve questions and three programs. You need 70% on the questions and every program accepted to clear the module. You can retake it as often as you like; your best score counts.
Before you start, make sure you can answer these from memory:
- Which
statisticsfunction is the sample standard deviation, and what does an empty input do? - Why is
Decimal("0.1")right andDecimal(0.1)wrong, and what doesquantizetake? - What does seeding
random.Random(42)guarantee, and why prefer an instance to the module functions? - What is the difference between
astimezoneandreplace(tzinfo=…)? - Which
OrderedDictmethod makes an LRU cache possible? - What does
Counter(a) - Counter(b)drop? - Why is
Status.ACTIVE == "active"false for a plainEnum, and which enum class makes it true?
The three programs are a statistics report built with exact and rounded arithmetic, a schedule calculator that converts between time zones and adds durations, and an LRU cache on OrderedDict driven by commands with an enum for the operation names.
Common questions
Why is Decimal("0.1") right and Decimal(0.1) wrong?
Decimal(0.1) converts the float, which already carries binary error, so it holds 0.1000000000000000055511151231257827… exactly. Decimal("0.1") is exactly one tenth. Build decimals from strings, then round with quantize(Decimal("0.01")), which takes a pattern for the number of places and an optional rounding mode.
Which OrderedDict method makes an LRU cache possible?
move_to_end(key), which moves a key to the end in O(1), so the most recently used entry is always last. Together with popitem(last=False), which removes the entry at the front, it gives O(1) updates and eviction; a plain dict has no move_to_end, and its popitem removes only the last entry.
What is the difference between astimezone and replace(tzinfo=...)?
astimezone(zone) converts an instant, changing the clock reading so it shows the same moment in another zone. replace(tzinfo=zone) keeps the reading and only labels it with a zone, which is right for attaching a zone to a naive value a user entered and wrong for converting.
Exercises
Statistics report
Read amounts as decimal strings with two decimals, one per line. Print the mean, median and population standard deviation computed by statistics over floats, each with three decimals; then the exact total as a Decimal sum of the strings; then the total rounded to whole units with quantize(Decimal("1"), rounding=ROUND_HALF_UP); then the mean as an exact Fraction of the total in cents over the count, reduced.
Input: at least one amount per line. Output: mean <m>, median <d>, pstdev <s>, total <t>, rounded <r>, exact-mean <p>/<q> (or exact-mean <n> when the denominator is 1).
10.00
20.50
30.00
prints
mean 20.167
median 20.500
pstdev 8.168
total 60.50
rounded 61
exact-mean 6050/3Schedule across zones
The first line is <zone> <ISO start datetime> — a meeting start as a wall-clock time in that zone. The following lines are either add <minutes> (shift the start by a timedelta), or in <zone> (print the current start converted to that zone in ISO format), or utc (print it in UTC). Use aware datetimes throughout.
Input: the first line, then commands. Output: one line per in and utc.
Asia/Kolkata 2024-03-10T09:00:00
utc
in Europe/London
add 90
in America/New_York
prints
2024-03-10T03:30:00+00:00
2024-03-10T03:30:00+00:00
2024-03-10T00:00:00-05:00Cache operations as an enum
Define Op(StrEnum) with members GET, PUT, DEL and SIZE whose values are the lower-case words (auto()). Parse each command's first word with Op(word) — an unknown word prints unknown op — and drive an LRU cache on OrderedDict of the given capacity: get k prints the value or -1, put k v, del k (prints deleted or missing), size prints the entry count. At the end print the keys from least to most recently used.
Input: the capacity, then commands. Output: the command results, then keys … (or keys none).
2
put a 1
put b 2
get a
put c 3
del b
size
flush
prints
1
missing
2
unknown op
keys a cIn this module: The standard library in depth
- math, statistics, fractions, decimal and random
- Dates and times — datetime, timedelta and zoneinfo
- collections in depth — deque, Counter, OrderedDict, ChainMap and the User classes
- Text-processing tools — textwrap, difflib, string.Template and re in depth
- Enums — Enum, IntEnum, StrEnum, Flag and auto
- Checkpoint — The standard library in depth (this lesson)
← Enums — Enum, IntEnum, StrEnum, Flag and auto · Reading and writing files — open, modes, encoding and with →