Question

In: Computer Science

(based on 8.38) A stack is a sequence container type that, like a queue, supports very...

  1. (based on 8.38) A stack is a sequence container type that, like a queue, supports very restrictive access methods: all insertions and removals are from one end of the stack, typically referred to as the top of the stack. A stack is often referred to as a list-in first-out (LIFO) container because the last item inserted is the first removed. Implement a Stack class. It should support the following methods/functions:
    1. _init__ - Can construct either an empty stack, or initialized with a list of items, the first item is at the bottom, the last is at the top.
    2. push() – take an item as input and push it on the top of the stack
    3. pop() – remove and return the item at the top of the stack
    4. isEmpty() – returns True if the stack is empty, False otherwise
    5. [] – return the item at a given location, [0] is at the bottom of the stack
    6. len() – return length of the stack

The object is to make this client code work:

'''

>>> s = Stack()

>>> s.push('apple')

>>> s

Stack(['apple'])

>>> s.push('pear')

>>> s.push('kiwi')

>>> s

Stack(['apple', 'pear', 'kiwi'])

>>> top = s.pop()

>>> top

'kiwi'

>>> s

Stack(['apple', 'pear'])

>>> len(s)

2

>>> s.isEmpty()

False

>>> s.pop()

'pear'

>>> s.pop()

'apple'

>>> s.isEmpty()

True

>>> s = Stack(['apple', 'pear', 'kiwi'])

>>> s = Stack(['apple', 'pear', 'kiwi'])

>>> s[0]

'apple'

>>>

'''

use python3.7

>>> s = Stack()
>>> s.push('apple')
>>> s
Stack(['apple'])
>>> s.push('pear')
>>> s.push('kiwi')
>>> s
Stack(['apple', 'pear', 'kiwi'])
>>> top = s.pop()
>>> top
'kiwi'
>>> s
Stack(['apple', 'pear'])
>>> len(s)
2
>>> s.isEmpty()
False
>>> s.pop()
'pear'
>>> s.pop()
'apple'
>>> s.isEmpty()
True
>>> s = Stack(['apple', 'pear', 'kiwi'])
>>> s = Stack(['apple', 'pear', 'kiwi'])
>>> s[0]
'apple'
>>>

check that Stacks constructed without a list remain distinct
if you receive an error on s2 then you probably need to use a
default argument of None in __init__
(see the Queue class developed in class for an example)

>>> s = Stack()
>>> s.push('apple')
>>> s
Stack(['apple'])
>>> s2 = Stack()
>>> s2.push('pear')
>>> s2 # if this fails - see the TEST file for explanation
Stack(['pear'])

Solutions

Expert Solution

SOURCE CODE:

*Please follow the comments to better understand the code.

**Please look at the Screenshot below and use this code to copy-paste.

***The code in the below screenshot is neatly indented for better understanding.

class Stack:
    # Constructor
    # Can construct either an empty stack,
    # or initialized with a list of items,
    # the first item is at the bottom, the last is at the top
    def __init__(self, items=None):
        if items is None:
            self.data = []
        else:
            self.data = items

    # take an item as input and push it on the top of the stack
    def push(self,item):
        self.data.append(item)

    # remove and return the item at the top of the stack
    def pop(self):
        return self.data.pop(-1)

    #  returns True if the stack is empty, False otherwise
    def isEmpty(self):
        return len(self.data)==0

    # gives the length of the stack
    def __len__(self):
        return len(self.data)

    # gives the item at location
    def __getitem__(self, index):
        return self.data[index]

    # string representation
    def __str__(self):
        return 'Stack('+str(self.data)+')'

    def __repr__(self):
        return self.__str__()

==============================

SCREENSHOT:

OUTPUT:


Related Solutions

