将节点特定的计数器添加到链表中

时间:2019-04-23 04:14:49

标签: python-3.x

进行了一些研究,但只能找到有键的示例-说“ 5”,并且它们会计算链接列表中“ 5”的出现次数。我想统计llist中每个字符串的每次出现次数。假设我有一个链接列表,其中包含“ a,a,a,b,d,f”。我希望输出说a-3 b-1 d -1 f -1。

我已经建立了列表,但是我想到的唯一方法是初始化一个计数变量,但是当一切完成后,我打印了整个列表,所以我不知道如何重置它。看起来像是:a-3 b -3 d -3 f -3。

代码如下:

class Linked_List:
def __init__(self):
    self.head = None
    self.count = 0

def print(self):
    p = self.head
    while p is not None:
        print(p.data, ' -', self.count)
        p = p.next

def insert(self, x):
    """"""
    p = self.head
    q = None
    done = False
    while not done:
        if self.head == x:
            done = True
        elif p == None:
            head = Linked_List_node(x)
            q.next = head
            done = True
        elif x == p.data:
            # head = Linked_List_node(x)

            # self.head = head
            self.count += 1
            done = True
        elif x < p.data:
            if self.head == p:
                head = Linked_List_node(x)
                head.next = p
                self.head = head
                done = True
            else:
                head = Linked_List_node(x)
                head.next = p
                q.next = head
                done = True
        q = p
        if p is not None:
            p = p.next
class Linked_List_node:
    def __init__(self, value):
        self.data = value
        self.next = None

修改后的代码:

    def print(self):
        p = self.head
        head = Linked_List_node(p.data)
        while p is not None:
            print(p.data, '-', self.count(p.data))
            p = p.next

    def count(self, x):
        # loop thru list for all x, if find x add 1 to count. Assign final count to that word.
        with open('cleaned_test.txt', 'r') as f:
            for line in f:
                for word in line.split():
                    if word == x:
                        self.count += 1

1 个答案:

答案 0 :(得分:0)

由于您希望自己的count函数能够计算每个单词的出现频率,因此我将在类print中创建一个类似于count的函数Linked_List,在列表中进行迭代,并更新频率字典。

def count(self):

    dct = {}
    p = self.head
    while p is not None:
        if p.data in dct:
            dct[p.data] += 1
        else:
            dct[p.data] = 1
        p = p.next
    return dct

输出将如下所示。

head = Linked_List_node('a')
ll = Linked_List()
ll.head = head
for item in ['a', 'a', 'b', 'd', 'f']:
    ll.insert(item)
print(ll.count())
#{'a': 3, 'b': 1, 'd': 1, 'f': 1}