Data Structure means organization of data.
A data structure has well defined operations, behaviour and properties.
A stack is a linear list, also known as LIFO list.
A list is a mutable sequence of data elements indexed by their position.
Traversing means accessing or visiting or processing each element of any data structure.
push is the term coined for insertion of elements in a Stack list.
Consider the following operations done on Stack:
push(5)
push(8)
pop()
push(2)
push(5)
pop()
pop()
pop()
push(1)
pop()
The output of the above snippet is [], empty list.
In the Stack, if a user tries to remove an element from the empty Stack, it is called underflow of stack.
If the elements "A", "B", "C" and "D" are placed in a queue and are deleted one at a time, the order in which they will be removed will be A, B, C and D.
The process of inserting an element in a queue is called enqueue while deleting an element from a queue is called dequeue.
Single-ended linear structure is a type of queue data structure.
Answer
False
Reason — A single-ended linear structure is a type of stack data structure because a stack is a linear/sequence structure or a list of elements where insertion and deletion can only occur at one end, following the Last-In-First-Out (LIFO) principle.
Reversing a word/line is an application of Stack.
Answer
True
Reason — Reversing a word or a line is an application of the stack data structure. This can be accomplished by pushing each character onto a stack as it is read. When the line is finished, characters are popped off the stack, and they will come off in reverse order.
The insertion and deletion from a Stack takes place only from the 'TOP'.
Answer
True
Reason — A stack is a linear/sequence structure or a list of elements in which insertion and deletion can take place only at one end, i.e., stack's top.
A queue behaves on the basis of LIFO principle.
Answer
False
Reason — A stack behaves based on the Last-In-First-Out (LIFO) principle, meaning that the last element added to the stack is the first one to be removed, while a queue operates according to the First-In-First-Out (FIFO) principle, allowing insertions only at the rear end and deletions only at the front end.
When a queue is implemented with the help of a list, it is termed as a linear queue.
Answer
True
Reason — When a queue is implemented using a list, it is referred to as a linear queue. The syntax is : Queue = list()
or Queue = []
.
Deletion of an element from the queue is termed as pop operation.
Answer
False
Reason — The deletion of an element from the stack is termed as a pop operation, while the deletion of an element from the queue is termed as dequeue.
An element to a queue is added from the front end.
Answer
False
Reason — An element is added to a queue from the rear end, while an element is deleted from the front end of the queue.
Handling the processes of a network printer is the most important application of queues.
Answer
True
Reason — Queues are very useful in a multi-user environment, such as in the case of a network printer, where multiple requests for print operations are generated by several users on the network. If the printer is busy, successive print requests are spooled to the hard disk, where they wait in a queue until the printer becomes available. Hence, handling the processes of a network printer is one of the most important applications of queues.
The append() function inserts an element at the rear end in a queue.
Answer
True
Reason — The built-in list function "append()" inserts an element at the rear end of a queue.
Stack is a linear data structure.
Answer
True
Reason — A stack is a linear data structure following the Last In, First Out (LIFO) principle, where elements are arranged sequentially.
PUSH operation may result in underflow condition.
Answer
False
Reason — When attempting to remove an element (POP operation) from an empty stack, it leads to an underflow condition, resulting in an exception being raised.
The process of inserting an element in Stack is called:
- Create
- Push
- Evaluation
- Pop
Answer
Push
Reason — The process of inserting/adding a new element to the Stack is called PUSH operation.
The process of removing an element from Stack is called:
- Create
- Push
- Evaluation
- Pop
Answer
Pop
Reason — The process of removing/deleting an element from Stack is called Pop operation.
In a Stack, if a user tries to remove an element from an empty Stack, the situation is called:
- Underflow
- Empty collection
- Overflow
- Garbage collection
Answer
Underflow
Reason — In a stack, if a user attempts to remove an element from an empty stack, the situation is called "underflow". This occurs because there are no elements left in the stack to be removed.
Pushing an element into a Stack already having five elements and a Stack of size 5, then the Stack becomes:
- User flow
- Crash
- Underflow
- Overflow
Answer
Overflow
Reason — When pushing an element into a stack that already has five elements and the stack size is limited to 5, the situation is called an "overflow." This is because the stack has reached its maximum capacity, and adding another element would exceed the stack's limit, resulting in an overflow condition.
Entries in a Stack are "ordered". What is the meaning of this statement?
- A collection of Stacks can be sorted.
- Stack entries may be compared with the '<' operation.
- The entries are stored in a linked list.
- There is a Sequential entry that is one by one.
Answer
There is a Sequential entry that is one by one.
Reason — The statement "Entries in a Stack are ordered" means that the entries in a stack are arranged in a sequential order, where each new entry is placed on top of the previous entry. This sequential arrangement follows the Last-In-First-Out (LIFO) principle.
Which of the following applications may use a Stack?
- A parentheses balancing program
- Tracking of local variables at run time
- Compiler Syntax Analyzer
- All of these
Answer
All of these
Reason — Stacks, with their last-in-first-out (LIFO) functionality, are important in parentheses balancing programs, tracking local variables at runtime for efficient memory management, and compiler syntax analyzers for parsing expressions and managing program flow.
Consider the usual algorithm for determining whether a sequence of parentheses is balanced.
The maximum number of parentheses that appear on the Stack AT ANY ONE TIME when the algorithm analyzes: (()(())(())) is:
- 1
- 2
- 3
- 4 or more
Answer
3
Reason — Initially, two opening parentheses '(' are pushed onto the stack. When a closing parenthesis ')' is encountered, it is matched with an open parenthesis on the stack. Subsequently, two new opening parentheses are pushed onto the stack. Then subsequent two closing parentheses are matched with open parentheses on the stack and this process repeats. ensuring that at most, 3 parentheses are on the stack at any given time, maintaining balance.
A linear list of elements in which deletion can be done from one end (front) and insertion can take place only at the other end (rear) is known as a:
- Queue
- Stack
- Tree
- Linked list
Answer
Queue
Reason — A queue is represented as a linear list where insertion (enqueue) can be performed at one end (rear) and deletion (dequeue) can be performed at the other end (front). This characteristic of queues follows the First-In-First-Out (FIFO) principle.
A Queue is a:
- FIFO (First In First Out) list
- LIFO (Last In First Out) list
- Ordered array
- Linear tree
Answer
FIFO (First In First Out) list
Reason — A Queue is a FIFO (First In First Out) list, meaning that the item that is first inserted into the queue is also the first one to be removed.
Assertion (A): The major implementation of using a data structure is to manage the storage of data in the memory efficiently.
Reasoning (R): Data structure refers to the way memory is allocated for holding data using minimum space. It leads to faster data access during the execution of the program.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
Data structures play a crucial role in efficiently managing data in memory. A data structure refers to the method of allocating memory to hold data using minimal space, which ensures faster data access during program execution.
Assertion (A): While working with Stacks, the program should check for Overflow condition before executing push operation and, similarly, check for Underflow before executing pop operation.
Reasoning (R): In Stack, Underflow means there is no element available to remove and Overflow means no further element can be added to it.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
To use a Stack efficiently, it's crucial to check its status by examining overflow conditions before executing a push operation and underflow conditions before executing a pop operation. In a stack, underflow occurs when there are no elements available to remove (e.g., trying to pop from an empty stack), while overflow happens when there's no more space to add elements (e.g., trying to push onto a full stack).
Assertion (A): Stack is a memory structure that works on the principle of FIFO (First In, First Out).
Reasoning (R): Stack is implemented using list and allows to add an element using append() method.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
A is false but R is true.
Explanation
A stack is a memory structure that works on the principle of LIFO (Last In, First Out), meaning that the last element added to the stack is the first one to be removed. In Python, a stack can be implemented using a list data structure, and the "append()" method is used to add elements to the top of the stack.
Assertion (A): A Stack is a linear data structure that stores the elements in First In, First Out order.
Reasoning (R): In Stack, a new element is added and removed from one end only.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
A is false but R is true.
Explanation
A stack is a linear data structure that stores elements in LIFO (Last In, First Out) order, where the last element added to the stack is the first one to be removed. In a stack, a new element is added and removed from only one end, which is the top of the stack.
Assertion (A): Stack and Queue are linear data structures.
Reasoning (R): List, tuples and dictionaries are Python built-in linear data structures.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
A is true but R is false.
Explanation
Stacks and queues are linear data structures because they organize data elements in a linear order, allowing elements to be accessed in a sequential manner. Python provides built-in data structures like lists, tuples, and dictionaries. Lists and tuples are examples of linear data structures as they store elements in a specific linear order, while dictionaries are non-linear data structures because they do not maintain a specific linear order, and elements are accessed based on their keys rather than indices.
Assertion (A): An element in a Stack is removed from its Top.
Reasoning (R): The process of removing an element from a Stack is called pop.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
An element in a stack is removed from its top. The stack follows the Last-In-First-Out (LIFO) approach, where the last element added (the top element) is the first one to be removed. The process of removing an element from a stack is called pop.
Assertion (A): An error gets displayed when you try to delete an element from an empty Stack.
Reasoning (R): Inserting an element when the Stack is full is termed as Underflow.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
A is true but R is false.
Explanation
When we attempt to delete an element from an empty stack, it results in an error known as an underflow error. This occurs because the stack is empty, and there's no element to remove. On the other hand, inserting an element when the stack is full is termed as an overflow condition.
What is Stack? Why is it called LIFO data structure?
Answer
A stack is a linear/sequence structure or a list of elements in which insertion and deletion can take place only at one end, i.e., Stack's top. Because of this, Stack is called LIFO data structure. The Last-In-First-Out (LIFO) means the element inserted last would be the first to be deleted or accessed from the stack.
List two ways to implement Stack.
Answer
The two ways to implement Stack are as follows :
Stack = list()
Stack = []
Write applications of Stack.
Answer
The applications of Stack include:
- Reversing a Word/Line — This can be accomplished by pushing each character on to a Stack as it is read. When the line is finished, characters are popped off the Stack and they will come off in the reverse order.
- Evaluation of Arithmetic Expressions — Stack is used to evaluate these arithmetic expressions on the basis of operator precedence.
- Processing Function Calls — The compilers use Stacks to store the previous state of a program when a function is called or during recursion.
- Backtracking — Backtracking is a form of recursion which involves choosing only one option out of the possibilities. Backtracking is used in a large number of puzzles like Sudoku and in optimization problems such as Knapsack.
- Undo Mechanism in Text Editors — This operation is accomplished by keeping all text changes in a Stack.
Can a Stack be used to convert a decimal number into a binary number?
Answer
Yes, a Stack can be used to convert a decimal number into a binary number.
Write an algorithm to push an element into the Stack.
Answer
An algorithm to push an element into the Stack is as follows:
- START
- Stack = list() or Stack = [] #Initialize a Stack using list
- element = input("Enter the value to be added in the stack:")
- Stack.append(element) #Adding element into list
- END
Write an algorithm to pop an element from the Stack.
Answer
An algorithm to pop an element from the Stack is as follows:
- START
- St_len = len(Stack) #Count the total number of elements in the Stack and checks whether the Stack is empty or not
- if St_len == []: or if not Stack: or If not len(Stack):
print("Stack is empty")
go to step 6 - element = Stack.pop() #Removing last element from top of the Stack
- print(element)
- END
Write an interactive menu-driven program implementing Stack using list. The list is storing numeric data.
def push(num):
h = int(input("Enter a number: "))
num.append(h)
def pop(num):
if len(num) == 0:
print("No number to delete")
else:
print("Deleted number is:", num.pop())
def display(num):
print(num)
num = []
while True:
print("1. Add number")
print("2. Delete number")
print("3. Display numbers")
print("4. Exit")
op = int(input("Enter the Choice: "))
if op == 1:
push(num)
elif op == 2:
pop(num)
elif op == 3:
display(num)
elif op == 4:
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 1
Enter a number: 2
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 1
Enter a number: 4
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 1
Enter a number: 6
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 1
Enter a number: 8
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 3
[2, 4, 6, 8]
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 2
Deleted number is: 8
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 3
[2, 4, 6]
1. Add number
2. Delete number
3. Display numbers
4. Exit
Enter the Choice: 4
Exiting program.
Write an interactive menu-driven program to implement Stack using list. The list contains the names of students.
def push(student):
h = input("Enter a name: ")
student.append(h)
def pop(student):
if len(student) == 0:
print("No name to delete")
else:
print("Deleted name is:", student.pop())
def display(student):
print(student)
student = []
while True:
print("1. Add name")
print("2. Delete name")
print("3. Display names")
print("4. Exit")
op = int(input("Enter the Choice: "))
if op == 1:
push(student)
elif op == 2:
pop(student)
elif op == 3:
display(student)
elif op == 4:
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 1
Enter a name: Prajwal
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 1
Enter a name: Amrita
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 1
Enter a name: Kavya
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 1
Enter a name: Drishti
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 3
['Prajwal', 'Amrita', 'Kavya', 'Drishti']
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 2
Deleted name is: Drishti
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 3
['Prajwal', 'Amrita', 'Kavya']
1. Add name
2. Delete name
3. Display names
4. Exit
Enter the Choice: 4
Exiting program.
How does FIFO describe queue?
Answer
FIFO, First In First Out, defines a queue because in a queue, elements are retrieved from one end (called the front end) and inserted at another end (rear end). Thus, at any time, in a queue, retrieval gets the oldest element, while always adding to the rear of the queue. Thus, items are processed in first-in, first-out (FIFO) order.
Write a menu-driven Python program using queue to implement movement of shuttlecock in its box.
queue = []
def display_queue():
if not queue:
print("Queue is empty")
else:
print("Current queue:", queue)
def enqueue(item):
queue.append(item)
def dequeue():
if queue:
removed = queue.pop(0)
print("Removed", removed, "from the queue")
else:
print("Queue is empty, cannot remove")
while True:
print("\nMENU:")
print("1. Add movement to the queue")
print("2. Remove movement from the queue")
print("3. Display current queue")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
movement = input("Enter the movement (up/down): ")
enqueue(movement)
print("Added", movement, "to the queue")
elif choice == '2':
dequeue()
elif choice == '3':
display_queue()
elif choice == '4':
print("Exiting program...")
break
else:
print("Invalid choice, please try again")
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 1
Enter the movement (up/down): up
Added up to the queue
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 1
Enter the movement (up/down): down
Added down to the queue
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 3
Current queue: ['up', 'down']
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 2
Removed up from the queue
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 3
Current queue: ['down']
MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 4
Exiting program...
Give the necessary declaration of a list implemented Stack containing float type numbers. Also, write a user-defined function to pop a number from this Stack.
# Declaration for list implemented stack
Stack = list()
#Function body to pop a number from the stack
def pop_element(Stack):
if not Stack:
print("Stack is empty")
else:
Num = Stack.pop()
print("Value deleted from stack is", Num)
Stack = [1.5, 2.7, 3.2, 4.9]
print("Initial Stack:", Stack)
pop_element(Stack)
print("Stack after pop operation:", Stack)
Initial Stack: [1.5, 2.7, 3.2, 4.9]
Value deleted from stack is 4.9
Stack after pop operation: [1.5, 2.7, 3.2]
A linear Stack called Directory contains the following information as contacts:
— Pin code of city
— Name of city
Write add(Directory) and delete(Directory) methods in Python to add and remove contacts using append() and pop() operations in Stack.
def add(Directory):
pincode = int(input("Enter pincode of city: "))
cityname = input("Enter the city name: ")
contact = [pincode, cityname]
Directory.append(contact)
def delete(Directory):
if (Directory == []):
print("Directory is empty")
else:
print("Deleted contact:", Directory.pop())
Directory = []
add(Directory)
add(Directory)
print("Initial Directory Stack:", Directory)
delete(Directory)
print("Directory Stack after deletion:", Directory)
Enter pincode of city: 586789
Enter the city name: Bangalore
Enter pincode of city: 567890
Enter the city name: Mysore
Initial Directory Stack: [[586789, 'Bangalore'], [567890, 'Mysore']]
Deleted contact: [567890, 'Mysore']
Directory Stack after deletion: [[586789, 'Bangalore']]
Write add(Books) and delete(Books) methods in Python to add Books and Remove Books considering them to act as append() and pop() operations in Stack.
def add(Books):
bookname = input("Enter the book name: ")
Books.append(bookname)
def delete(Books):
if Books == []:
print("Books is empty")
else:
print("Deleted Book", Books.pop())
Books = []
add(Books)
add(Books)
add(Books)
print("Initial Books Stack:", Books)
delete(Books)
print("Books Stack after deletion:", Books)
Enter the book name: Three thousand stitches
Enter the book name: Wings of fire
Enter the book name: Ignited minds
Initial Books Stack: ['Three thousand stitches', 'Wings of fire', 'Ignited minds']
Deleted Book Ignited minds
Books Stack after deletion: ['Three thousand stitches', 'Wings of fire']
Write AddClient(Client) and DeleteClient(Client) methods in Python to add a new client and delete a client from a list client name, considering them to act as insert and delete operations of the Queue data structure.
def AddClient(client):
client_name = input("Enter client name: ")
client.append(client_name)
def DeleteClient(client):
if client == []:
print("Queue is empty")
else:
print("Deleted client:", client.pop(0))
client = []
AddClient(client)
AddClient(client)
AddClient(client)
print("Initial Client Queue:", client)
DeleteClient(client)
print("Client Queue after deletion:", client)
Enter client name: Rahul
Enter client name: Tanvi
Enter client name: Vidya
Initial Client Queue: ['Rahul', 'Tanvi', 'Vidya']
Deleted client: Rahul
Client Queue after deletion: ['Tanvi', 'Vidya']
Write Addscore(Game) and Delscore(Game) methods in Python to add new Score in the list of score in a game and remove a score from a list of score of a game considering these methods to act as PUSH and POP operation of data structure Stack.
def Addscore(Game):
score = int(input("Enter the score to add: "))
Game.append(score)
def Delscore(Game):
if Game == []:
print("Game's score list is empty")
else:
print("Deleted score:", Game.pop())
Game = []
Addscore(Game)
Addscore(Game)
Addscore(Game)
print("Initial Game Stack:", Game)
Delscore(Game)
print("Game Stack after deletion:", Game)
Enter the score to add: 10
Enter the score to add: 15
Enter the score to add: 20
Initial Game Stack: [10, 15, 20]
Deleted score: 20
Game Stack after deletion: [10, 15]
Write a Python program to sort a Stack in ascending order without using an additional Stack.
def pushSorted(s, num):
if len(s) == 0 or num > s[-1]:
s.append(num)
return
else:
t = s.pop()
pushSorted(s, num)
s.append(t)
def doSort(s):
if len(s) != 0:
t = s.pop()
doSort(s)
pushSorted(s, t)
s = []
s.append(12)
s.append(5)
s.append(-3)
s.append(4)
s.append(10)
print("Stack before sorting: ")
print(s)
doSort(s)
print("\nStack after sorting: ")
print(s)
Stack before sorting:
[12, 5, -3, 4, 10]
Stack after sorting:
[-3, 4, 5, 10, 12]
A Stack STK and Queue QUE is being maintained. Their maximum size is the same:
(i) check whether they have the same size, i.e., have the same number of elements.
(ii) check for equality of Stack and Queue, i.e.,
- Retrieve an element from the Stack and one element from the Queue.
- Compare the two.
- Stop and report if elements are different.
def is_empty(stack_or_queue):
return len(stack_or_queue) == 0
def size(stack_or_queue):
return len(stack_or_queue)
def check_size_equality(stack, queue):
return size(stack) == size(queue)
def check_element_equality(stack, queue):
if check_size_equality(stack, queue) == False:
print("The size of stack and Queue is not equal.")
return False
while not is_empty(stack) and not is_empty(queue):
stack_element = stack.pop()
queue_element = queue.pop(0)
if stack_element != queue_element:
return False
return True
STK = [1, 2, 3]
QUE = [3, 2, 1]
print("Size Equality Check:", check_size_equality(STK, QUE))
print("Element Equality Check:", check_element_equality(STK, QUE))
Size Equality Check: True
Element Equality Check: True
Write an algorithm to insert element into Stack as a list.
Answer
An algorithm to insert element into Stack as a list is as follows:
- START
- Stack = list() or Stack = [] #Initialize a Stack using list
- element = input("Enter the value to be added in the stack: ")
- Stack.append(element) #Adding element into list
- END
Write an algorithm to insert element into Queue as a list.
Answer
An algorithm to insert element into Queue as a list is as follows:
- START
- Queue = list() or Queue = [] #Initialize a Queue using list
- element = input("Enter the element to be added to the Queue: ")
- Queue.append(element) #Adding element into the list Queue
- STOP
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.)
def push(stack, item):
stack.append(item)
def pop(stack):
if stack == []:
return None
return stack.pop()
def oddStack(num):
if num % 2 == 1:
push(stack, num)
def GetLargest(stack):
elem = pop(stack)
large = elem
while elem != None:
if large < elem:
large = elem
elem = pop(stack)
return large
n = int(input("How many numbers?"))
stack = []
for i in range(n):
number = int(input("Enter number:"))
oddStack(number)
print("Stack created is", stack)
bigNum = GetLargest(stack)
print("Largest number in stack", bigNum)
How many numbers?8
Enter number:1
Enter number:2
Enter number:3
Enter number:4
Enter number:5
Enter number:6
Enter number:7
Enter number:8
Stack created is [1, 3, 5, 7]
Largest number in stack 7
Write a program that, depending upon the user's choice, either adds or removes an element from a Stack.
def add(stack):
h = input("Enter element: ")
stack.append(h)
def remove(stack):
if len(stack) == 0:
print("No element to delete")
else:
print("Deleted element is:", stack.pop())
stack = []
while True:
print("1. Add element")
print("2. Delete element")
print("3. Exit")
op = int(input("Enter the Choice: "))
if op == 1:
add(stack)
elif op == 2:
remove(stack)
elif op == 3:
print("Exiting program.")
break
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 11
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 33
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 44
1. Add element
2. Delete element
3. Exit
Enter the Choice: 2
Deleted element is: 44
1. Add element
2. Delete element
3. Exit
Enter the Choice: 1
Enter element: 55
1. Add element
2. Delete element
3. Exit
Enter the Choice: 2
Deleted element is: 55
1. Add element
2. Delete element
3. Exit
Enter the Choice: 3
Exiting program.
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.
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.")
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
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.
def enqueue(queue):
element = input("Enter the element to enqueue: ")
queue.append(element)
def dequeue(queue):
if queue:
removed_element = queue.pop(0)
print("Dequeued element:", removed_element)
else:
print("Queue is empty")
queue = []
while True:
print("QUEUE OPERATIONS")
print("1. Enqueue element")
print("2. Dequeue element")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == '1':
enqueue(queue)
elif choice == '2':
dequeue(queue)
elif choice == '3':
print("Exiting program")
break
else:
print("Invalid choice. Please enter a valid option.")
QUEUE OPERATIONS
1. Enqueue element
2. Dequeue element
3. Exit
Enter your choice (1-3): 1
Enter the element to enqueue: 4
QUEUE OPERATIONS
1. Enqueue element
2. Dequeue element
3. Exit
Enter your choice (1-3): 1
Enter the element to enqueue: 8
QUEUE OPERATIONS
1. Enqueue element
2. Dequeue element
3. Exit
Enter your choice (1-3): 1
Enter the element to enqueue: 12
QUEUE OPERATIONS
1. Enqueue element
2. Dequeue element
3. Exit
Enter your choice (1-3): 2
Dequeued element: 4
QUEUE OPERATIONS
1. Enqueue element
2. Dequeue element
3. Exit
Enter your choice (1-3): 3
Exiting program
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
def Push_na(Lname, Lage, Lnameage):
for i in range(len(Lname)):
if Lage[i] > 50:
Lnameage.append((Lname[i], Lage[i]))
def Pop_na(Lnameage):
if Lnameage:
removed_name, removed_age = Lnameage.pop()
print("The name removed is", removed_name)
print("The age of person is", removed_age)
else:
print("Underflow - Nothing to remove")
Lname = ['Narender', 'Jaya', 'Raju', 'Ramesh', 'Amit', 'Piyush']
Lage = [45, 23, 59, 34, 51, 43]
Lnameage = []
Push_na(Lname, Lage, Lnameage)
print("After Push_na() the Lnameage Stack contains:")
print(Lnameage)
print("\nThe output of first execution of Pop_na() is:")
Pop_na(Lnameage)
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
A dictionary stu contains rollno and marks of students. Two empty lists stack_roll and stack_mark will be used as Stack. Two functions Push_stu() and Pop_stu() are defined and perform the following operation:
- Push_stu(): It reads dictionary stu and adds keys into stack_roll and values into stack_marks for all students who secured more than 60 marks.
- Pop_stu(): It removes last rollno and marks from both list and prints "underflow" if there is nothing to remove.
For example,
stu={ 1 : 56, 2 : 45, 3 : 78, 4 : 65, 5 : 35, 6 : 90 }
Values of stack_roll and stack_mark after push_stu() function:
[3, 4, 6] and {78, 65, 90}
def Push_stu(stu, stack_roll, stack_mark):
for rollno, marks in stu.items():
if marks > 60:
stack_roll.append(rollno)
stack_mark.append(marks)
def Pop_stu(stack_roll, stack_mark):
if stack_roll and stack_mark:
print("Removed rollno:", stack_roll.pop())
print("Removed marks:", stack_mark.pop())
else:
print("Underflow - Nothing to remove")
stu = {1: 56, 2: 45, 3: 78, 4: 65, 5: 35, 6: 90}
stack_roll = []
stack_mark = []
Push_stu(stu, stack_roll, stack_mark)
print("Values of stack_roll and stack_mark after Push_stu() function:")
print(stack_roll, stack_mark)
print("\nThe output of first execution of Pop_stu() is:")
Pop_stu(stack_roll, stack_mark)
Values of stack_roll and stack_mark after Push_stu() function:
[3, 4, 6] [78, 65, 90]
The output of first execution of Pop_stu() is:
Removed rollno: 6
Removed marks: 90
Write AddCustomer(Customer) and DeleteCustomer(Customer) methods in Python to add a new Customer and delete a Customer from a List of CustomerNames, considering them to act as push and pop operations of the Stack data structure.
def AddCustomer(Customer):
Customer_name = input("Enter the customer name: ")
Customer.append(Customer_name)
def DeleteCustomer(Customer):
if Customer == []:
print("Customer list is empty")
else:
print("Deleted Customer name:", Customer.pop())
Customer = []
AddCustomer(Customer)
AddCustomer(Customer)
AddCustomer(Customer)
print("Initial Customer Stack:", Customer)
DeleteCustomer(Customer)
print("Customer Stack after deletion:", Customer)
Enter the customer name: Anusha
Enter the customer name: Sandeep
Enter the customer name: Prithvi
Initial Customer Stack: ['Anusha', 'Sandeep', 'Prithvi']
Deleted Customer name: Prithvi
Customer Stack after deletion: ['Anusha', 'Sandeep']