我有一个排序算法问题,它包括对子类Priority Person的对象进行排序(该对象将被放置在一个列表中,目标是更改子类Priority Person的lt方法以对列表上的.sort()方法产生影响),如果优先权人的对象存在由参数True描述的缺陷,则应将其视为小于获得参数False的优先权人对象(这意味着此人没有任何缺陷),如果两者都有缺陷,或者两者都没有缺陷,则应考虑所涉及的优先权人的名字的词典顺序。优先权人子类别的主要类别是我上面所示的类别人:
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
任何帮助都将不胜感激。 多谢各位
我希望这能奏效
输出:
您基本上希望按照优先级和名称进行排序。因此,您必须首先比较不同优先级,并且只有相同优先级的名称:
相关问题 更多 >
编程相关推荐