Distance count between one element and each other in a list (Python)

1

I have a list that symbolizes a timeline:

linha_tempo = [1107, 1107, 0, 1104, 1104, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1106, 1106, 0, 0, 0, 0, 0, 1102, 1102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1105, 1105, 1101, 1101, 0, 0, 1103, 1103, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

What I need from here is to store distances where each first occurrence of an element other than 0 is from the next element other than 0.

Ex: 1107 is at a distance of 3 from 1104, to 1106 is at 36 ... and so on, I have to do this for all elements.

    
asked by anonymous 26.06.2016 / 16:22

1 answer

1

The best way to store your data is by using a dictionary. You can do this:

distancias = {}
lenLT = len(linha_tempo)
for i in range(0, lenLT):
    if(linha_tempo[i] != 0 and linha_tempo[i] != linha_tempo[i+1]): # caso encontremos um elemento diferente de 0 e o elemento a seguir seja diferente (nao vale a pensa fazer isto duas vezes seguidas, que e o numero de ocorrencias de elementos dif de 0
        distancias[linha_tempo[i]] = {} # criamos uma chave do dicionario com elemento diferente de 0 encontrado
        distancia = 0 # resetamos a distancia
        for j in range(i, lenLT): # comecamos a contar a partir do index onde foi descoberto o elemento ate ao fim
            distancia += 1 # incrementamos 1 a distancia
            if(linha_tempo[j] == 0 or linha_tempo[j] == linha_tempo[i]): # nao vale continuar na iteracao se o elemento for 0 ou se for a segunda ocorrencia do elemento encontrado
                continue
            if(linha_tempo[j] not in distancias[linha_tempo[i]]):
                distancias[linha_tempo[i]][linha_tempo[j]] = distancia #armazenamos a chave (elemento deferente de 0, linha_tempo[j]) com a respetiva distancia (de linha_tempo[i] ate linha_tempo[j])

Result:

print(distancias) # {1104: {1105: 58, 1106: 33, 1101: 60, 1102: 40, 1103: 64}, 1105: {1101: 2, 1103: 6}, 1106: {1105: 25, 1101: 27, 1102: 7, 1103: 31}, 1107: {1104: 3, 1105: 61, 1106: 36, 1101: 63, 1102: 43, 1103: 67}, 1101: {1103: 4}, 1102: {1105: 18, 1101: 20, 1103: 24}, 1103: {}}

I try to explain the logic in the comments I hope you realize, but say that I try to improve

    
26.06.2016 / 16:36