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. ;)
Related
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.
so I am trying to create a list of stack objects in Python. I have first created a class Stack that has simple methods that a Stack should have. I have then created another class called Stacks. I am trying to create a list of stacks. If a stack has more than 3 elements, it creates a new stack but I get an error when I try to display the elements. Could someone point out what I might be doing wrong here please?
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def printStack(self):
for item in reversed(self.items):
print (item)
class Stacks:
def __init__(self):
self.stacks = []
self.noOfStacks = 0
self.itemsOnStack = 0
def dev(self):
self.stacks.append(Stack())
# if len(self.stacks) != 0:
# self.noOfStacks += 1
def push(self, item):
if self.itemsOnStack > 3:
self.dev()
else:
self.itemsOnStack += 1
self.stacks[self.noOfStacks].push(item)
def pop(self, stackNo):
return self.stacks(noOfStacks).pop()
def size(self):
return len(self.stacks)
def printtack(self, index):
print (len(self.stacks(index)))
self.stacks(index).printStack()
stacky = Stacks()
stacky.dev()
stacky.push(3)
stacky.printtack(0)
Indexing lists in Python works by [] not (). Try
def printtack(self, index):
self.stacks[index].printStack()
One thing to note as kshikama said indexing should be done using [] not (),the other problem is using the len() method in the stack class u most override the __len__() method or as u have given use the size() method
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def printStack(self):
for item in reversed(self.items):
print (item)
class Stacks:
def __init__(self):
self.stacks = []
self.noOfStacks = 0
self.itemsOnStack = 0
def dev(self):
self.stacks.append(Stack())
#if len(self.stacks) != 0:
#self.noOfStacks += 1
def push(self, item):
if self.itemsOnStack > 3:
self.dev()
else:
self.itemsOnStack += 1
self.stacks[self.noOfStacks].push(item)
def pop(self, stackNo):
return self.stacks(noOfStacks).pop()
def size(self):
return len(self.stacks)
def printtack(self, index):
print (self.stacks[index].size())
self.stacks[index].printStack()
stacky = Stacks()
stacky.dev()
stacky.push(3)
stacky.printtack(0)
OUTPUT
1
3
I'm writing an implementation of doubly linked lists. In order to traverse the list, I'm using something like:
class Node:
""" A node in our linked list """
def __init__(self, value: Any, next: Union['Node', None] =None,
previous: Union['Node', None] =None) -> None:
self.value = value
self.next = next
self.previous = previous
...
def __next__(self, direction: int =1) -> Union['Node', None]:
if direction == 1:
return self.get_next()
else:
return self.get_previous()
...
where get_next and get_previous are just getters of self.next and self.previous.
However, PyCharm yells at me for trying to call next as
next(some_node, direction=-1). What's the proper way to do this?
Besides __iter__ there is also __reversed__. Both are required to return iterators. The __next__ method should be implemented on iterators (not on node-classes). Note that all magic methods (when called by a function like next instead of directly invoked) need to implement the expected arguments not more - not less.
For example a doubly linked list could just implement __iter__ and __reversed__ and rely on next and previous attribute of the Node:
class Node(object):
def __init__(self, val, nxt, prv):
self.val = val
self.nxt = nxt
self.prv = prv
class DoublyLinkedList(object):
def __init__(self, base=None, last=None):
self.base = base
self.last = last
def prepend(self, val):
new = Node(val, self.base, None)
if self.base is None:
self.base = new
self.last = new
else:
self.base.prv = new
self.base = new
def append(self, val):
new = Node(val, None, self.last)
if self.last is None:
self.base = new
self.last = new
else:
self.last.nxt = new
self.last = new
def __iter__(self):
current = self.base
while current is not None:
yield current
current = current.nxt
def __reversed__(self):
current = self.last
while current is not None:
yield current
current = current.prv
For example:
dl = DoublyLinkedList()
dl.prepend(10)
dl.prepend(20)
dl.prepend(30)
for i in dl:
print(i.val)
gives:
30
20
10
similar for reversed:
for i in reversed(dl):
print(i.val)
# prints:
10
20
30
__next__ is part of the iterator protocol and should be used as described in said protocol, doing otherwise only make problems with the rest python.
In your case just rename the function to simple next and use as some_node.next(-1), though I would change the direction argument to a boolean, as that is how you use it, and its name too. Like this for example
class None:
...
def next(self, forward:bool=True) -> Union['Node', None]:
if forward:
return self.get_next()
else:
return self.get_previous()
and use as some_node.next(), some_node.next(False) or even some_node.next(0) (using 0 instead of False for the same effect)
The extra argument to next is a default value, and __next__ doesn't take any extra arguments. Python doesn't have any sort of two-way iterators. If your interface is not exactly the same as for i in obj:, then you should write your own.
I'm doing some basic Python programming practice exercises and tried to implement a queue (using lists). Unfortunately, I'm getting behavior for my isempty() function that I don't understand. When running the code below, the last two lines give different answers: A yields False, while B yields True. Why doesn't A also yield False?
class Queue:
def __init__(self):
self.items = []
def push(self,item):
self.items.insert(0,item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def isempty(self):
return self.size == 0
q = Queue()
q.push("a")
q.push("b")
print(q.pop())
print(q.isempty())
print(q.pop())
print(q.isempty()) # shouldn't this (A)...
print(q.size()==0) # ...and this (B) yield the same answer?
Just change your isempty() method to:
def isempty(self):
return self.size() == 0
Your implementation of Queue.isempty() is checking to see if the method size is equal to the integer 0, which will never be true.
class Queue:
def __init__(self):
self.items = []
def push(self,item):
self.items.insert(0,item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def isempty(self):
return self.size == 0
q = Queue()
print(q.size)
Produces:
<bound method Queue.size of <__main__.Queue object at 0x02F4EA10>>
The easiest solution is to use Christopher Shroba's suggestion to modify your Queue.isempty() implementation to use the list's size method.
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.