counts: dict[int, int] = {}
for value in [4, 1, 4, 2, 1]:
    counts[value] = counts.get(value, 0) + 1
    print("Read:", value, "Counts:", counts)
print("Count for missing key 9:", counts.get(9, 0))
print("Key 9 exists:", 9 in counts)

def count_target_segments(values: list[int], target: int) -> int:
    """Count nonempty contiguous segments with the requested sum.

    Args:
        values: Signed integer values in their original order.
        target: Required sum of each counted segment.

    Returns:
        The number of contiguous segments whose sum equals target.
    """
    prefix_counts = {0: 1}
    prefix = 0
    total = 0
    for value in values:
        prefix += value
        total += prefix_counts.get(prefix - target, 0)
        prefix_counts[prefix] = prefix_counts.get(prefix, 0) + 1
    return total


changes = [2, -1, 2, 1]
target = 3
prefix_counts = {0: 1}
prefix = 0
total = 0
print("index prefix needed matches total counts")
for index, value in enumerate(changes):
    prefix += value
    needed = prefix - target
    matches = prefix_counts.get(needed, 0)
    total += matches
    prefix_counts[prefix] = prefix_counts.get(prefix, 0) + 1
    print(index, prefix, needed, matches, total, prefix_counts)
print("Segment count:", count_target_segments(changes, target))

assert count_target_segments([], 0) == 0
assert count_target_segments([0], 0) == 1
assert count_target_segments([0, 0], 0) == 3
assert count_target_segments([2, -2, 2], 2) == 3
assert count_target_segments([5, 6], 1) == 0
print("Boundary checks passed.")
