题目:
基于元素相等操作“==”定义一个单链表的相等比较函数。另请基于字典序的概念,为链表定义大于,小于,大于等于,小于等于的判断
1 class LList: 2 3 """ 4 省略已实现部分 5 """ 6 7 #根据索引获得该位置的元素 8 def __getitem__(self, key): 9 if not isinstance(key, int): 10 raise TypeError 11 if 0<=key<len(self): 12 p = self._head 13 num = -1 14 while p: 15 num += 1 16 if key == num: 17 return p.elem 18 else: 19 p = p.next 20 else: 21 raise IndexError 22 23 #判断两个列表是否相等 == 24 def __eq__(self, other): 25 #两个都为空列表 则相等 26 if len(self)==0 and len(other)==0: 27 return True 28 #两个列表元素个数相等 当每个元素都相等的情况下 两个列表相等 29 elif len(self) == len(other): 30 for i in range(len(self)): 31 if self[i] == other[i]: 32 pass 33 else: 34 return False 35 #全部遍历完后则两个列表相等 36 return True 37 #两个列表元素个数不相等 返回Fasle 38 else: 39 return False 40 #判断两个列表是否不相等 != 41 def __ne__(self, other): 42 if self.__eq__(other): 43 return False 44 else: 45 return True 46 # > 47 def __gt__(self, other): 48 l1 = len(self) 49 l2 = len(other) 50 if not isinstance(other, LList): 51 raise TypeError 52 # 1.len(self) = len(other) 53 if l1 == l2: 54 for i in range(l1): 55 if self[i] == other[i]: 56 continue 57 elif self[i] < other[i]: 58 return False 59 else: 60 return True 61 #遍历完都相等的话说明两个列表相等 所以返回False 62 return False 63 # 2.len(self) > len(other) 64 if l1 > l2: 65 for i in range(l2): 66 if self[i] == other[i]: 67 continue 68 elif self[i] < other[i]: 69 return False 70 else: 71 return True 72 #遍历完后前面的元素全部相等 则列表个数多的一方大 73 #if self[l2-1] == other[l2-1]: 74 return True 75 # 3.len(self) < len(other) 76 if l1 < l2: 77 for i in range(l1): 78 if self[i] == other[i]: 79 continue 80 elif self[i] < other[i]: 81 return False 82 else: 83 return True 84 #遍历完后前面的元素全部相等 则列表个数多的一方大 85 #if self[l2-1] == other[l2-1]: 86 return False 87 # < 88 def __lt__(self, other): 89 #列表相等情况下>会返回False,则<这里判断会返回True,有错误.所以要考虑在==的情况下也为False 90 if self.__gt__(other) or self.__eq__(other): 91 return False 92 else: 93 return True 94 # >= 95 def __ge__(self, other): 96 """ 97 if self.__eq__(other) or self.__gt__(other): 98 return True 99 else: 100 return False 101 """ 102 #大于等于和小于是完全相反的,所以可以依靠小于实现 103 if self.__lt__(other): 104 return False 105 else: 106 return True 107 # <= 108 def __le__(self, other): 109 """ 110 if self.__eq__(other) or self.__lt__(other): 111 return True 112 else: 113 return False 114 """ 115 ##小于等于和大于是完全相反的,所以可以依靠大于实现 116 if self.__gt__(other): 117 return False 118 else: 119 return True