Question

Please answer the following as soon as possible. Thank you. Add the top method in class...

Please answer the following as soon as possible. Thank you.

Add the top method in class Stack to the following python code which returns the top item of the stack. Test it.

Design top() method using a single queue as an instance variable, and only constant additional local memory within the method bodies.

python code:

class Stack:
    def __init__(self):
        self.q = Queue()

    def is_empty(self):
        return self.q.is_empty()

    def push(self, data):
        self.q.enqueue(data)

    def pop(self):
        for _ in range(self.q.get_size() - 1):
            dequeued = self.q.dequeue()
            self.q.enqueue(dequeued)
        return self.q.dequeue()

class Queue:
    def __init__(self):
        self.items = []
        self.size = 0

    def is_empty(self):
        return self.items == []

    def enqueue(self, data):
        self.size += 1
        self.items.append(data)

    def dequeue(self):
        self.size -= 1
        return self.items.pop(0)

    def get_size(self):
        return self.size



s = Stack()
s.push(1)
s.push(2)
s.push(3)
s.push(4)

Homework Answers

Answer #1

Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate the question. Thank You So Much.

class Stack:
def __init__(self):
self.q = Queue()

def is_empty(self):
return self.q.is_empty()

def push(self, data):
self.q.enqueue(data)

def pop(self):
for _ in range(self.q.get_size() - 1):
dequeued = self.q.dequeue()
self.q.enqueue(dequeued)
return self.q.dequeue()
def top (self):
return self.q.get_rear()
  
class Queue:
def __init__(self):
self.items = []
self.size = 0

def is_empty(self):
return self.items == []

def enqueue(self, data):
self.size += 1
self.items.append(data)

def dequeue(self):
self.size -= 1
return self.items.pop(0)

def get_size(self):
return self.size
  
def get_rear(self):
return self.items[self.size-1]

s = Stack()
s.push(1)
s.push(2)
s.push(3)
s.push(4)
s.push(40)
print("Top is : ",s.top())

output

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None:...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None: """This method adds new value to the tree, maintaining BST property. Duplicates must be allowed and placed in the right subtree.""" Example #1: tree = BST() print(tree) tree.add(10) tree.add(15) tree.add(5) print(tree) tree.add(15) tree.add(15) print(tree) tree.add(5) print(tree) Output: TREE in order { } TREE in order { 5, 10, 15 } TREE in order { 5, 10, 15, 15, 15 } TREE in order {...
"""linkedQueue.py implements LinkedQueue""" class Node(object): def __init__(self, e, nextNode): self.item, self.next = (e, nextNode) def __str__(self):...
"""linkedQueue.py implements LinkedQueue""" class Node(object): def __init__(self, e, nextNode): self.item, self.next = (e, nextNode) def __str__(self): return str(self.item)    class LinkedQueue(object): def __init__(self): #O(1) self._front, self._rear =(None, None) self._size = 0    def enqueue(self, e): # add e to the rear of the queue. newTail = Node(e, None) if self.isEmpty(): self._front = newTail else: self._rear.next = newTail self._rear = newTail self._size += 1 def front(self): # raise exception if it is empty, otherwise return front element if self.isEmpty(): raise Exception("call...
Python Problem 1 Create a function, biggest_ip_sum, outside of the ServerClass class, that: 1. Takes two...
Python Problem 1 Create a function, biggest_ip_sum, outside of the ServerClass class, that: 1. Takes two ServerClass objects 2. Sums the octets of the IP together (example 127.0.0.1 = 127+0+0+1 = 128) 3. Returns the larger number Example: server_one = ServerClass("127.0.0.1") server_two = ServerClass("192.168.0.1") result = biggest_ip_sum(server_one, server_two) print(result) In the example above, result will be 361. _________________________________ Problem 1 Here is the code to start with class ServerClass: """ Server class for representing and manipulating servers. """ def __init__(self,...
CAN YOU PLEASE ANSWER AS SOON AS POSSIBLE AND PLEASE ANSWER ALL QUESTIONS THANK YOU 1/...
CAN YOU PLEASE ANSWER AS SOON AS POSSIBLE AND PLEASE ANSWER ALL QUESTIONS THANK YOU 1/ Create a short paragraph using the following terms: sound, pinna, auditory canal, tympanic membrane, ossicles, middle ear, oval window. 2/ Why cone receptors are able to send information about different frequencies of light? 3/In your own words, explain one way in which neuroplasticity allows learning and memory to occur 4/ Sleep is a behavioral state and play a key role in cognition. So how...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity  ...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity   Code   Description   Project   File   Line   Suppression State Warning   C6385   Reading invalid data from 'DynamicStack': the readable size is '(unsigned int)*28+4' bytes, but '56' bytes may be read.   Here is the C++ code were I'm having the warning. // Sstack.cpp #include "SStack.h" // Constructor SStack::SStack(int cap) : Capacity(cap), used(0) {    DynamicStack = new string[Capacity]; } // Copy Constructor SStack::SStack(const SStack& s) : Capacity(s.Capacity), used(s.used)...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
I've posted this question like 3 times now and I can't seem to find someone that...
I've posted this question like 3 times now and I can't seem to find someone that is able to answer it. Please can someone help me code this? Thank you!! Programming Project #4 – Programmer Jones and the Temple of Gloom Part 1 The stack data structure plays a pivotal role in the design of computer games. Any algorithm that requires the user to retrace their steps is a perfect candidate for using a stack. In this simple game you...
Data Structures using C++ Consider the classes QueueADT and ArrayQueueType: QueueADT: #ifndef QUEUEADT_H #define QUEUEADT_H template...
Data Structures using C++ Consider the classes QueueADT and ArrayQueueType: QueueADT: #ifndef QUEUEADT_H #define QUEUEADT_H template <class ItemType> class QueueADT { public:        // Action responsibilities        virtual void resetQueue() = 0;           // Reset the queue to an empty queue.           // Post: Queue is empty.        virtual void add(const ItemType& newItem) = 0;           // Function to add newItem to the queue.           // Pre: The queue exists and is not full.          ...
ALL CODE MUST BE IN C++ Before you begin, you must write yourself a LinkedList class...
ALL CODE MUST BE IN C++ Before you begin, you must write yourself a LinkedList class and a Node class (please name your classes exactly ​as I did here). Please follow the below specifications for the two classes. Node.cpp ● This must be a generic class. ● Should contain a generic member variable that holds the nodes value. ● Should contain a next and prev Node* as denoted here. ● All member variables should be private. ● Use public and...