Question

In: Computer Science

Write a Python program to (a) create a new empty stack. Then, (b) add items onto...

  • Write a Python program to (a) create a new empty stack. Then, (b) add items onto the stack. (c) Print the stack contents. (d) Remove an item off the stack, and (e) print the removed item. At the end, (f) print the new stack contents:

Solutions

Expert Solution

Program Description:

Following program uses user-defined linked list to represent a stack. A linked list contains connected nodes which can be traversed sequentially. A node or element or item in linked list contains link to the next node. To create a stack using linked list, a new node is always inserted at front or begining of the linked list. The item in stack is inserted at top or removed from the top only. Initially the stack is empty. Items are pushed on the stack using push method. to remove an item from the top of the stack pop method is used. peek method just returns the data or value from the top of the stack, it doesn't remove the item from the top of the stack.

CODE (PLEASE REFER THE SCREENSHOT FOR CODE INDENTATION):

# Program uses user-defined linked list for demonstrating Stack

# Define Node class
class Node:

# Node class constructor
def __init__(self, value):
self.data = value # data part of the Node
self.next = None # pointer to the next Node, initially pointing to None
  

# Define stack class utilizing the Node class
class Stack:
  
# Stack class constructor to initialize
def __init__(self):
# topOfStack is initialized with dummy node
self.topOfStack = None
self.size = 0 # keeps track of the stack size
  
# returns stack as string
def __str__(self):
# take a temporary variable to point to topOfStack
cur = self.topOfStack
  
# out is a string representation of the stack
out = ""
  
# loop until cur is pointing to valid Node
while cur:
# append the data in the out string
out += str(cur.data) + "->"
# move cur to next node in the list
cur = cur.next
  
# return the string representation after removing last occurence of "->"
return out[:-2]
  
# returns True if stack is empty, otherwise False
def isEmpty(self):
return self.size == 0
  
# push a value on stack
def push(self, value):
# create a new node
node = Node(value)
# make node's next to point to topOfStack
node.next = self.topOfStack
# reset the topOfStack to newly created node
self.topOfStack = node
# increment the size of the stack
self.size += 1
  
# return the data of the top node in the stack
def peek(self):
# make sure stack is not empty, if empty raise an exception
if self.isEmpty():
raise Exception("No items in the stack.")
  
# here means stack is not empty, so return the value from top node
return self.topOfStack.data
  
# remove and return value from the stack
def pop(self):
# if stack is empty, cannot delete, raise an exception
if self.isEmpty():
raise Exception("No items in the stack")
# get the topOfStack in a variable to delete/remove
remove = self.topOfStack
# set the topOfStack to next node in the stack
self.topOfStack = self.topOfStack.next
# decrease the size of the stack
self.size -= 1
# return the data part of the removed node
return remove.data

# driver Code to test stack
if __name__ == "__main__":
# a) create an object of Stack class
stack = Stack()
  
# b) push items on stack
stack.push(5)
stack.push(10)
stack.push(15)
stack.push(20)
stack.push(25)
  
# c) display the stack contents
print(f"Stack: {stack}")
  
# d) remove an item from the stack
remove = stack.pop()
  
# e) display removed item data
print(f"Pop: {remove}")
  
# f) display the new stack contents
print(f"Stack: {stack}")

OUTPUT:


Related Solutions

Description of the Assignment: Write a Python program to (a) create a new empty stack. Then,...
Description of the Assignment: Write a Python program to (a) create a new empty stack. Then, (b) add items onto the stack. (c) Print the stack contents. (d) Remove an item off the stack, and (e) print the removed item. At the end, (f) print the new stack contents: Please use the following comments in your python script: # ************************************************* # COP3375 # Student's full name ( <<< your name goes here) # Week 8: Assignment 1 # ************************************************* #...
PYTHON-- create a method that prints items from a stack in a top to bottom order
PYTHON-- create a method that prints items from a stack in a top to bottom order
Exercise 3: Stack Write a program in Java to manipulate a Stack List: 1. Create Stack...
Exercise 3: Stack Write a program in Java to manipulate a Stack List: 1. Create Stack List 2. Display the list 3. Create the function isEmply 4. Count the number of nodes 5. Insert a new node in the Stack List. 6. Delete the node in the Stack List. 7. Call all methods above in main method with the following data: Test Data : Input the number of nodes : 4 Input data for node 1 : 5 Input data...
Develop a python program to create a quiz with limited time and attempts!!! Add comments and...
Develop a python program to create a quiz with limited time and attempts!!! Add comments and screenshot of running the program quiz could be of anything like , what's the sum of 2&2. There should be number of attempts(limited) suppose if the answer is wrong.
Write a Python program to add, multiply and divide any two numbers.
Write a Python program to add, multiply and divide any two numbers.
Using the Stack ADT: Create a program that uses a stack. Your program should ask the...
Using the Stack ADT: Create a program that uses a stack. Your program should ask the user to input a few lines of text and then outputs strings in reverse order of entry. (Optional) Create a similar program that uses a stack. Your new program should ask the user to input a line of text and then it should print out the line of text in reverse. To do this your application should use a stack of Character. In Java...
PYTHON PROGRAM Requirements: 1. Create an empty directory a variable named song_search 2. Repeatedly prompt the...
PYTHON PROGRAM Requirements: 1. Create an empty directory a variable named song_search 2. Repeatedly prompt the user to enter either the title of a song or enter nothing if they have no more songs to enter 3. For each song title entered by the user, split the song title into words by using the split function and splitting on a space. For each word from each song title, ensure the song_search dictionary has a entry with that word as the...
write a python program, please. Create a program that uses the Gettysburg Address as input and...
write a python program, please. Create a program that uses the Gettysburg Address as input and outputs a list of tuples for every two words. For example: [('Four', 'score'),('and', 'seven'), ...].
(C++ program) ***User Interface Write a program that offers an easy way to add items, remove...
(C++ program) ***User Interface Write a program that offers an easy way to add items, remove the last item, look at the last item put in the list. You will write all of the code for processing the stack - do not use any predefined objects in C++.  You decide how the interface will look. A menu driven program is always a good choice. ***Rules for program*** NEVER use break, exit, return, pass, continue or anything to leave a loop (or...
2. Using the Stack ADT: Create a program that uses a stack. Your program should ask...
2. Using the Stack ADT: Create a program that uses a stack. Your program should ask the user to input a few lines of text and then outputs strings in reverse order of entry. In Java please.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT