Skip to content

Instantly share code, notes, and snippets.

@blzzua
Last active October 7, 2022 20:12
Show Gist options
  • Save blzzua/e03b994314464b2fffe879d4341c4f68 to your computer and use it in GitHub Desktop.
Save blzzua/e03b994314464b2fffe879d4341c4f68 to your computer and use it in GitHub Desktop.
range extraction
from itertools import groupby
def solution(args):
# [-3,-2,-1,2,10,15,16,18,19,20] -> [[-3, -2, -1], [2], [10], [15, 16], [18, 19, 20]]
grps = ([v[1] for v in g] for _,g in groupby(enumerate(args), lambda p: p[1]-p[0]))
#[[-3, -2, -1], [2], [10], [15, 16], [18, 19, 20]] -> -3--1,2,10,15,16,18-20
return ','.join('{}{}{}'.format(g[0],'-'if len(g)>2 else',',g[-1])
if len(g)>1 else str(g[0]) for g in grps)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment