Joshua Smith
Joshua Smith

Reputation: 23

Python - 'int' object is not callable

I'm writing a singly linked list that counts the number of words that get imported from a test file. I initialized count inside of my class. I defined the print function, that prints out each of the nodes, after they are sorted. I defined a count class to iterate through the list and count up all the occurences of a word fed to it.

I want to pass in every node into count to count how many times it appears in my text file. When I try to do that I end up with 'int' object is not callable. Here is my code

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

    def print(self):
        p = self.head
        head = Linked_List_node(p.data)
        while p is not None:
            print(p.data, '-', self.count(p.data)) # This is where the error appears
            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

    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)

                #head.counter += 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

Upvotes: 0

Views: 403

Answers (1)

Koterpillar
Koterpillar

Reputation: 8104

Relevant part from your code is:

class Linked_List:
    def __init__(self):
        # ...
        self.count = 1

    def count(self, x):
        # ...

The self.count = 1 assignment overwrites the value of self.count for every Linked_List object that's created, so it refers to 1 instead of the method you defined on the class. Rename either the variable or the function.

Upvotes: 1

Related Questions