THINK FIRST·CODE LATER

← All labs

Caching with a time-to-live

Problem

Simulate st.cache_data(ttl=...). Input: ttl T (seconds), cost C (seconds per database query), then requests TIME KEY in increasing time.

A request is a hit if the key is cached and TIME − cached_time < T; otherwise the database is queried and the cache entry is refreshed. Print per request t= 10 district=Lucheng: cache hit (data 10 s old) or t= 0 district=Lucheng: query database (2.5 s) (time right-aligned in 4 characters), then hits 3/7 (43%), database time 10 s instead of 17.5 s and worst-case staleness shown to users: 299 s (TTL 300 s).

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

v9-3-data-1.txt

ttl 300
cost 2.5
0 district=Lucheng
10 district=Lucheng
20 district=Ouhai
299 district=Lucheng
300 district=Lucheng
310 district=Ouhai
900 district=Ouhai
What your program must print for v9-3-data-1.txt
t=   0 district=Lucheng: query database (2.5 s)
t=  10 district=Lucheng: cache hit (data 10 s old)
t=  20 district=Ouhai: query database (2.5 s)
t= 299 district=Lucheng: cache hit (data 299 s old)
t= 300 district=Lucheng: query database (2.5 s)
t= 310 district=Ouhai: cache hit (data 290 s old)
t= 900 district=Ouhai: query database (2.5 s)
hits 3/7 (43%), database time 10 s instead of 17.5 s
worst-case staleness shown to users: 299 s (TTL 300 s)

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), in the folder that holds both files:

python my_lab.py < v9-3-data-1.txt

Windows PowerShell (the default terminal of VS Code on Windows) does not understand <:

Get-Content v9-3-data-1.txt | python my_lab.py

PyCharm: Run → Edit Configurations → tick Redirect input from and choose the file.

Jupyter: put this at the top of the cell that holds your program:

import sys
sys.stdin = open("v9-3-data-1.txt", encoding="utf-8")

Write it here, in Jupyter or in your IDE, then paste it. Run it on the sample input yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.