C++ Given Stack Code, Implements Queue. enqueue, dequeue. Modify to function like Queue. Stack #ifndef STACK_H...
C++ Given Stack Code, Implements Queue. enqueue, dequeue. Modify to function like Queue. Stack #ifndef STACK_H #define STACK_H #include "Node.h" template class Stack { private: Node* top; public: // Constructor Stack() { top = nullptr; } void push(Object ab) { if (top != nullptr) { Node* newNode = new Node(ab, *top); top = newNode; } else { Node* newNode = new Node(ab); top = newNode; } } Object pop() { if (top != nullptr) { Node *returnVal = top; top...
Given C++ Stack Code, Modify the code to work like a Queue.(First in First out) Stack...
Given C++ Stack Code, Modify the code to work like a Queue.(First in First out) Stack #ifndef STACK_H #define STACK_H #include "Node.h" template class Stack { private: Node* top; public: // Constructor Stack() { top = nullptr; } void push(Object ab) { if (top != nullptr) { Node* newNode = new Node(ab, *top); top = newNode; } else { Node* newNode = new Node(ab); top = newNode; } } Object pop() { if (top != nullptr) { Node *returnVal =...
Q1 A- What are stack and queue? What are the differences between stack and queue? B-...
Q1 A- What are stack and queue? What are the differences between stack and queue? B- What is the priority queue? What are the differences between queue and priority queue
Compare the list, stack and queue
Compare the list, stack and queue
A deque (short for double-ended queue, but pronounced “deck”) is an abstract data type that supports...
A deque (short for double-ended queue, but pronounced “deck”) is an abstract data type that supports adding and removing at both the front and back. So, at a bare minimum, a deque has four operations: addFront(), removeFront(), addBack(), removeBack(). Suppose you have a deque D containing the numbers (1, 2, 3, 4, 5, 6, 7, 8), in this order. Suppose further that you have an initially empty queue Q. Give pseudo-code description of a method that uses only D and...
C++ language We are given a Queue data structure that supports standard operations like Enqueue() and...
C++ language We are given a Queue data structure that supports standard operations like Enqueue() and Dequeue(): Enqueue(element): add a new element at the tail of the queue; Dequeue(): delete the element at the head of the queue. Show how to implement a stack using two queues. Analyze the running time of the stack operations: Push and Pop.
Implement a stack using a single queue. In particular, you are given a queue Q that...
Implement a stack using a single queue. In particular, you are given a queue Q that provides the method Q.size() to return its size at any point and the standard methods of queues (i.e, Q.enqueue(x) and Q.dequeue()). The requirement is to use such methods of Q to implement two methods S.push(x) and S.pop() for a stack S. What are the running times of your methods? Kindly answer using python programming
In C++ In this lab we will be creating a stack class and a queue class,...
In C++ In this lab we will be creating a stack class and a queue class, both with a hybrid method combining linked list and arrays in addition to the Stack methods(push, pop, peek, isEmpty, size, print) and Queue methods (enqueue, deque, peek, isEmpty, size, print). DO NOT USE ANY LIBRARY, implement each method from scratch. Both the Stack and Queue classes should be generic classes. Don't forget to comment your code.
Stack Class //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Queue Class public class Stack { private java.util.ArrayList pool = new java.util.ArrayList(); pu
Stack Class //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Queue Class public class Stack { private java.util.ArrayList pool = new java.util.ArrayList(); public Stack() { }    public Stack(int n) { pool.ensureCapacity(n); }    public void clear() { pool.clear(); }    public boolean isEmpty() { return pool.isEmpty(); }    public Object topEl() { if (isEmpty()) throw new java.util.EmptyStackException(); return pool.get(pool.size()-1); }    public Object pop() { if (isEmpty()) throw new java.util.EmptyStackException(); return pool.remove(pool.size()-1); }    public void push(Object el) { pool.add(el); }    public String toString() {...
In java thanks! Design a Stack that is composed ONLY of one or two Queue objects...
In java thanks! Design a Stack that is composed ONLY of one or two Queue objects ergo the ONLY instance variables that exist in this stack are queues. Stack class should contain the following methods: Print Pop Push Top Size isEmpty copy [(2)] Design a Queue that is composed ONLY of two Stacks objects ergo the ONLY instance variables that exist in this queue are stacks. Queue class should contain the following methods:   Print Enqueue Dequeue Front Rear Size isEmpty...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT