How to create sublists with numeric elements that are in a sequence?

0

Friends, imagine a list:

lista = [1, 2, 2, 3, 3, 3, 6, 6, 7, 11, 12, 12, 13, 14, 14]

Would you like to create sublists with only the elements that are in sequence? For example, in this case it would be:

lista = [[1, 2, 2, 3, 3, 3], [6, 6, 7], [11, 12, 12, 13, 14, 14]]

Since the number of sublists can vary, depending on the number of elements in the list.

I await and thank you.

    
asked by anonymous 10.02.2017 / 18:10

2 answers

3

Initially the question did not specify the desired language, and so it had done only in Javascript. Now that the author has specified that they want Python, I have implementations in Python, Javascript and Java.

Python

def dividir(array):
    resultado = []
    nada = {}
    parte = []
    ultima = nada
    for elemento in array:
        if len(parte) > 0 and (ultima == nada or (elemento != ultima and elemento != ultima + 1)):
           resultado.append(parte)
           parte = []
        parte.append(elemento)
        ultima = elemento
    if len(parte) > 0:
        resultado.append(parte)
    return resultado

# Teste
array = [1, 2, 2, 3, 3, 3, 6, 6, 7, 11, 12, 12, 13, 14, 14]
lista = dividir(array)
print(lista);

See here working on ideone.

Javascript

function dividir(array) {
    var resultado = [];
    var nada = {};
    var parte = [];
    var ultima = nada;
    for (var idx in array) {
        var elemento = array[idx];
        if (parte.length > 0 && (ultima === nada || (elemento !== ultima && elemento !== ultima + 1))) {
           resultado.push(parte);
           parte = [];
        }
        parte.push(elemento);
        ultima = elemento;
    }
    if (parte.length > 0) resultado.push(parte);
    return resultado;
}

// Teste
var array = [1, 2, 2, 3, 3, 3, 6, 6, 7, 11, 12, 12, 13, 14, 14];
var lista = dividir(array);
console.log(lista);

Click the blue "Run" button above to test.

Java

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {

    private static List<List<Integer>> dividir(int... array) {
        List<Integer> lista = IntStream.of(array).boxed().collect(Collectors.toList());
        return dividir(lista);
    }

    private static List<List<Integer>> dividir(List<Integer> lista) {
        List<List<Integer>> resultado = new ArrayList<>();
        List<Integer> parte = new ArrayList<>();
        Integer ultima = null;
        for (Integer i : lista) {
            int elemento = i;
            if (!parte.isEmpty() && (ultima == null || (elemento != ultima && elemento != ultima + 1))) {
                resultado.add(parte);
                parte = new ArrayList<>();
            }
            parte.add(elemento);
            ultima = elemento;
        }
        if (!parte.isEmpty()) resultado.add(parte);
        return resultado;
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 2, 3, 3, 3, 6, 6, 7, 11, 12, 12, 13, 14, 14};
        List<List<Integer>> lista = dividir(array);
        System.out.println(lista);
    }
}

See here working on ideone.

    
10.02.2017 / 19:31
2

If you can use the NumPy library (which I strongly advise), a very simple way of get this is with the following code:

# Sua lista original
lista = [1, 2, 2, 3, 3, 3, 6, 6, 7, 11, 12, 12, 13, 14, 14]

# Importa a biblioteca NumPy
import numpy as np

# Separa em grupos usando como índices da separação os locais onde ocorre uma
# diferença entre o item atual e o próximo maior do que 1
grupos = np.split(lista, [i+1 for i,j in enumerate(np.diff(lista)) if j > 1])

# Imprime os grupos produzidos
for i, g in enumerate(grupos):
    print('Grupo #{}: {}'.format(i, g.tolist()))

It produces the following output:

Grupo #0: [1, 2, 2, 3, 3, 3]
Grupo #1: [6, 6, 7]
Grupo #2: [11, 12, 12, 13, 14, 14]

The essential part of the code is the line with the call of np.split . It receives as a parameter the list to be divided and another list with the indexes where the division should occur. These indexes are located using another NumPy function that is np.diff , which automatically calculates the differences between one item in the list and the next. Basically you only need this line (besides importing).

See working at Ideone .

    
10.02.2017 / 22:22