【发布时间】:2016-06-14 05:30:24
【问题描述】:
情况:我正试图很好地处理双链接结构。到目前为止,我已经很好地掌握了这些方法。我希望能够为此类创建两个对象并检查其中的每个项目是否相等。我没有任何语法错误,而且我得到的错误有点令人困惑。这就是我目前所拥有的。
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]”我不确定为什么我的代码将其识别为相等,而我希望它实际检查节点中的特定值。
【问题讨论】:
标签: python linked-list