Python 3D Academyবাংলা

A time-based key-value store

🌍 In real life. A weather station in Sylhet writes down the temperature with the hour each time it changes: 24° at 8, 26° at 9, 29° at 12, 31° at 15 and 27° at 18. Someone asks: "what was it at 14:00?" No reading was taken then, but the answer is still clear: the latest reading at or before 14:00, which is 29° from 12:00.

The idea in one sentence: a time-based key-value store keeps, for every key, its values with the times they were set; to answer "what was the value at time t?" it binary-searches that key's sorted list of times for the last one at or before t.

Its words:

  • timestamp: the time a value was set; for each key, timestamps only grow
  • at or before: a reading at exactly t counts; one after t does not
  • bisect_right(times, t) (Chapter 43): how many times are ≤ t, so the reading wanted is at index one less

Step by step:

  1. set(key, value, timestamp): append the time and the value to that key's two lists (they stay sorted because time only moves forward)
  2. get(key, timestamp): i = bisect_right(times, timestamp)
  3. if i is 0, nothing was set yet: return ""; otherwise return values[i − 1]

Here are the station's hours on a shelf. bisect_right finds where 15 and 14 would go:

For 15 the answer is 4: four readings (8, 9, 12, 15) are at or before 15:00, so the value wanted is at index 3, the 15:00 reading itself. For 14 it is 3, so the value is at index 2, the 12:00 reading.

Why bisect_right and not bisect_left. bisect_left stops before an equal time, so for 15 it gives 3 and the store would answer with 12:00's reading although a reading was taken at exactly 15:00. bisect_right puts the search point after equal times, which is exactly "at or before".

What it costs, by counting. set appends to two lists: O(1). get is one binary search: a station with 1,000,000 readings for one key needs about 20 halvings (2²⁰ is about 1,000,000), where scanning the list from the end could take 1,000,000 steps. Memory is O(n) for n readings, one time and one value each.

from bisect import bisect_right


class TimeMap:
    def __init__(self):
        self.times = {}                          # key -> its timestamps, in increasing order
        self.values = {}                         # key -> the value set at each of those times

    def set(self, key, value, timestamp):
        if key not in self.times:
            self.times[key], self.values[key] = [], []
        self.times[key].append(timestamp)        # timestamps only grow, so the list stays sorted
        self.values[key].append(value)

    def get(self, key, timestamp):
        times = self.times.get(key, [])
        i = bisect_right(times, timestamp)       # how many readings are at or before timestamp
        return self.values[key][i - 1] if i > 0 else ""

station = TimeMap()
for hour, temp in [(8, 24), (9, 26), (12, 29), (15, 31), (18, 27)]:
    station.set("sylhet", temp, hour)
print(station.get("sylhet", 14), station.get("sylhet", 15), station.get("sylhet", 7))
print(repr(station.get("dhaka", 10)))

Mistakes and edge cases.

  • bisect_left instead of bisect_right: a reading at exactly t is missed
  • returning values[i]: that is the next reading, after t, and it raises IndexError when t is past the last reading
  • a time before the first reading: i is 0, and values[-1] would quietly return the newest value; check i > 0
  • a key never set: use .get(key, []) so it answers "" instead of raising KeyError
  • sorting on every get: the lists are already sorted because time only grows; sorting again costs O(n log n) per call

Quiz

  1. What does this print?

    from bisect import bisect_left, bisect_right
    times = [8, 9, 12, 15, 18]
    print(bisect_left(times, 15), bisect_right(times, 15), bisect_right(times, 14))
  2. What does this print?

    from bisect import bisect_right
    
    
    class TimeMap:
        def __init__(self):
            self.times = {}                          # key -> its timestamps, in increasing order
            self.values = {}                         # key -> the value set at each of those times
    
        def set(self, key, value, timestamp):
            if key not in self.times:
                self.times[key], self.values[key] = [], []
            self.times[key].append(timestamp)        # timestamps only grow, so the list stays sorted
            self.values[key].append(value)
    
        def get(self, key, timestamp):
            times = self.times.get(key, [])
            i = bisect_right(times, timestamp)       # how many readings are at or before timestamp
            return self.values[key][i - 1] if i > 0 else ""
    
    m = TimeMap()
    m.set("x", "a", 1)
    m.set("x", "b", 4)
    print(m.get("x", 3), m.get("x", 4), m.get("x", 9), repr(m.get("x", 0)))
  3. What do set and get cost?

    • set O(1), get O(log n)
    • set O(n), get O(1)
    • Both O(n)
  4. Why does each key's list of times stay sorted without sorting it?

    • Timestamps for a key only grow, so each new time goes at the end
    • Python dicts keep their lists sorted
    • bisect sorts the list
  5. get(key, 0) returns the newest value instead of "" when nothing was set before time 0. Which line is wrong?

    def get(self, key, timestamp):
        times = self.times.get(key, [])
        if not times:
            return ""
        i = bisect_right(times, timestamp)
        return self.values[key][i - 1]

Coding tasks

  1. Write a class TimeMap with set(key, value, timestamp) and get(key, timestamp), which returns the value set for key at the largest timestamp at or before timestamp, or "" if there is none. Timestamps for each key only grow. get must take O(log n) time. Each test runs a list of calls on a new TimeMap and shows what each returns (set returns None).

  2. Write value_at(history, t): history is a list of (time, value) pairs sorted by time, with no time twice. Return the value of the latest pair whose time is at or before t, or None if every time is after t.