Python中文
首页
教程
问答
标签
搜索
登录
注册
如何编写equals方法
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>情境:我正试图很好地理解双链接结构。到目前为止,我对这些方法掌握得很好。我希望能够为这个类创建两个对象,并检查其中的每个项是否相等。我没有任何语法错误,我得到的错误是有点混乱。这是我到目前为止的情况。你知道吗</p> <pre><code>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 </code></pre> <p>测试:</p> <pre><code>from unittest import TestCase tc = TestCase() lst = LinkedList() lst2 = LinkedList() tc.assertEqual(lst, lst2) lst2.append(100) tc.assertNotEqual(lst, lst2) </code></pre> <p>当我测试这段代码时,我得到了一个断言错误,它说“<code>[] == [100]</code>”,我不确定为什么我的代码会将其识别为相等,而我希望它实际检查节点中的特定值。你知道吗</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p><code>zip(self.other)</code>只提供两个列表中较短的元素。它将丢弃较长列表中多余的部分。因此,对于<code>[] == [100]</code>,<code>zip</code>不提供任何元素,您的代码不检查任何内容就返回True。你知道吗</p> <p>你可以在开始的时候做一个检查,看看列表是否有不同的长度。如果他们这样做了,他们就不可能平等。你知道吗</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何合并多个PDF文件?
10 回答
如何合并多个xarray数据变量及其坐标?
10 回答
如何合并多个列中具有重复值的行
4 回答
如何合并多个唯一id
7 回答
如何合并多个图纸并使用图纸名称的名称重命名列名?
5 回答
如何合并多个字典并添加同一个键的值?(Python)
5 回答
如何合并多个搜索结果文件(pkl)以将它们全部打印在一起?
1 回答
如何合并多个数据帧
2 回答
如何合并多个数据帧并使用Pandas为假人添加列?
5 回答
如何合并多个数据帧并按时间戳排序
10 回答
如何合并多个数据帧的列表并用另一个lis标记每列
5 回答
如何合并多个数据框中的列
5 回答
如何合并多个文件?
3 回答
如何合并多个查询集?
4 回答
如何合并多个绘图?
4 回答
如何合并多个词典
5 回答
如何合并多个输入数据集(数据帧)?
1 回答
如何合并多条记录中拆分的文本行
9 回答
如何合并多索引列datafram
6 回答
如何合并多级(即多索引)数据帧?
8 回答