Как мне изменить магический метод __lt__, чтобы этот алгоритм работал? - Python - PullRequest
1 голос
/ 09 мая 2020

Python Проблема сортировки

У меня проблема алгоритма сортировки, которая заключается в сортировке объектов подкласса Priority Person (эти объекты будут помещены в список, и цель состоит в том, чтобы изменить метод lt объекта подкласс приоритет person, чтобы иметь влияние на метод .sort () в списках), если объект Priority Person имеет недостаток, который описывается параметром True, его следует рассматривать МЕНЬШЕ, чем объект приоритетного человека, который получил параметр False ( что означает, что у этого человека нет какого-либо недостатка), в случае, если у обоих есть недостаток, или у обоих нет недостатка, следует учитывать лексикографический порядок имен приоритетных вовлеченных лиц. Как показано выше, основным классом подкласса Priority Person является класс Person:

class Person(object):

    def __init__(self, name):
        """Create a person"""
        self.name = name
        try:
            lastBlank = name.rindex(' ')
            self.lastName = name[lastBlank + 1:]
        except:
            self.lastName = name
        self.birthday = None

    def __lt__(self, other):
        """Returns True if self's name is lexicographically
           less than other's name, and False otherwise"""
        return self.name < other.name

    def __str__(self):
        """Returns self's name"""
        return self.name

class PriorityPerson(Person): # the __lt__ part of this class does not work and I don't know why?

   def __init__(self,name,deficiencia):
        super().__init__(name)
        self.deficiente = deficiencia
    
    
    def __lt__(self, other):
        if self.deficiente and other.deficiente and self.name< other.name:
            return self.name < other.name
        elif self.deficiente and other.deficiente and other.name < self.name:
            return other.name< self.name
        elif self.deficiente and not other.deficiente and self.name < other.name:
            return self.name < other.name
        elif self.deficiente and not other.deficiente and other.name < self.name:
            return self.name< other.name
        elif not self.deficiente and other.deficiente and self.name < other.name:
            return other.name < self.name
        elif not self.deficiente and other.deficiente and other.name < self.name:
            return other.name < self.name
        elif not self.deficiente and not other.deficiente and self.name < other.name:
            return  self.name < other.name
        elif not self.deficiente and not other.deficiente and other.name < self.name:
            return other.name < self.name

Пример реализации:

p1 = PriorityPerson("John Smith", False)
p2 = PriorityPerson("Sam Mendes", False)
p3 = PriorityPerson("Grandmother Anne", True)
p4 = PriorityPerson("Stephen Hawking", True)
p5 = PriorityPerson("Betty Large", True)

listaPessoas = [p1,p2,p3,p4, p5]
listaPessoas.sort()
for p in listaPessoas:
   print(p)

Правильный вывод:

Betty Large
Grandmother Anne
Stephen Hawking
John Smith
Sam Mendes

Мой неправильный вывод:

Betty Large
Stephen Hawking
Grandmother Anne
Sam Mendes
John Smith

Любая помощь будет чрезвычайно признательна. Спасибо.

Ответы [ 2 ]

1 голос
/ 09 мая 2020

Надеюсь, это сработает

class Person(object):
    def __init__(self, name):
        """Create a person"""
        self.name = name
        try:
            lastBlank = name.rindex(' ')
            self.lastName = name[lastBlank + 1:]
        except:
            self.lastName = name
        self.birthday = None

    def __lt__(self, other):
        """Returns True if self's name is lexicographically
        less than other's name, and False otherwise"""
        return self.name < other.name

    def __str__(self):
        """Returns self's name"""
        return self.name


class PriorityPerson(Person):
    def __init__(self, name, deficiencia):
        super().__init__(name)
        self.deficiente = deficiencia

    def __lt__(self, other):
        if self.deficiente and not other.deficiente:
            # If self is VIP and other is not, just return True
            return True
        elif not self.deficiente and other.deficiente:
            # If other is VIP and self is not, just return False
            return False

        # On equal priority, normal compare
        return super().__lt__(other)

p1 = PriorityPerson("John Smith", False)
p2 = PriorityPerson("Sam Mendes", False)
p3 = PriorityPerson("Grandmother Anne", True)
p4 = PriorityPerson("Stephen Hawking", True)
p5 = PriorityPerson("Betty Large", True)

listaPessoas = [p1,p2,p3,p4, p5]
listaPessoas.sort()
for p in listaPessoas:
   print(p)

Результат:

Betty Large
Grandmother Anne
Stephen Hawking
John Smith
Sam Mendes
0 голосов
/ 09 мая 2020

Вы в основном хотите сортировать по приоритету и по имени второму. Итак, вам нужно сначала сравнить разные приоритеты и только с одинаковым приоритетом для имени:

def __lt__(self, other):
    if self.deficiente != other.deficiente: # yes, you can compare bools!
        return self.deficiente
    else:
        return self.name < other.name
...