Change language

Python | Find groups of strictly increasing numbers in a list

| | |

Examples :

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

Approach # 1: Python is naive

It’s naive an approach that takes advantage of the extra space of the input list. It uses a for loop and at each iteration checks if the next item is incremented from the previous one by 1. If yes, add it to the current sublist, otherwise create another sublist.

# Python3 group finder
The number of strictly increasing numbers within

  

def groupSequence (lst):

res = [[lst [ 0 ]]]

 

for i in range ( 1 , len (lst)):

if lst [i - 1 ] + 1 = = lst [i]:

res [ - 1 ]. append (lst [i])

 

else :

res.append ([lst [i]])

return res

 
# Driver program

l = [ 8 , 9 , 10 , 7 , 8 , 1 , 2 , 3 ]

print (groupSequence (l ))

Exit:

 [ [8, 9, 10], [7, 8], [1, 2, 3]] 

Approach # 2: Alternative naive

This alternative to above a very naive approach. This method is pretty straightforward and straightforward. It creates a start list and a end list that contains the position of the starting and ending sequence of increasing integers. So, just revert the borders using for loops.

# Python3 group search program
The number of strictly increasing numbers within

 

def groupSequence (l):

start_bound = [i for i in range ( len (l) - 1 )

if (l = = 0 or l [i]! = l [i - 1 ] + 1 )

  and l [i + 1 ] = = l [i] + 1 ]

 

end_bound = [i for i in range ( 1 , len (l))

if l [i] = = l [i - 1 ] + 1 and

(i = = len (l) - 1 or l [i + 1 ]! = l [i] + 1 )]

 

return [l [start_bound [i]: end_bound [i]] + 1 ]

  for i in range ( len (start_bound))]

 
# Driver program

l = [ 8 , < / code> 9 , 10 , 7 , 8 , 1 , 2 , 3 ]

print ( list (groupSequence (l)))

Exit:

 [[8, 9, 10 ], [7, 8], [1, 2, 3]] 

Approach # 3. Using iterable and profitable
This approach uses a different list & # 39 ; res & # 39; and repeatable & # 39; it & # 39 ;. Variable & # 39; prev & # 39; is used to store a record of the previous integer, and start is used to get the starting position of the ascending sequence. Using a loop, in each iteration, we check if the initial element is a successor to prev or not. If yes, we add it to res, otherwise we just issue res + [prev] as a list item.

# Python3 program for finding groups
The number of strictly increasing numbers within

 

def groupSequence (x):

  it = iter (x )

prev, res = next (it), []

 

while prev is not None :

  start = next (it, None )

  

  if prev + 1 = = start:

res.append (prev)

elif res:

yield list  (res + [prev])

res = []

prev = start

 
# Driver program

l = [ 8 , 9 , 10 , 7 , 8 , 1 , 2 , 3 ]

print ( list (groupSequence (l)))

Exit:

 [[8, 9, 10], [7, 8], [1, 2, 3 ]] 

Approach # 4 Using itertools
Python’s itertools provides operations such as looping and group invocation that are used in this method. First, we form another list & # 39;  temp_list & # 39; using a loop. The loop generates an infinitely repeating series of values. Then we group temp_list accordingly with the groupby operation and finally get the desired result.

# Python3 program for finding groups
The number of strictly increasing numbers within

from itertools import groupby, cycle

  

def groupSequence (l):

temp_list = cycle (l)

 

next (temp_list)

  groups = groupby (l, key = lambda j: j + 1 = = next (temp_list))

for k, v in groups:

if k:

yield tuple (v) + ( next (( next (groups) [ 1 ]) ),)

 

 
# Driver program

l = [ 8 , 9 , 10 , 7 , 8 , 1 , 2 , 3 ]

print ( list (groupSequence (l)))

Exit:

 [(8, 9, 10), (7, 8), (1, 2, 3 )] 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically