Python | Make a list of intervals with sequential numbers - GeeksforGeeks

20 Nov, 2019
Given a list of sequential numbers, Write a Python program to convert the given list into list of intervals.
Examples:
Input : [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]
Output : [[2, 5], [7, 11], [15, 16]]

Input : [1, 2, 3, 6, 7, 8, 9, 10]
Output : [[1, 3], [6, 10]]

 Method #1 : Naive Approach
First, we use the brute force approach to Convert list of sequential number into intervals. Start a loop till the length of the list. In every iteration, use another loop to check the continuity of the sequence. As soon as the sequence stop, yield the lower and higher bound of each interval.
# Python3 program to Convert list of # sequential number into intervals  def interval_extract(list):    length = len(list)    i = 0    while (i< length):        low = list[i]        while i <length-1 and list[i]+1 == list[i + 1]:            i += 1        high = list[i]        if (high - low >= 1):            yield [low, high]        elif (high - low == 1):            yield [low, ]            yield [high, ]        else:            yield [low, ]        i += 1  # Driver codel =  [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]print( list(interval_extract(l)))
[[2, 5], [7, 9], [11], [15, 16]]

 Method #2 : Pythonic NaiveFirst, sort the given list. Initialize previous_number and range_start with first element. Start a loop and check if the next number is additive of the previous number, If yes, Initialize this number to previous number otherwise yield the new interval starting with range_start and ending with previous_number.
# Python3 program to Convert list of # sequential number into intervals  def interval_extract(list):    list = sorted(set(list))    range_start = previous_number = list[0]      for number in list[1:]:        if number == previous_number + 1:            previous_number = number        else:            yield [range_start, previous_number]            range_start = previous_number = number    yield [range_start, previous_number]  # Driver codel = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]print( list(interval_extract(l)))
[[2, 5], [7, 9], [11, 11], [15, 16]]

 Method #3 : Using itertoolsThe other pythonic method is to use Python itertools. We use itertools.groupby(). Where enumerate(iterable) is taken as iterable and lambda t: t[1] – t[0]) as key function to find the sequence for intervals.
# Python3 program to Convert list of # sequential number into intervalsimport itertools  def intervals_extract(iterable):          iterable = sorted(set(iterable))    for key, group in itertools.groupby(enumerate(iterable),    lambda t: t[1] - t[0]):        group = list(group)        yield [group[0][1], group[-1][1]]  # Driver codel = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]print( list(intervals_extract(l)))
[[2, 5], [7, 9], [11, 11], [15, 16]]

ManasChhabra2
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python