Skip to content

Instantly share code, notes, and snippets.

@limansky
Created December 22, 2011 15:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save limansky/1510723 to your computer and use it in GitHub Desktop.
Save limansky/1510723 to your computer and use it in GitHub Desktop.
Problem of grouping list values.
-- ghci example
-- *Main> group [1,2,3,4,7,8,13]
-- [(1,4),(7,8),(13,13)]
group = foldr f []
where f x [] = [(x,x)]
f x as@((a,b):as') = if a == x+1 then (x,b):as'
else (x,x):as
-- *Main> ungroup [(1,4),(7,8),(13,13)]
-- [1,2,3,4,7,8,13]
ungroup [] = []
ungroup xs = concat $ map f xs
where f (a,b) = if a == b then [a] else a:f (a+1,b)
@kovrov
Copy link

kovrov commented Dec 22, 2011

def group(a, i=None):
    if i is None:
        return reduce(group, a[1:], [(a[0],a[0])])
    x,y = a.pop()
    return a + ([(x,i)] if i - y == 1 else [(x,y), (i,i)])

assert group([1,2,3,4,7,8,13]) == [(1, 4), (7, 8), (13, 13)]

@kovrov
Copy link

kovrov commented Dec 25, 2011

Python version using a 'generator' function:

def group(numbers):
    it = iter(numbers)
    x = y = next(it)
    for i in it:
        if i - y > 1:
            yield x, y
            x = i
        y = i
    yield x, y

assert list(group([1,2,3,4,7,8,13])) == [(1,4), (7,8), (13,13)]
assert list(group([])) == []

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment