Python – Ways to print longest consecutive list without considering duplicates element
Given, a list of Numbers, the task is to print the longest consecutive (Strictly) list, without considering duplicate elements. If there is more than one answer, print anyone. These type of problem are quite common while working on some web development projects in Django or flask.
Below are some ways to solve the above task.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Note : If there are multiple answers, print anyone
Input:
[1, 2, 3, 5, 6, 6, 7, 9, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]
Output:
[13, 14, 15, 16]
Explanation :
Original list = [1, 2, 3, 5, 6, 6, 7, 9, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]
Calculated list = [13, 14, 15, 16, 16, ]
Unique elements = [13, 14, 15, 16, ]
Method 1: Using Iteration
The basic method that comes to mind while performing this operation is the naive method of printing longest consecutive list.
Python3
# Python code to print longest consecutive list.# Input list initializationInput = [12, 13, 14, 17, 18, 23, 24, 25, 25, 26, 27]# Output list initializationOutput = []temp = []last = -1# Iterationfor elem in Input: if elem - last == 1: temp.append(last) else: temp.append(last) Output.append(temp) temp = [] last = elemans = []most = 0for elem in Output: if len(elem)> most: most = len(elem) ans = elem # Printing outputprint("Initial List is")print(Input)print("Longest Consecutive list is :")print(ans) |
Output:
Initial List is [12, 13, 14, 17, 18, 23, 24, 25, 25, 26, 27] Longest Consecutive list is : [23, 24, 25]
Method 2: Using groupby and zip
Using Groupby and zip is the most elegant way to print the longest consecutive list.
Python3
# Python code to print longest consecutive list.# Importingfrom itertools import groupby# List InitializationInput = [1, 2, 3, 5, 6, 6, 7, 9, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]# Using zipz = zip(Input, Input[1:])# Using groupbylis = [list(y) for i, y in groupby(z, key = lambda x: (x[1] - x[0]) == 1)]# Taking max according to keylengthout = max(lis, key = len)# Output list Initializationoutput = []for elem in out: output.append(elem[0]) output.append(elem[1])# Converting to setoutput = list(set(output))# Sorting outputoutput.sort()# Printing answerprint("Initial list is ")print(Input)print("Longest Consecutive list is:")print(output) |
Output:
Initial list is [1, 2, 3, 5, 6, 6, 7, 9, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21] Longest Consecutive list is: [13, 14, 15, 16]


