Skip to content

Instantly share code, notes, and snippets.

@jptalusan
Created February 26, 2026 23:29
Show Gist options
  • Select an option

  • Save jptalusan/39acb67a1682bf4df773bd463a30f219 to your computer and use it in GitHub Desktop.

Select an option

Save jptalusan/39acb67a1682bf4df773bd463a30f219 to your computer and use it in GitHub Desktop.
stopid, directionid to index
def build_pattern_index(pattern_by_direction: dict) -> dict:
   """Return a lookup mapping (stop_id, direction_id) to its position in the
   corresponding pattern list.
   ``pattern_by_direction`` is expected to be a mapping from direction IDs
   (usually strings like "0"/"1") to an iterable of Stop objects.  The
   returned dictionary uses a tuple key ``(stop_id, direction_id)`` and the
   value is the zero‑based sequence index of that stop within its pattern.
   Example::
       pattern_by_direction = {
           "0": [Stop("A", "0", ...), Stop("B", "0", ...)],
           "1": [Stop("C", "1", ...)],
       }
       build_pattern_index(pattern_by_direction)
       # -> { ("A", "0"): 0, ("B", "0"): 1, ("C", "1"): 0 }
   """
   lookup: dict = {}
   for direction, stops in pattern_by_direction.items():
       for idx, stop in enumerate(stops):
           # stops may already know their direction, but include the key for
           # safety/clarity
           key = (stop.stop_id, stop.direction_id or direction)
           lookup[key] = idx
   return lookup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment