- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find groups of strictly increasing numbers in a list in Python
Sometimes we may need to evaluate if the elements in a list are strictly incremental. Which means the numbers are increasing with a gap of 1. In this article we will see how to find out the groups of strictly increasing numbers in a given list.
Direct comparison
In this approach we gradually increase the index of each number and compare it with previous number in the list. As long as the second number is 1 greater than the first, we append the numbers to a inner list. Else the number becomes part of the outer list.
Example
listA = [11, 12, 6, 7, 8, 12, 13,14] res = [[listA[0]]] for i in range(1, len(listA)): if listA[i - 1] + 1 == listA[i]: res[-1].append(listA[i]) else: res.append([listA[i]]) print(res)
Output
Running the above code gives us the following result −
[(11, 12), (6, 7, 8), (12, 13, 14)]
With itertools
In this approach we use the itertools and its functions to get the set of strictly incrementing numbers.
Example
from itertools import groupby, cycle def groupincreasing(l): inner_list = cycle(listA) next(inner_list) groups = groupby(l, key=lambda j: j + 1 == next(inner_list)) for k, v in groups: if k: yield tuple(v) + (next((next(groups)[1])),) listA = [11, 12, 6, 7, 8, 12, 13,14] print(list(groupincreasing(listA)))
Output
Running the above code gives us the following result −
[(11, 12), (6, 7, 8), (12, 13, 14)]
Advertisements