Python 在链表中计数
我只是想确保我的getCount函数能够工作,因为我不知道如何测试它以确保它能够工作。有人能告诉我如何测试这个函数或者我做错了什么吗?它应该计算某个对象在我的链接列表中出现的次数 这是ListNode导入Python 在链表中计数,python,python-2.7,Python,Python 2.7,我只是想确保我的getCount函数能够工作,因为我不知道如何测试它以确保它能够工作。有人能告诉我如何测试这个函数或者我做错了什么吗?它应该计算某个对象在我的链接列表中出现的次数 这是ListNode导入 class ListNode(object): def __init__(self, item = None, link = None): '''creates a ListNode with the specified data value and link
class ListNode(object):
def __init__(self, item = None, link = None):
'''creates a ListNode with the specified data value and link
post: creates a ListNode with the specified data value and link'''
self.item = item
self.link = link
希望我发布的代码足够让你们看到这个问题。我只是想找到一种方法来测试我的计数是否有效,如果无效,我需要知道如何使其有效。您的
LinkedList.getCount()
方法有几个问题:
- 如果
等于self.head
,则它会尝试计数position
,但self.head
是一个节点,是self.head
的一个实例。它永远不会等于您想要计算的值ListNode
- 它尝试递归地使用该方法,但没有全局
函数getCount()
节点进行比较。每次:
def getCount(self, value):
count = 0
current = self.head
while current is not None:
if current.item == value:
count += 1
current = current.link
return count
您在getCount
中调用的getCount
是什么?为什么ListNode在一个单独的文件中?为什么要基于self.head
(一个ListNode
实例)进行计数?您不应该根据每个节点的ListNode.item
值进行计数吗?@MartijnPieters那么,这些代码是什么样子的呢?很抱歉,我不知道我需要改变什么。所以如果我必须找到索引,我会通过位置吗?例如:def getIndex(self,position):
?或者我该怎么做?@CooperGay:你的意思是getIndex()
返回该索引处的值?然后使用相同的while
循环,但使用计数器计算到目前为止得到的索引;达到所需索引后,返回current.item
。
def getCount(self, value):
count = 0
current = self.head
while current is not None:
if current.item == value:
count += 1
current = current.link
return count