Created
December 22, 2011 15:40
-
-
Save limansky/1510723 to your computer and use it in GitHub Desktop.
Problem of grouping list values.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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
commented
Dec 22, 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