I need to mirror a queue using a function called mirror
I have made the code for the queue class, but i dont know how to create a mirror of it. It needs to print out the original queue and then the same queue reversed
Any help would be appreciated
My Code:
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def is_empty(self):
return not self.items
def size(self):
return len(self.items)
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def mirror(n):
pass
This will work. Your queue is composed of a list, so you can use slice syntax on the list to get a reversed version of the queue.
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.append(item)
def __str__(self):
'''Allow print to be called on the queue object itself'''
return str(self.items)
def __getitem__(self, i):
'''Allow the queue object to be indexable directly'''
return self.items[i]
def mirror(q):
return q[::-1]
q = Queue()
for i in range(10):
q.enqueue(i)
print q
print mirror(q)
Note: A queue appends to the end, not the start. That's the behaviour of a stack.
Maybe you give this one a try: How can I reverse a list in python
You can create a new queue using the reversed self.items list in a member function mirror.
q = ArrayQueue()
def mirror(q):
copy = ArrayQueue()
stack = ArrayStack()
while not q.is_empty():
stack.push(q.first())
copy.enqueue(q.dequeue())
while not stack.is_empty():
copy.enqueue(stack.pop())
for i in range(len(copy)):
print(copy.dequeue(),end=" ")
Related
hey guys i am new to data structure and i havee been wondering how to inherit a parent class attributes.
I am trying to inherit the attributes of stack(parent) to stack3(child) but the error keeps popping up: TypeError: init() missing 1 required positional argument: '_Stack3__list'
Any help or suggestions would be appreciated!
class Stack:
def __init__(self):
self.__list= []
def isEmpty(self):
return self.__list == []
def size(self):
return len(self.__list)
def clear(self):
self.__list.clear()
def push(self, item):
self.__list.append(item)
def pop(self):
if self.isEmpty():
return None
else:
return self.__list.pop()
def get(self):
if self.isEmpty():
return None
else:
return self.__list[-1]
def __str__(self):
output = '<'
for i in range( len(self.__list) ):
item = self.__list[i]
if i < len(self.__list)-1 :
output += f'{str(item)}, '
else:
output += f'{str(item)}'
output += '>'
return output
class Stack3(Stack):
def __init__(self,__list):
self.__list = __list
super().__init__(self.__list)
def printMe(self):
super().__str__()
s = Stack3()
print(s.pop())
for i in range(1,6):
s.push(i)
print('Content of stack =',s)
print('Item at top=',s.get())
print('Size=', s.size())
while not s.isEmpty():
print(s.pop())
print(s)
If you want to pass all arguments from Stack3.__init__ to Stack. __init__ use:
class Stack3(Stack):
def __init__(self,*args, **kwargs):
super().__init__(*args, **kwargs)
see here for a detailed explanation of *args and **kwargs usage.
I'm reading a book on data structures and algorithms and understand the overall goal of the code but for top() and pop() there are strange member variables. Is this some sort of python abstraction that I am running into (ex. self._head._element) or a feature of not using pythons dictionary variable assignment?
'''
class LinkedStack:
class _Node:
__slots__ = '_element','_next' #treats elements not like a dictionary
def __init__(self, element, next):
self._element = element
self._next = next
def __init__(self):
self._head = None
self._size = 0
def __len__(self):
return self._size
def is_empty(self):
return self._size == 0
def push(self, e):
self._head = self._Node(e, self._head)
self._size += 1
def top(self):
if self.is_empty():
raise Empty('Stack is empty')
else:
return self._head._element
def pop(self):
if self.is_empty():
raise Empty('Stack is empty')
answer = self._head._element
self._head = self._head._next
self._size -=1
return answer
'''
import Queue_PlistLR as queueList
class Stack_2Queues():
def __init__(self, name, salary):
self.items = []
self.name = name
self.salary = salary
def isEmpty(self):
return len(self.items) == 0
def push(self, e):
self._data.append(e)
def pop(self):
if self.is_empty:
raiseEmpty("Stack is empty")
return self._data.pop()
def size(self):
return len(self.items)
def to_String(self):
str_i = ""
for e in self.items:
str_i+=str(e)+" "
return str_i.strip()
def length(self):
return len()
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if self.isEmpty():
raise Empty('Queue is empty')
return self.items.pop(0)
def employeeName(self):
print("The employee is: ", self.name)
def employeeSalary(self):
print("Employees salary is", self.salary)
s1 = Stack_2Queues(["Ash", "Jen", "Mike", "Zach"], [45000, 32000, 74000, 960000])
s1.employeeName()
s1.employeeSalary()
s1.employeeName.push("Earl")
s1.employeeSalary.push(55000)
I am trying to push new values to the queues employeeName and employeeSalary()
However I am faced with this error. What am I doing wrong?
s1.employeeName.push("Earl")
s1.employeeSalary.push(55000)
This is calls of push on methods. What is the idea? You have push/pop methods on your class, start with calling s1.push
Btw, you should probably look into deque
'function' object has no attribute 'push'
...
What am I doing wrong?
employeeName and employeeSalary are not queues, the are instance methods (functions) of your class. They do not have a (callable) push attribute. They do not contain anything, they do something, so you cannot add to them.
I scoured the web to come up with this implementation of MinHeap and Maxheap in Python.
import heapq
class MinHeap:
def __init__(self):
self.heap = []
def push(self, item):
heapq.heappush(self.heap, item)
def pop(self):
return heapq.heappop(self.h)
def __getitem__(self, item):
return self.heap[item]
def __len__(self):
return len(self.h)
class MaxHeap(MinHeap):
def push(self, item):
heapq.heappush(self.heap, Comparator(item))
def pop(self):
return heapq.heappop(self.h)
def __getitem__(self, i):
return self.heap[i].val
class Comparator:
def __init__(self, val):
self.val = val
def __lt__(self, other):
return self.val > self.other
def __eq__(self, other):
return self.val == self.other
def __str__(self):
return str(self.val)
Now I need to add a peek method to both these classes. In it's current implementation I could pop and push back. But my question is, is there a better way to do it. Something in O(1) time.
These classes are based on Python's heapq structure, which is built on a standard Python list. The smallest item in the minheap and the largest item in the maxheap is at index zero. So just return
self.heap[0]
If the heap is empty, that will cause an error, but that probably is what you want.
The program I am creating should run a queue class however errors occur that append is not able to be used in the class as it does not exist, even thought it is set to a string. Could someone help me understand why I am receiving these errors?
class Queue:
def queue(self):
self.queue = []
self.out_stack = []
def enqueue(self, other='string'):
self.enqeue = self.queue.append(other)
def dequeue(self):
if not self.out_stack:
while self.queue:
self.dequeue = self.out_stack.append(self.queue.pop(1))
return self.dequeue
def isEmpty(self):
return self.queue == []
When you create an instance variable self.queue, you are shadowing the method defined by def queue(self):
It looks like that method should perhaps be your __init__ method
class Queue:
def __init__(self):
self.queue = []
self.out_stack = []
def enqueue(self, other='string'):
self.queue.append(other)
def dequeue(self): # what is this method supposed to do?
if not self.out_stack:
while self.queue:
self.dequeue = self.out_stack.append(self.queue.pop(1))
return self.dequeue
def isEmpty(self):
return self.queue == []
Now there is still a similar problem with self.dequeue being used as both a method and an attribute. I am not sure what you are trying to do there.