Python - Make a list of intervals with sequential numbers
Last Updated :
20 Dec, 2024
Creating a list of sequential numbers in Python allows us to generate a range of values within a defined interval. We can customize the sequence by adjusting the starting point, ending point, and step size. This article will explore various methods to list intervals with sequential numbers.
itertools.groupby()
groups consecutive numbers by detecting sequence changes. It efficiently groups data and avoids creating unnecessary intermediate lists.
Example:
Python
import itertools
def fun(a):
a = sorted(set(a))
b = []
for k, g in itertools.groupby(enumerate(a),
key=lambda t: t[1] - t[0]):
g = list(g)
b.append([g[0][1], g[-1][1]])
return b
l = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]
print(fun(l))
Output[[2, 5], [7, 9], [11, 11], [15, 16]]
Explanation :
- This function sorts the list, removes duplicates, and then groups consecutive numbers based on the difference between their indices and values.
- Each group is converted to an interval and added to the result list.
Let's discuss more method to make list of interval with sequential numbers.
Using Loop
Loop efficiently groups consecutive numbers into intervals by iterating through the list once. It detects gaps between numbers, closes the current interval, and starts a new one when needed.
Python
def fun(n):
if not n:
return []
b = []
start = n[0] # Start
for i in range(1, len(n)):
if n[i] != n[i - 1] + 1:
b.append([start, n[i - 1]])
start = n[i] # Update start for the new interval
b.append([start, n[-1]]) # Add the last interval
return b
a = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]
print(fun(a))
Output[[2, 5], [7, 9], [11, 11], [15, 16]]
Explanation:
- This function returns an empty list if the input is empty.
- Iterates through the list, detecting gaps and appending intervals to the result list.
- After the loop, it adds the last interval and returns the list of intervals.
range()
create intervals by comparing consecutive numbers. By iterating through the list and comparing numbers to the end of the current range, you can construct intervals.
Python
def fun(a):
if not a:
return []
b = []
start = a[0]
for i in range(1, len(a)): # Iterate
if a[i] != a[i - 1] + 1: # gap
b.append([start, a[i - 1]]) # Append
start = a[i] # Update
b.append([start, a[-1]]) # Finalize
return b
l = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]
print(fun(l))
Output[[2, 5], [7, 9], [11, 11], [15, 16]]
Explanation:
- This function groups consecutive numbers into intervals and detects gaps between them.
- It appends each interval to the result list and returns a list of intervals in the form [start, end].
Using Recursion
Recursion identifies intervals by checking if consecutive numbers follow each other. It recursively compares each number with the next, saving intervals when gaps are detected.
Example:
Python
def fun(a, start=0):
if start >= len(a):
return []
b = []
end = start
while end + 1 < len(a) and a[end + 1] == a[end] + 1: # find consecutive number
end += 1
b.append([a[start], a[end]]) # Add interval
b.extend(fun(a, end + 1)) # Recursion for the next part
return b
l= [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]
print(fun(l))
Output[[2, 5], [7, 9], [11, 11], [15, 16]]
Explanation:
- This function returns an empty list when the start index exceeds the list length.
- Identifies consecutive numbers and creates an interval.
Similar Reads
How to create a list of uniformly spaced numbers using a logarithmic scale with Python? In this article, we will create a list of uniformly spaced numbers using a logarithmic scale. It means on a log scale difference between two adjacent samples is the same. The goal can be achieved using two different functions from the Python Numpy library. Functions  Used:numpy.logspace: This functi
3 min read
Internal working of list in Python Introduction to Python lists :Â Python lists are internally represented as arrays. The idea used is similar to implementation of vectors in C++ or ArrayList in Java. The costly operations are inserting and deleting items near the beginning (as everything has to be moved). Insert at the end also becom
3 min read
Python - Get a sorted list of random integers with unique elements Given lower and upper limits, generate a sorted list of random numbers with unique elements, starting from start to end. Examples: Input: num = 10, start = 100, end = 200 Output: [102, 118, 124, 131, 140, 148, 161, 166, 176, 180] Input: num = 5, start = 1, end = 100 Output: [37, 49, 64, 84, 95] To g
2 min read
Iterate over a list in Python Python provides several ways to iterate over list. The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly.Example: Print all elements in the list one by one using for loop.Pythona = [1, 3, 5, 7, 9] # On each
3 min read
Python - Generate random numbers within a given range and store in a list Our task is to generate random numbers within a given range and store them in a list in Python. For example, you might want to generate 5 random numbers between 20 and 40 and store them in a list, which could look like this: [30, 34, 31, 36, 30]. Let's explore different methods to do this efficientl
3 min read