Question

In: Computer Science

All code should be in Python 3. Implement the Stack Class, using the push, pop, str,...

All code should be in Python 3. Implement the Stack Class, using the push, pop, str, init methods, and the insurance variable 'list'.

Solutions

Expert Solution

We can't use list as a variable a it is a predefined function in python. So, it will show error.

---------------------Program-----------------

import random

class Stack():

    # constructor

    def __init__(self):

   

        self._elements = []

        self._count = 0

    # push elt into the stack

    def push(self, elt):

   

        self._elements.append(elt)

       

        self._count += 1

    # pop top most element from the stack

    def pop(self):

   

        # if stack is empty

        if self.is_empty():

            return 'Stack Empty!'

       

        # decrement the count of elements in the stack

        self._count -= 1

       

        # return the top most element in th list

        return self._elements.pop()

    # get the top most element from the stack

    def top(self):

   

        if self.is_empty():

            return 'Stack Empty!'

        else:

            return self._elements[self._count - 1]

       

    # return true if the stack is empty, false otherwise

    def is_empty(self):

   

        return self._count == 0

    # get the size of stack

    def size(self):

   

        return self._count

    def __str__(self):

       

        # if stack is empty

        if self.is_empty() == True:

            return '()'

       

        ans = '('

       

        for i in range(0, self._count - 1):

       

            ans += str(self._elements[i]) + ', '

           

        ans += str(self._elements[self._count - 1]) + ')'

       

        return ans

    def __repr__(self):

   

        if self.is_empty() == True:

            return 'Stack List ()'

   

        ans = 'Stack List ('

        

        for i in range(0, self._count - 1):

       

            ans += str(self._elements[i]) + ', '

           

        ans += str(self._elements[self._count - 1]) + ')'

       

       return ans

       

s = Stack()

s.push(random.randint(-100, 100))

s.push(random.randint(-100, 100))

s.push(random.randint(-100, 100))

s.push(random.randint(-100, 100))

print(s)

print(s.__repr__())

print('\nTop Most Element :', s.top())

print('\nPopping Stack ...')

while not s.is_empty():

    print(s.pop())

Sample Output


Related Solutions

Reverse the contents of a stack using only stack operations [ push() and pop()  ]. Using the...
Reverse the contents of a stack using only stack operations [ push() and pop()  ]. Using the java and give the explanation
Please code in C /* Implements functions that operate on Stack 1. PUSH 2. POP 3....
Please code in C /* Implements functions that operate on Stack 1. PUSH 2. POP 3. isEmpty 4. PEEK 5. Size */ #include <stdio.h> #define CAPACITY 1000 //Two stacks .. for each stack we need // 1. An Array that can hold capacity of elements // 2. A top initialzied to -1 (signifying that the stak is empty at the start) //NOTE : THESE STACKS ARE OF TYPE CHAR :( ... so you need to FIX IT!!!! to int and...
Write a code to implement a python stack class using linked list. use these operations isEmpty...
Write a code to implement a python stack class using linked list. use these operations isEmpty   • push. • pop.   • peek. • size Time and compare the performances ( this is optional but I would appreciate it)
3.1.1 Implement the pop() operation in the stack (1 mark) Implement a stack class named Stack2540Array...
3.1.1 Implement the pop() operation in the stack (1 mark) Implement a stack class named Stack2540Array using array. The starter code is as follows. The instance variables and most operations are provided. You need to implement the pop operation. Make sure that your program checks whether the stack is empty in the pop operation. The implementation can be found in the book and in our lecture slides. import java . io .*; import java . util .*; public class Stack2540Array...
Using Python list tools, create the standard stack (push, pop) and queue (enqueue, dequeue) operations Counting...
Using Python list tools, create the standard stack (push, pop) and queue (enqueue, dequeue) operations Counting Letter Challenge: Create a function that... Takes in a string as parameter Counts how often each letter appears in the string Returns a dictionary with the counts BONUS: make it so lowercase and uppercase letter count for the same letter
LDR, POP, STR, PUSH, MOV What is the difference between them?
LDR, POP, STR, PUSH, MOV What is the difference between them?
# ArrayStack # TODO: push and pop using array stack with doubling technique. import numpy as...
# ArrayStack # TODO: push and pop using array stack with doubling technique. import numpy as np from future import print_function # Definisi class ArrayStack class ArrayStack(object): def __init__(self): self.data = np.zeros(20, dtype=np.int) self.count = 0 def isEmpty(self): pass # ubah saya def size(self): pass # ubah saya def push(self, obj): pass # ubah saya def pop(self): pass # ubah saya #-------------------------- # End of class if __name__ == "__main__": stack = ArrayStack() randn = np.random.permutation(1000) for i in range(1000):...
This is my current code for a question that asks: "Implement the stack methods push(x) and...
This is my current code for a question that asks: "Implement the stack methods push(x) and pop() using two queues". It works well, other than I want it to work for data of type T, not just Int's. (EXCUSE THE INDENTING... CHEGG POSTING DOESNT ALLOW PROPER CODE TO BE UPLOADED... JUST COPY PASTE IT INTO ECLIPSE IDE, HIGHLIGHT ALL CODE, PRESS COMMAND+SHIFT+F AND SHOULD AUTO-FORMAT) MY QUESTION: How could one modify this code in order to take data of type...
how could I implement an intStack class that has only a push and pop method? in...
how could I implement an intStack class that has only a push and pop method? in java of course.
Python - Please include running time of push(), pop(), and top() methods and tester code for...
Python - Please include running time of push(), pop(), and top() methods and tester code for all methods. Design a stack ADT using a single queue as an instance variable, and only constant additional local memory within the method bodies. What is the running time of the push(), pop(), and top() methods for your design? Implement your modified stack ADT in Python, including tester code to test all its methods.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT