I have the following method that goes through a certain input file with an amount of data that increases exponentially and returns a list with the coordinates of a city.
The code block that represents the above is the following:
def recorrido(puntos):
for i in range(0, len(puntos)):
for j in range(i + 1, len(puntos)):
objeto.add_recorrido(i, j, peso = distancia(puntos[i], puntos[j]))
return objeto
The problem with this block is that going through for
a list with a very large amount of data will take twice as long to go through it as doing it with a set()
whose efficiency is much higher. So I'm looking for a way to pass the above method, specifically the loops, for
to a set()
.
On the other hand, the next block of code to be optimized is composed of an empty list in which the first element of a tuple that is contained in a list is stored and the repeated elements, if they have already been entered in the empty list, are not included again.
C = [(0, 4), (4, 0), (0, 1), (1, 2), (2, 3), (3, 2), (2, 1), (1, 0)]
solution = []
for i, j in C:
if i not in solution:
solution.append(i)
return solution
Therefore, I want to take this block composed by for
to another much more efficient functionality, so that, in this way, I avoid manual iteration of the for
. I tried to implement it by means of a set()
of the form:
miListaSinRepeticion = list(set(listaoriginal))
sorted(miListaSinRepeticion)