Comparing Adjacent Items

Adjacent pairs describe transitions between neighboring values. Count them by looking at the gaps between items.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Trace a change series
  2. Preserve intentional boundaries
  3. Print the pairs before deciding what they mean
  4. Use a saved previous reading with a one-pass source

A sequence of \(n\) items has \(\max(n-1,0)\) adjacent pairs. An empty sequence and a singleton both have none.

Trace a change series

Temperatures 6, 8, and 7 produce changes +2 and minus 1. There is no first change until the second reading arrives. Keep the previous reading and use each new reading exactly once. Enumerated iteration can attach useful source positions.

Preserve intentional boundaries

When readings are grouped by day, a comparison across midnight might be invalid. Reset the previous-value state at each new group. Use missing values and sentinels to keep the absence of a previous reading separate from a genuine temperature of zero.[1]

Print the pairs before deciding what they mean

Given readings [4, 7, 7, 3], the adjacent pairs are (4,7), (7,7), and (7,3). Subtracting the first value from the second yields [3,0,-4]. When detecting a strict decrease, only the final pair qualifies. For \(n \ge 1\) readings, there are exactly \(n-1\) differences. A singleton contains no transition, and an empty input has none either. Use equal neighboring values in tests to detect mistakes between a strict comparison and an inclusive one. A matching two-input iteration technique works if the two inputs are offset by one position.

Use a saved previous reading with a one-pass source

An indexed array allows access to positions \(i\) and \(i+1\). For a stream, take the first reading as the previous value, then process each incoming reading before replacing the previous value. Updating first would compare the reading with itself and return zero at every step. With timestamped records, the interpretation may depend on the distance between the two timestamps. A drop of four units over one second has a different rate from four units over one hour. Test what happens at a missing or duplicated timestamp before dividing by the elapsed time. The iterator contract explains why a streaming source may not support replay.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