Python - 'int' object is not callable - python-3.x

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

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.

Related

Switching between classes and passing results

I am trying to add different PlugLead's to the PlugBoard and extract the combination. In the first class I am extracting the one letter from the list should they match or return the input. e.g.
lead = PlugLead("AG")
assert(lead.encode("A") == "G")
class PlugLead:
def __init__(self, c):
self.c = c
def encode(self, l):
c0 = self.c[0]
c1 = self.c[1]
if len(l) == 1 and c0 == l:
return c1
elif len(l) == 1 and c1 == l:
return c0
else:
return l
class Plugboard:
def __init__(self):
self.__head = 0
self.leads = []
self.c = []
def add(self, item):
if self.__head >= 10:
print("leads already got 10 items")
elif item in self.leads:
print(f"leads already have this item: {item}")
else:
self.leads.append(item)
self.__head += 1
return self.leads
def encode(self)
lines = plugboard.leads
for word in lines:
word = word.split(",")
PlugLead.encode(word)
In the second class I am trying to add multiple combinations and then at the end pass the one letter to see what its match is in the Class PlugLead however am not able to switch between the two. In the class PlugLead I have a add function that allows the different combinations to be added up to 10 and then I would like to encode from this list the combination of the pairs. e.g.
plugboard = Plugboard()
plugboard.add(PlugLead("SZ"))
plugboard.add(PlugLead("GT"))
plugboard.add(PlugLead("DV"))
plugboard.add(PlugLead("KU"))
assert(plugboard.encode("K") == "U")
assert(plugboard.encode("A") == "A")
if you want to use PlugLead("{balabala}"),you need use __new__ to return a dict when you create an instance, not __init__.
you want a key-value pair in Plugboard, it should be a dict not list
fix some other typo and bugs.
code:
class PlugLead:
def __new__(self, c):
return {c[0]:c[1]}
class Plugboard:
def __init__(self):
self.__head = 0
self.leads = {}
def add(self, item):
if self.__head >= 10:
print("leads already got 10 items")
elif list(item.keys())[0] in self.leads.keys():
print(f"leads already have this item: {item}")
else:
self.leads.update(item)
self.__head += 1
return self.leads
def encode(self,key):
if key in self.leads:
return self.leads[key]
elif key in self.leads.values():
return list(self.leads.keys())[list(self.leads.values()).index(key)]
return key
plugboard = Plugboard()
plugboard.add(PlugLead("SZ"))
plugboard.add(PlugLead("GT"))
plugboard.add(PlugLead("DV"))
plugboard.add(PlugLead("KU"))
plugboard.add(PlugLead("KU"))
assert(plugboard.encode("K") == "U")
assert(plugboard.encode("U") == "K")
assert(plugboard.encode("A") == "A")
print(plugboard.encode("K"))
print(plugboard.encode("U"))
print(plugboard.encode("A"))
result:
leads already have this item: {'K': 'U'}
U
K
A

Add a node specific counter to a slingly linked list

Did some research, but could only find examples where there was a key - say '5' and they count the occurrences of '5' in the linked list. I want to count each occurrence of each string in a llist. Say I have a linked list with ' a, a, a, b, d, f'. I want the output to say a - 3 b - 1 d -1 f -1.
I have built the list but the only way I can think of doing it is initializing a count variable, however I can't figure out how to reset it as I print the entire list after everything is done so right now my output looks like: a - 3 b -3 d -3 f -3.
Here is the code:
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
Revised Code:
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
Since you want your count function to be able to count the frequencies of each word, I would create a function similar to print called count in class Linked_List, which iterates through the list, and updates the frequency dictionary.
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
The output will look like.
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}

trying to look for duplicates in an ordered list

So my programs function is to add the provided numbers to an ordered list, then search for the duplicates. I have a function that finds the duplicates of a number I asked and I know is a duplicate. Im trying to get the duplic function to read through the list and append the duplicates to a new list called seen.
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setNext(self,newnext):
self.next = newnext
class OrderedList:
def __init__(self):
self.head = None
def add(self, item):
current = self.head
previous = None
stop = False
while current != None and not stop:
if current.getData() > item:
stop = True
else:
previous = current
current = current.getNext()
temp = Node(item)
if previous == None:
temp.setNext(self.head)
self.head = temp
else:
temp.setNext (current)
previous.setNext(temp)
def prntlist(self):
prnt = self.head
while prnt != None:
print(prnt.data, end=" ")
prnt = prnt.next
print()
def duplic (self):
currnt = self.head
seen = set()
uniq = []
for i in range(int(currnt.data)):
if i not in seen:
uniq.append(i)
seen.add(i)
print (seen)
def count(self, item):# function to count the value
count = 0
ptr = self.head
while ptr != None:
if (ptr.data == item):
count += 1
ptr = ptr.next
return count
mylist = OrderedList()
mylist.add(23)
mylist.add(23)
mylist.add(10)
mylist.add(14)
mylist.add(5)
mylist.add(31)
mylist.add(35)
mylist.add(37)
mylist.add(26)
mylist.add(23)
mylist.add(29)
mylist.add(18)
mylist.add(2)
mylist.add(25)
mylist.prntlist()
print('Count of 23 in list: ', mylist.count(23))
print('Duplicates in list: ', mylist.duplic())
I would like it to print:
mylist
Count of 23 in list: 3
Duplicates in list: {23,23}
You may need to be more clear in the question..
From what i understand, you could write the function this way:
def duplic (self):
currnt = self.head
seen = set()
for i in currnt.data:
if currnt.data.count(i)>1:
seen.add(i)
print (seen)
The uniq seems to be useless. And, a set object cannot have two same elements, so you can't have {23,23}. (you can write this, but it will result in {23} in the end)

