I can't make this code work. I've tried what I've seen browsing the net. Most indications suggest to use __cmp__
but it doesn't work. Also, I've tried using __lt__
with the same unsuccessful results.
Can anyone keep an eye on my code and tell me how to get it to work correctly?
I've created a Vertex class (Vertice) with it's initializer, __lt__
, __gt__
and __cmp__
methods. Also, a main program that creates a list of Vertex
and tries to order them (unsuccessfully).
class Vertice:
def __init__(self, coordenada_x, coordenada_y):
self.coordenada_x = coordenada_x
self.coordenada_y = coordenada_y
def __str__(self):
return "Vértice ({},{})".format(self.coordenada_x, self.coordenada_y)
def __add__(self, otro_vertice):
vertice_resultado = Vertice(self.coordenada_x + otro_vertice.coordenada_x, self.coordenada_y + otro_vertice.coordenada_y)
return vertice_resultado
def __lt__(self, otro_vertice):
if self.coordenada_x > otro_vertice.coordenada_x:
return -1
elif self.coordenada_x < otro_vertice.coordenada_x:
return +1
else:
if self.coordenada_y > otro_vertice.coordenada_y:
return -1
elif self.coordenada_y < otro_vertice.coordenada_y:
return +1
else:
return 0
def __gt__(self, otro_vertice):
if self.coordenada_x > otro_vertice.coordenada_x:
return +1
elif self.coordenada_x < otro_vertice.coordenada_x:
return -1
else:
if self.coordenada_y > otro_vertice.coordenada_y:
return +1
elif self.coordenada_y < otro_vertice.coordenada_y:
return -1
else:
return 0
def __cmp__(self, otro_vertice):
if self.coordenada_x > otro_vertice.coordenada_x:
return +1
elif self.coordenada_x < otro_vertice.coordenada_x:
return -1
else:
if self.coordenada_y > otro_vertice.coordenada_y:
return +1
elif self.coordenada_y < otro_vertice.coordenada_y:
return -1
else:
return 0
from Vertice import Vertice
import random
def main():
lista = []
for i in range(0,10):
a = random.randint(1,99)
b = random.randint(1,99)
lista.append(Vertice(a,b))
for elemento in lista:
print(elemento)
print()
lista.sort()
for elemento in lista:
print(elemento)
print()
main()
I expect the output of a list of Vertex firstly ordered by it's "x" coordinate and secondly by it's "y" coordinate. At this moment the list is reordered chaotically.