-2

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
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
Kryptic12
  • 3
  • 2

3 Answers3

0

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.

Community
  • 1
  • 1
0

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.

Community
  • 1
  • 1
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
0
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=" ")
Sabelo
  • 1
  • 1