Heap Structure with Key Function in initalizer

I'm basically trying to implement this Heap Structure in Python and I've editing the portions under def heap-iffy and def add but I'm not sure how to how to use the current initialize with a key function. This function will be used to extract a value from each element added to the heap; these values, in turn, will be used to order the elements. f no key function is provided, the default max-heap behavior should be used — the "lambda x:x" default value for the initialize method does just that.
class Heap:
def __init__(self, key=lambda x:x):
self.data = []
self.key = key
#staticmethod
def _parent(idx):
return (idx-1)//2
#staticmethod
def _left(idx):
return idx*2+1
#staticmethod
def _right(idx):
return idx*2+2
def _heapify(self, idx=0):
enter code here
while True:
l = Heap._left(idx)
r = Heap._right(idx)
maxidx = idx
if l < len(self) and self.data[l] > self.data[idx]:
maxidx = l
if r < len(self) and self.data[r] > self.data[maxidx]:
maxidx = r
if maxidx != idx:
self.data[idx], self.data[maxidx] = self.data[maxidx], self.data[idx]
idx = maxidx
else:
break
def add(self, x):
enter code here
self.data.append(x)
i = len(self.data) - 1
p = Heap._parent(i)
while i > 0 and self.data[p] < self.data[i]:
self.data[p], self.data[i] = self.data[i], self.data[p]
i = p
p = Heap._parent(i)
def peek(self):
return self.data[0]
def pop(self):
ret = self.data[0]
self.data[0] = self.data[len(self.data)-1]
del self.data[len(self.data)-1]
self._heapify()
return ret
def __bool__(self):
return len(self.data) > 0
def __len__(self):
return len(self.data)
def __repr__(self):
return repr(self.data)

Sort a unordered list class in python? solution?

I have a Unordered list class like this :
from node import Node
class UnorderedList:
"""
Unordered list
"""
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def __len__(self):
"""
returns the length of the list O(1)
"""
return self.size()
def add(self, item):
"""
Add item to list
"""
temp = Node(item)
temp.set_next(self.head)
self.head = temp
def size(self):
"""
Return size of list
"""
current = self.head
count = 0
while current != None:
count = count + 1
current = current.get_next()
return count
def set(self, index, newdata):
"""
Set node-data in list at specific index
"""
current = self.head
previous = None
for i in range(index):
previous = current
current = current.get_next()
if current != None:
temp = Node(newdata)
temp.set_next(current)
if previous is None:
self.head = temp
else:
previous.set_next(temp)
else:
raise("index out of range")
def getIndex(self, item):
"""get the index of an item, assume the first one (head pointing to)
is 0"""
index = 0
current = self.head
found = False
while current != None:
if current.get_data() == item:
found = True
break
else:
current = current.get_next()
index += 1
if not found:
index = None
return index
def get(self, index):
"""
Returns node data based on index
"""
current = self.head
for i in range(index):
current = current.get_next()
if current != None:
return current.get_data()
else:
raise("index out of range")
def search(self, item):
"""
Returns True if item found, else return False
"""
# Här ska du returnera en bool (True/False)
# beroende på om 'item' finns i listan
current = self.head
found = False
while current != None and not found:
if current.get_data() == item:
found = True
else:
current = current.get_next()
return found
def print_list(self):
"""
Prints each item in list
"""
# Traversera listan och gör en print() på varje element
result = "["
node = self.head
if node != None:
result += str(node.data)
node = node.next
while node:
result += ", " + str(node.data)
node = node.next
result += "]"
return result
def remove(self, item):
"""
Removes item from list
"""
current = self.head
previous = None
found = False
while not found:
if current.get_data() == item:
found = True
else:
previous = current
current = current.get_next()
if previous == None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
I want to create a class list and then i can sort the list with my "bubblesort" function.
My "bubblesort" function look like this :
def bubble_sort(items):
""" Bubble sort """
Size = items.size()
for i in range(Size):
for j in range(Size-1-i):
if items.get(j) > items.get(j+1):
tmps = items.get(j+1)
items.set(j, items.get(j+1))
items.set(j+1, tmps)
return items
Now let us create a list :
// create the list
myListTwo = UnorderedList()
// Add the elements to the list
myListTwo.add(4)
myListTwo.add(50)
myListTwo.add(6)
myListTwo.add(10)
myListTwo.add(60)
//print the list :
print(myListTwo.print_list())
[60, 10, 6, 50, 4]
In this stage all work very well but the problem is when I want to sort the list with my bubble_sort function I got this result :
// bubble_sort my list
sorte = bubble_sort(myListTwo)
//print the list
print(sorte.print_list())
[10, 10, 10, 10, 60, 10, 6, 50, 4]
Any idea?
Thanx/Georges
So, you have two issues to your implementation.
The first one is the inner code of bubble sort. Change this
tmps = items.get(j+1)
to
tmps = items.get(j)
See here for more about swapping Python Simple Swap Function
The second issue is the set method. You should remove this
temp = Node(newdata)
temp.set_next(current)
if previous is None:
self.head = temp
else:
previous.set_next(temp)
and you should write something like this
current.set_data(newData)
(I don't know how exactly you implemented the Node class)

Resources