Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在链表中计数_Python_Python 2.7 - Fatal编程技术网

Python 在链表中计数

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

我只是想确保我的getCount函数能够工作,因为我不知道如何测试它以确保它能够工作。有人能告诉我如何测试这个函数或者我做错了什么吗?它应该计算某个对象在我的链接列表中出现的次数

这是ListNode导入

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