I'm new to Python, thus the question. This is my implementation of a Queue
class Queue:
def __init__(self):
self.top = None
self.marker = None
self.size = 0
def push(self, item):
self.size += 1
curr = Node(item)
if self.top is None:
self.top = curr
self.marker = curr
else:
self.marker.next = curr
self.marker = curr
def pop(self):
if self.top is None:
raise Exception("Popping an empty queue")
curr = self.top
self.size -= 1
if self.top is self.marker:
self.top = None
self.marker = None
else:
self.top = self.top.next
return curr
def peek(self):
return self.top.value
def size(self):
return self.size
def isempty(self):
return self.size == 0
The Node class is defined as follows,
class Node:
def __init__(self, value=None, next=None):
self.value = value;
self.next = next
This implementation works fine for most of the methods except when I call size.
This call,
print(queue.size())
Results in the following exception,
print(queue.size())
TypeError: 'int' object is not callable
Can't seem to understand what the issue is here.
You gave an attribute and a method the same name, size. This confuses name resolution (to you; the interpreter has its rules tightly in place). Check your name resolution precedence; I think you'll find that the attribute takes precedence in this case. Thus, queue.size resolves to an integer, not a function.
Related
So i've been trying to solve a problem in leetcode that is to design a linked list. Here's what i tried:
class Node:
def __init__(self,next=None,val=None):
self.next = next
self.val = val
class Linked_list(object):
def __init__(self):
self.head = None
self.length = 0
def insertAtEnd(self, val):
new_node = Node(val)
if self.head is None:
self.head = new_node
else:
itr = self.head
while itr.next: #Error
itr = itr.next
itr.next = new_node
self.length += 1
So in the insertAtEnd method when i try to iterate over the list it shows the error that self.head is an an int object. I'm struggling to find an answer here. So please help me out. Thank you!
Your code is fine but I found one bug there
new_node = Node(val)
But constructor looks:
def __init__(self,next=None,val=None):
self.next = next
self.val = val
So you pass your val to next parameter and self.head.next points to val which is int. Probably you ment
new_node = Node(val=val)
Or alternatively, change order of next and val in Node constructor.
So i started learning about listNodes or linked lists in python and created one;
class Node:
def __init__(self, data, next = None):
self.data = data
self.next = next
class LinkedNode:
def __init__(self):
self.head = None
self.size = 0
def add(self, data):
self.head = Node(data, self.head)
self.size += 1
It works fine but how can i get a listNode in python as the result of this node.
What i mean is a list node looks like this;
{val: 'some_val', next: {val: 'other_val', next{...}}}
In js, when we print the instance of the list node class, it gets the result in the same format but, in python when i tried the same;
ln = LinkedNode()
print(ln)
It gives this;
<main.LinkedNode object at 0x7fe191576400>
There are several ways to make your instance print something more useful.
For instance, you could add a method that will produce a dict, because dictionaries are printed in an output format that is similar to what you ask for:
class Node:
def __init__(self, data, next = None):
self.data = data
self.next = next
def asdict(self):
return { "data": self.data, "next": self.next and self.next.asdict() }
So now when you do this:
print(Node(1).asdict())
... you'll get:
{'data': 1, 'next': None}
When you also add such a method to the LinkedNode class:
class LinkedNode:
def __init__(self):
self.head = None
self.size = 0
def add(self, data):
self.head = Node(data, self.head)
self.size += 1
def asdict(self):
return self.head and self.head.asdict()
...you can do:
lst = LinkedNode()
lst.add(1)
lst.add(2)
print(lst.asdict())
And that will output:
{'data': 2, 'next': {'data': 1, 'next': None}}
And finally, if you want this output to be the default that print will use when you just do print(lst), then define __repr__ (or __str__) on the class:
class LinkedNode:
def __init__(self):
self.head = None
self.size = 0
def add(self, data):
self.head = Node(data, self.head)
self.size += 1
def asdict(self):
return self.head and self.head.asdict()
def __repr__(self):
return repr(self.asdict())
Now you can do print(lst) without calling .asdict() explicitly, and get that same output.
The "append" method is not working correctly.
It's only going inside the 'if" statement of the "append' method and not entering into the while loop.
class Node:
def __init__(self,data=None):
self.data=data
self.next=None
class Linkedlist:
def __init__(self):
self.head=Node()
def append(self,data):
new_node=Node(data)
if self.head.data is None:
self.head=new_node
cur_node=self.head
while cur_node.next is not None:
cur_node=cur_node.next
cur_node=new_node
def insert_after_node(self,prev_node,data):
new_node=Node(data)
if prev_node is None:
print("node that you have entered does not exist")
new_node.next=prev_node.next
prev_node.next=new_node
def display(self):
current=self.head
while current.next is not None:
print(current.data)
current=current.next
List=Linkedlist()
List.append("A")
List.append("B")
List.append("C")
List.insert_after_node(List.head,"g")
List.display()
Expected output: AgBC
Actual Output: A
Your .append() method simply sets a local variable to cur_node to point to new_node. This doesn't change the linked list at all; the last node in the link that was previously assigned to that local variable is not changed.
You instead want to assign to the .next attribute of the last node:
cur_node.next = new_node
The while loop in the method is working fine otherwise.
You also should not use new_node twice, when the list is empty. Exit when you don't yet have a head node with data:
if self.head.data is None:
self.head=new_node
return
Personally, I'd set self.head = None instead of self.head = Node(), then use if self.head is None:.
Next, your display function forgets to print the last element. Rather than test for current.next, check if current is None; this is where setting self.head to None for an empty list would work a lot better:
def display(self):
current = self.head
while current is not None
print(current.data)
current = current.next
I had the exact same question as you, but my implementation was different and it seems to work just fine.
First I created a node class with all its different methods:
class Node:
def __init__(self, init_data):
self.data = init_data
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, new_data):
self.data = new_data
def set_next(self, new_next):
self.next= new_next
The I created my UnorderedList class with its methods too, including append. insert, index and pop I am still working on...
class UnorderedList:
"""
An unordered list class built from a collection of nodes.
"""
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def add(self, item):
temp = Node(item)
temp.set_next(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count += 1
current = current.get_next()
return count
def search(self, item):
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 remove(self, item):
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())
def print_list(self):
current = self.head
while current != None:
print(current.data)
current = current.get_next()
def append(self, item):
new_node = Node(item)
if self.head == None:
self.head = new_node
return
current = self.head
found_last = False
while not found_last:
if current.get_next() == None:
found_last = True
current.set_next(new_node)
else:
current = current.get_next()
def insert(self, item, pos):
pass
def index(self, item):
pass
def pop(self):
pass
I realize my version of append is more verbose, but I was using the traversal method I previously used as part of my size method to make it work, and it seems to work just fine.
I found it easier to create a Node class with its methods separately as it made it easier to visualize how to set the next node and get data from the current one. Hope this helps!
FYI the node class and a lot of the UnorderedList is straight out of Problem Solving with Algorithms and Data Structures in Python by David Ranum and Brad Miller, so I know they work fine!
class Node:
def __init__(self,data=None):
self.data=data
self.next=None
class LinkedList():
def __init__(self):
self.head=Node()
def append(self,data):
new_node=Node(data)
if self.head.data is None:
self.head=new_node
else:
cur_node=self.head
while cur_node.next is not None:
cur_node=cur_node.next
cur_node.next=new_node
def insert_after_node(self,prev_node,data):
new_node=Node(data)
if prev_node is None:
print("node that you have entered does not exist")
new_node.next=prev_node.next
prev_node.next=new_node
def display(self):
current=self.head
while current.next is not None:
print(current.data)
current=current.next
print(current.data)
List=LinkedList()
List.append("A")
List.append("B")
List.append("C")
List.insert_after_node(List.head,"g")
Fixed some bugs for you:
The class name LinkedList mismatch problem
In append, if self.head.data is None, it should set self.head and then return.
In the else part of append, let the last node point to the new node by cur_node.next=new_node
In display, the last node should also be printed.
I have the following code in python. My question is how do you print each element in the linked queue? I know that I will have to make a __repr__ or __str__ function but I am unsure how to implement it. Thanks.
class LinkedQueue :
class _Node :
def __init__(self, element, next):
self._element = element
self._next = next
def get_elements():
return self._element
def set_elements(num):
self._element = num
def __init__(self) :
self._head = None
self._tail = None
self._size = 0
def __len__(self) :
return self._size
def is_empty(self) :
return self._size == 0
def first(self) :
if self.is_empty() :
raise Empty('Queue is empty')
return self._head._element
def dequeue(self) :
if self.is_empty():
raise Empty('Queue is empty')
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.is_empty() :
self._tail = None
return answer
def enqueue(self, e) :
newest = self._Node(e,None)
if self.is_empty() :
self._head = newest
else :
self._tail._next = newest
self._tail = newest
self._size += 1
class Empty(Exception) :
pass
It depends on what you want the repr to look like, but here's one way. We give the _Node class a simple __repr__ that just returns the repr of the element, and to build the repr for a LinkedQueue instance we walk the linked list, storing the repr of each Node into a list. We can then call .join on that list to make the repr for the LinkedQueue.
class Empty(Exception):
pass
class LinkedQueue:
class _Node:
def __init__(self, element, _next=None):
self._element = element
self._next = _next
def __repr__(self):
return repr(self._element)
def __init__(self):
self._head = None
self._tail = None
self._size = 0
def __len__(self):
return self._size
def __repr__(self):
lst = []
head = self._head
while head is not None:
lst.append(repr(head))
head = head._next
return 'Queue({})'.format(", ".join(lst))
def is_empty(self):
return self._size == 0
def first(self):
if self.is_empty():
raise Empty('Queue is empty')
return self._head._element
def dequeue(self):
if self.is_empty():
raise Empty('Queue is empty')
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.is_empty():
self._tail = None
return answer
def enqueue(self, e):
newest = self._Node(e)
if self.is_empty():
self._head = newest
else:
self._tail._next = newest
self._tail = newest
self._size += 1
# test
q = LinkedQueue()
for u in 'abcd':
q.enqueue(u)
print(len(q))
print(q)
while not q.is_empty():
print(q.first(), q.dequeue())
output
1
2
3
4
Queue('a', 'b', 'c', 'd')
a a
b b
c c
d d
I got rid of the getter & setter method in Node, since you don't use them, and we don't normally write getters & setters like that in Python. See the Descriptor HowTo Guide in the docs.
FWIW, I would make Node a separate class (or get rid of it entirely), rather than nesting it in LinkedQueue. I guess it doesn't hurt to nest it, but nested class definitions aren't often used in Python.
BTW, the collections.deque is a very efficient double-ended queue. For simple queues and stacks, it's generally faster than list. But I guess this LinkedQueue class is for an exercise in implementing linked lists in Python, so collections.deque isn't currently relevant for you. ;)
I need some help writing an __iter__() method for my UnorderedList() class. I tried this:
def __iter__(self):
current = self
while current != None:
yield current
But the while loop doesn't stop. Here is the rest of my classes and code:
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 setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
self.count = 0
If you want to iterate all items succeedingly, you should do
def __iter__(self):
# Remember, self is our UnorderedList.
# In order to get to the first Node, we must do
current = self.head
# and then, until we have reached the end:
while current is not None:
yield current
# in order to get from one Node to the next one:
current = current.next
so that in every step you go one step further.
BTW, setters and getters aren't used in Python in the form of methods. If you need them, use properties, otherwise omit them altogether.
So just do
class Node(object):
def __init__(self, initdata):
self.data = initdata
self.next = None
class UnorderedList(object):
def __init__(self):
self.head = None
self.count = 0
def __iter__(self):
current = self.head
while current is not None:
yield current
current = current.next