Skip to content

Instantly share code, notes, and snippets.

@uchida
Last active July 14, 2016 15:08
Show Gist options
  • Select an option

  • Save uchida/7746780 to your computer and use it in GitHub Desktop.

Select an option

Save uchida/7746780 to your computer and use it in GitHub Desktop.
1 3 4 5 7 => 1,3-5,7
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from itertools import chain, izip_longest, groupby
def hyphenate(s):
"""
>>> hyphenate("1 2 3")
'1-3'
>>> hyphenate("1 2 3 5 7 8")
'1-3,5,7-8'
>>> hyphenate("1 3 4 5 7")
'1,3-5,7'
"""
arr = [int(c) for c in s.split()]
is_stepwise = [x - y == -1 for x, y in zip(arr, arr[1:])]
seq = chain.from_iterable(izip_longest(arr, is_stepwise, fillvalue=False))
groups = (list(g) for k, g in groupby(seq, bool) if k)
return ",".join(["{}-{}".format(x[0], x[-1]) if len(x) > 1
else "{}".format(x[0]) for x in groups])
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True, report=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment