Introduction to Programming using Python 1st Edition

Published by Pearson
ISBN 10: 0132747189
ISBN 13: 978-0-13274-718-9

Chapter 12 - Inheritance and Polymorphism - Programming Exercises - Page 436: 12.16

Answer

code

Work Step by Step

# 12.16 (Implement Stack using inheritance) In Listing 12.13, the Stack class is # implemented using composition. Define a new Stack class using inheritance # that extends list. # Draw UML diagrams of the new class. Implement it. Write a test program that # prompts the user to enter five strings and displays them in reverse order. class Stack(list): def __init__(self, size): super().__init__() self.size = size self.counter = -1 def push(self, val): if self.counter < self.size: self.append(val) self.counter += 1 else: print("Stack is full!") def pop(self): if self.counter >= 0: res = self[self.counter] self[:] = self[:self.counter] self.counter -= 1 return res else: return "Stack is empty" def isEmpty(self): return self.counter < 0 def peek(self): if not self.isEmpty(): return self[self.counter] else: return "Stack is empty" s = Stack(5) s.push(10) s.push(20) s.push(30) s.push(40) s.push(50) print(s.peek()) print(s.pop()) print(s.pop()) print(s.pop()) print(s.pop()) print(s.pop()) print(s.pop()) print(s.pop()) print(s.peek())
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.