Open In App

Python – Make a list of intervals with sequential numbers

Last Updated : 20 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Using itertools.groupby()

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.

Using range()

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.


Practice Tags :

Similar Reads