Skip to content

Instantly share code, notes, and snippets.

@tfeldmann
Last active July 20, 2023 15:04
Show Gist options
  • Save tfeldmann/4edd3e0d0abc5e0f641f443ceb9906fd to your computer and use it in GitHub Desktop.
Save tfeldmann/4edd3e0d0abc5e0f641f443ceb9906fd to your computer and use it in GitHub Desktop.
Format consecutive numbers as ranges
from itertools import count, groupby
from typing import Iterable, Tuple
def group_consecutive(nums: Iterable[int]) -> Iterable[Tuple[int, ...]]:
counter = count()
for _, g_it in groupby(nums, lambda n: n - next(counter)):
yield tuple(g_it)
def format_consecutive_group(group: Tuple[int, ...], sep: str = "-") -> str:
if len(group) == 1:
return f"{group[0]}"
return f"{group[0]}{sep}{group[-1]}"
def format_consecutive(
nums: Iterable[int], sep: str = ",", range_sep: str = "-"
) -> str:
"""
>>> format_consecutive([1, 2, 3, 4, 8, 9, 10, 100, 200])
"1-4,8-10,100,200"
"""
groups = group_consecutive(sorted(nums))
return sep.join(format_consecutive_group(g, sep=range_sep) for g in groups)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment