gpt4 book ai didi

python - equals方法怎么写

转载 作者:行者123 更新时间:2023-12-01 03:54:05 27 4
gpt4 key购买 nike

情况:我正在尝试很好地处理双向链接结构。到目前为止,我已经掌握了这些方法。我希望能够为此类创建两个对象,并检查其中的每个项目是否相等。我没有任何语法错误,而且我得到的错误有点令人困惑。这就是我到目前为止所拥有的。

class LinkedList:
class Node:
def __init__(self, val, prior=None, next=None):
self.val = val
self.prior = prior
self.next = next

def __init__(self):
self.head = LinkedList.Node(None) # sentinel node (never to be removed)
self.head.prior = self.head.next = self.head # set up "circular" topology
self.length = 0

def append(self, value):
n = LinkedList.Node(value, prior=self.head.prior, next=self.head)
n.prior.next = n.next.prior = n
self.length += 1

def _normalize_idx(self, idx):
nidx = idx
if nidx < 0:
nidx += len(self)
if nidx < -1:
raise IndexError
return nidx

def __getitem__(self, idx):
"""Implements `x = self[idx]`"""
nidx = self._normalize_idx(idx)
currNode = self.head.next
for i in range(nidx):
currNode = currNode.next
if nidx >= len(self):
raise IndexError
return currNode.val


def __setitem__(self, idx, value):
"""Implements `self[idx] = x`"""
nidx = self._normalize_idx(idx)
currNode = self.head.next
if nidx >= len(self):
raise IndexError
for i in range(nidx):
currNode = currNode.next
currNode.val = value

def __iter__(self):
"""Supports iteration (via `iter(self)`)"""
cursor = self.head.next
while cursor is not self.head:
yield cursor.val
cursor = cursor.next

def __len__(self):
"""Implements `len(self)`"""
return self.length

def __eq__(self, other):
currNode = self.head.next
currNode2 = other.head.next
for currNode, currNode2 in zip(self, other):
if currNode.val != currNode2.val:
return False
return True

测试:

from unittest import TestCase
tc = TestCase()
lst = LinkedList()
lst2 = LinkedList()

tc.assertEqual(lst, lst2)

lst2.append(100)
tc.assertNotEqual(lst, lst2)

当我测试这段代码时,我得到一个断言错误,说“[] == [100] ”我不确定为什么我的代码将其识别为相等,而我实际上希望它这样做检查节点中的特定值。

最佳答案

zip 只到达最短的列表。您需要 itertools.zip_longest,但不需要 .val(您的迭代器已返回实际值)。试试这个:

def __eq__(self, other):
for val1, val2 in zip_longest(self, other):
if val1 != val2:
return False
return True

或者也许更好?

def __eq__(self, other):
return all(val1 == val2 for val1, val2 in zip_longest(self, other))

编辑

我喜欢@BrenBarn 首先检查长度的建议。这是一个更有效的答案:

def __eq__(self, other):
return len(self) == len(other) and all(
val1 == val2 for val1, val2 in zip(self, other))

关于python - equals方法怎么写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37803637/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com