The aim is to find groups of increasing/monotonic numbers given a list of integers. Each item in the resulting group must be of a +1 increment from the previous item
A (really) simple implementation:
x = [7, 8, 9, 10, 6, 0, 1, 2, 3, 4, 5]
result = []
current = x[0]
temp = []
for i in xrange(1, len(x)):
if (x[i] - current == 1):
temp.append( x[i] )
else:
if (len(temp) > 1):
result.append(temp)
temp = [ x[i] ]
current = x[i]
result.append(temp)
And you will get [ [7, 8, 9, 10], [0, 1, 2, 3, 4, 5] ]
. From there, you can get the number of increasing numbers by [ len(x) for x in result ]
and the total number of numbers sum( len(x) for x in result)
.
I think the most maintainable solution would be to make it simple:
def group_by(l):
res = [[l[0]]]
for i in range(1, len(l)):
if l[i-1] < l[i]:
res[-1].append(l[i])
else:
res.append([l[i]])
return res
This solution does not filter out single element sequences, but it can be easily implemented. Additionally, this has O(n) complexity. And you can make it an generator as well if you want.
By maintainable I mean code that is not an one-liner of 300 characters, with some convoluted expressions. Then maybe you would want to use Perl :). At least you will how the function behaves one year later.
>>> x = [7, 8, 9, 10, 6, 0, 1, 2, 3, 4, 5]
>>> print(group_by(x))
[[7, 8, 9, 10], [6], [0, 1, 2, 3, 4, 5]]