Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find groups of strictly increasing numbers in a list in Python
Finding groups of strictly increasing numbers means identifying sequences where each number is exactly 1 greater than the previous number. This is useful for pattern recognition and data analysis tasks in Python.
Using Direct Comparison
This approach compares each element with the previous one to check if they form a consecutive sequence ?
numbers = [11, 12, 6, 7, 8, 12, 13, 14]
groups = [[numbers[0]]]
for i in range(1, len(numbers)):
if numbers[i - 1] + 1 == numbers[i]:
groups[-1].append(numbers[i])
else:
groups.append([numbers[i]])
print(groups)
[[11, 12], [6, 7, 8], [12, 13, 14]]
Using itertools.groupby
A more elegant approach using itertools to group consecutive sequences based on the difference pattern ?
from itertools import groupby
def find_increasing_groups(numbers):
groups = []
for k, group in groupby(enumerate(numbers), lambda x: x[1] - x[0]):
sequence = [x[1] for x in group]
if len(sequence) > 1:
groups.append(sequence)
else:
groups.append(sequence)
return groups
numbers = [11, 12, 6, 7, 8, 12, 13, 14]
result = find_increasing_groups(numbers)
print(result)
[[11, 12], [6, 7, 8], [12, 13, 14]]
How the itertools Approach Works
The groupby function groups elements based on a key. We use enumerate to get index-value pairs, then subtract the index from the value. Consecutive numbers will have the same difference ?
numbers = [11, 12, 6, 7, 8]
enumerated = list(enumerate(numbers))
print("Enumerated:", enumerated)
differences = [value - index for index, value in enumerated]
print("Differences:", differences)
Enumerated: [(0, 11), (1, 12), (2, 6), (3, 7), (4, 8)] Differences: [11, 11, 4, 4, 4]
Comparison
| Method | Complexity | Readability | Best For |
|---|---|---|---|
| Direct Comparison | O(n) | High | Simple cases, learning |
| itertools.groupby | O(n) | Medium | Functional programming style |
Conclusion
Use direct comparison for simple, readable code when learning the concept. Use itertools.groupby for more sophisticated data processing pipelines where functional programming style is preferred.
