From 3bcc5b9f508c262a19c12ce0981c69f1a9897f2f Mon Sep 17 00:00:00 2001
From: linarphy <linarphy@linarphy.net>
Date: Tue, 9 May 2023 12:16:21 +0200
Subject: [PATCH] Add functions

- Add consecutive
- Add last_consecutive
---
 utils.py | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)

diff --git a/utils.py b/utils.py
index 4ae2249..7b053d4 100644
--- a/utils.py
+++ b/utils.py
@@ -173,3 +173,32 @@ def find_point( list_ , index , axis = 'x' , threshold = 0.5 ):
                     inside = False
             i += 1
     return points
+def consecutive( list_ ):
+    """
+    divide a sorted list of integer by consecutive part
+    """
+    if not isinstance( list_ , list ) and not isinstance( list_ , np.ndarray ):
+        raise ValueError( 'list_ must be a list, ' + type( list_ ) + ' given' )
+    index = last_consecutive( list_ )
+    if index == len( list_ ) - 1:
+        return [ list_ ]
+    return consecutive( list_[ : i + 1 ] ) + consecutive( list_[ i + 1 : ] ) # happy recursion \o/
+def last_consecutive( list_ ):
+    """
+    return the last index of the first consecutive list
+    """
+    if not isinstance( list_ , list ) and not isinstance( list_ , np.ndarray ):
+        raise ValueError( 'list_ must be a list, ' + type( list_ ) + ' given' )
+    first , lower , greater = list_[0] , 0 , len( list_ )
+    while greater - lower != 1:
+        i = lower + ( greater - lower ) // 2
+        if list_[ i ] - first != i: # outside of the consecutive list
+            greater = i
+        else:
+            if i != len( list_ ) - 1:
+                if list_[ i ] + 1 != list_[ i + 1 ]: # next one is not inside the consecutive list => limit retrieved
+                    break
+                lower = i
+            else: # if inside the consecutive list and last element, every element is consecutive
+                break
+    return i