Computer Science
Write a program that, depending upon the user's choice, either pushes or pops an element in a Stack. The elements are shifted towards the right so that the top always remains at 0th (zeroth) index.
Answer
def push(stack, element):
stack.insert(0, element)
def pop(stack):
if stack == []:
print("Stack is empty")
else:
print("Popped element:", stack.pop(0))
stack = []
while True:
print("STACK OPERATIONS")
print("1. Push element")
print("2. Pop element")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == '1':
element = input("Enter the element to push: ")
push(stack, element)
elif choice == '2':
pop(stack)
elif choice == '3':
print("Exiting program")
break
else:
print("Invalid choice. Please enter a valid option.")Output
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 3
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 6
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 9
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 12
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 2
Popped element: 12
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 3
Exiting program
Related Questions
Write a program to create a Stack for storing only odd numbers out of all the numbers entered by the user. Display the content of the Stack along with the largest odd number in the Stack. (Hint. Keep popping out the elements from stack and maintain the largest element retrieved so far in a variable. Repeat till Stack is empty)
Write a program that, depending upon the user's choice, either adds or removes an element from a Stack.
Write a program to insert or delete an element from a Queue depending upon the user's choice. The elements are not shifted after insertion or deletion.
Two lists Lname and Lage contain name of person and age of person respectively. A list named Lnameage is empty. Write functions as per details given below:
- Push_na(): It will push the tuple containing pair of name and age from Lname and Lage whose age is above 50.
- Pop_na(): It will remove the last pair of name and age and also print name and age of the removed person. It should also print "underflow" if there is nothing to remove.
For example, the two lists have the following data:
Lname=['Narender', 'Jaya', 'Raju', 'Ramesh', 'Amit', 'Piyush' ]
Lage= [45, 23, 59, 34, 51, 43]After Push_na() the Lnameage Stack contains:
[('Raju', 59), ('Amit', 51)]
The output of first execution of Pop_na() is:
The name removed is Amit
The age of person is 51