0% found this document useful (0 votes)
8 views17 pages

Class 12 CS Python Stack Practice Questions

The document contains a series of Python programming exercises focused on stack operations, including pushing and popping elements based on specific conditions. It covers various scenarios such as managing player names, city names, employee codes, student records, and course details using stacks. Each exercise includes a description, example usage, and the corresponding Python code implementation.

Uploaded by

rvidyamsc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views17 pages

Class 12 CS Python Stack Practice Questions

The document contains a series of Python programming exercises focused on stack operations, including pushing and popping elements based on specific conditions. It covers various scenarios such as managing player names, city names, employee codes, student records, and course details using stacks. Each exercise includes a description, example usage, and the corresponding Python code implementation.

Uploaded by

rvidyamsc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Class 12 CS Python Stack Practice Questions

1. Suppose L = [3, 4, 5, 20, 4, 5], What is L after [Link]()?

1. [3,4,5,20,4]

2. [3,5,20,4,5]

3. [3,5,20,5]

4. Error

2. A School has created a dictionary containing top players and their runs as key value pairs of cricket team. Write a
program with separate user defined functions to perform the following operations:
(a) Push the name of the players(Keys) of the dictionary into a stack, where the corresponding runs (value) is greater than
49.
(b) Pop and display the content of the stack.
For Example
If dictionary has the following values:
Data={'Rohan':40, 'Rihaan':55, 'Tejas':80,'Ajay':90}
The output should be:
Ajay
Tejas
Rihaan

ANSWER:

class PlayerStack:
def __init__(self):
[Link] = []

def Push_Players(self, player_data):


# Push players' names whose runs are greater than 49
for player, runs in player_data.items():
if runs > 49:
[Link](player)

def Pop_Players(self):
# Pop and display the content of the stack
if not [Link]:
print("Underflow")
else:
while [Link]:
print([Link]())

# Example usage
data = {
'Rohan': 40,
'Rihaan': 55,
'Tejas': 80,
'Ajay': 90
}

player_stack = PlayerStack()
player_stack.Push_Players(data)
player_stack.Pop_Players()
3. Write a program in Python, with separate user defined functions to perform the following operations on Stack 'City'.
(a) - Push the pin code and name of the city in the stack 'City'
(b) - Display the latest added element in the stack 'City'

ANSWER:

class CityStack:
def __init__(self):
[Link] = []

def push(self, pin_code, city_name):


"""Push the pin code and city name onto the stack."""
[Link]((pin_code, city_name))
print(f"Added: Pin Code: {pin_code}, City: {city_name}")

def display_latest(self):
"""Display the latest added element in the stack."""
if [Link]:
latest = [Link][-1]
print(f"Latest Added: Pin Code: {latest[0]}, City: {latest[1]}")
else:
print("The stack is empty.")

# Example usage
if __name__ == "__main__":
city_stack = CityStack()

# Push some cities onto the stack


city_stack.push("110001", "New Delhi")
city_stack.push("400001", "Mumbai")
city_stack.push("600001", "Chennai")

# Display the latest added city


city_stack.display_latest()

4. In a stack, if a user tries to remove an element from empty stack, it is called --------

1. Empty Collection 2. Overflow 3. Underflow 4. None of these

5 - Priyanka has created a dictionary 'emeployee_data' containing EmpCode and Salary as key value pairs for 5
Employees of Cyber Intratech. Write a program, With separate user defined function, as mentioned below, to perform the
following operations:
(a) push_emp(): Push all those EmpCode, where the Salary is less than 25000, from the dictionary into a stack 'stk_emp'
(b) pop_emp(): Remove all the elements from the stack, one at a time, in a Last-In-First-Out(LIFO) manner and displays
them. It also displays 'Stack is empty' once all the element have been removed.
For Example:
If the sample content of the dictionary is as follows:
{'E001':15000,'E002':27000,'E003':30000,'E004':15000,'E005':19000}, then the stack 'stk_emp' will contain EmpCode
E001, E004, E005 after push_emp(). pop_emp() will pop and display employee record in LIFO fashion and display 'Stack
is empty' at last.
ANSWER:

# Define the employee data dictionary


employee_data = {
'E001': 15000,
'E002': 27000,
'E003': 30000,
'E004': 15000,
'E005': 19000
}

# Stack to hold employee codes


stk_emp = []

def push_emp(employee_data):
"""Push EmpCode into the stack where Salary is less than 25000."""
for emp_code, salary in employee_data.items():
if salary < 25000:
stk_emp.append(emp_code)
print("Employee codes pushed to stack:", stk_emp)

def pop_emp():
"""Pop all elements from the stack in LIFO manner."""
if not stk_emp:
print("Stack is empty")
return

print("Popping employee codes from stack:")


while stk_emp:
emp_code = stk_emp.pop()
print(emp_code)

print("Stack is empty")

# Main execution
push_emp(employee_data) # Push employees with salary < 25000
pop_emp() # Pop employees in LIFO order

6 - A school stores records of Class XII students using a list that contains multiple lists as its elements. The structure of
each such element is [Student_Name, Marks, MainSubject]. Crate user-defined functions to perform the operations as
mentioned below:
(a) Push_student(): To push the Student_Name and Marks of all those students, who have Science as MainSubject, into a
Stack StudentInfo
(b) Pop_student(): To delete all items (one at a time) from the stack StudentInfo in LIFO order and display them. Also
display "Empty Stack" when there are no items remaining in the stack.
For Example:
If the stored information is:
[['Akansha',98,"Mathematics"],["Priti",96,"Science"],["Garima",99,"Science"],["Ayushi",78,"English"]]
The stack should contain:
["Garima",99]
["Priti",96]
The output should be:
["Garima",99]
["Priti",96]
Empty Stack
ANSWER:

class StudentStack:
def __init__(self):
[Link] = []

def push_student(self, student_records):


# Push students with Science as MainSubject onto the stack
for record in student_records:
if record[2] == "Science":
[Link]([record[0], record[1]])

def pop_student(self):
# Pop students from the stack in LIFO order and display them
if not [Link]:
print("Empty Stack")
else:
while [Link]:
student_info = [Link]()
print(student_info)

# Example usage
if __name__ == "__main__":
student_records = [
['Akansha', 98, "Mathematics"],
["Priti", 96, "Science"],
["Garima", 99, "Science"],
["Ayushi", 78, "English"]
]

student_stack = StudentStack()
student_stack.push_student(student_records)
student_stack.pop_student()

7 - "Stack is a linear data structure which follows a particular order in which the operations are performed"
What is the order in which the operations ae performed in a Stack?
Name the List method/function available in Python which is used to remove the last element from a list implemented stack.
Also write an example using Python statements for removing the last element of the list.

ANSWER:

In a stack, the order in which operations are performed follows the Last In, First Out (LIFO) principle.
This means that the last element added to the stack is the first one to be removed.

In Python, the list method used to remove the last element from a list (which can be used to implement
a stack) is pop(). This method removes and returns the last item from the list.
8 - Write a program in Python to input 5 words and push them one by one into a list named All.
The program should then use the function PushNV() to create a stack of words in the list NoVowel so that it store only
those words which do not have any vowel present in it, from the list All.
Thereafter, pop each word from the list NoVowel and display the popped word. When the stack is empty display the
message 'EmptyStack'.
For Example:
If the words accepted and pushed into the list All are
['DRY','LIKE','RHYTHM','WORK','GYM']
Then the stack NoVowel should store
['DRY','RHYTHM','GYM']
And the output should be displayed as
GYM RHYTHM DRY EmptyStack

ANSWER:

def PushNV(all_words):
no_vowel = []
vowels = 'AEIOUaeiou'

for word in all_words:


if not any(char in vowels for char in word):
no_vowel.append(word)

return no_vowel

def main():
All = []

# Input 5 words
for _ in range(5):
word = input("Enter a word: ")
[Link](word)

# Create stack of words without vowels


NoVowel = PushNV(All)

# Pop each word from the stack and display


while NoVowel:
print([Link]())

# Display message when stack is empty


print("EmptyStack")

if __name__ == "__main__":
main()

9 - Write a program in Python to input 5 integers into a list named NUM.


The program should then use the function Push3_5() to push all those integers which are divisible by 3 or divisible by 5
from the list NUM into the stack of the list Only3_5.
Thereafter pop each integer from the list Only3_5 and display the popped value. When the list is empty, display the
message "StackEmpty".
For Example:
If the integers input into the list NUM are:
[10,6,14,18,30]
Then the stack Only3_5 should store
[10,6,18,30]
And the output should be displayed as
30 18 6 10 StackEmpty

ANSWER:

def Push(num_list):
stack = []
for num in num_list:
if num % 3 == 0 or num % 5 == 0:
[Link](num)
return stack

def main():
# Input 5 integers into the list NUM
NUM = []
for i in range(5):
while True:
try:
value = int(input(f"Enter integer {i + 1}: "))
[Link](value)
break
except ValueError:
print("Please enter a valid integer.")

# Push integers divisible by 3 or 5 into stack


stack = Push(NUM)

# Pop each integer from stack and display the popped value
while stack:
print([Link](), end=' ')

# Display message when stack is empty


print("StackEmpty")

if __name__ == "__main__":
main()

10 - Differentiate between Push and Pop operations in the context of stacks.

ANSWER:

Push Operation
 Definition: The Push operation adds an element to the top of the stack.
 Functionality: When an element is pushed onto the stack, it becomes the new top element. The previous top
element is now below the newly added element.
 Use Case: This operation is used when you want to store or save data temporarily. For example, when you
need to keep track of function calls in programming (call stack), or when you are implementing algorithms that
require backtracking.
 Complexity: The time complexity of the Push operation is O(1), meaning it takes constant time regardless of
the size of the stack.

Pop Operation
 Definition: The Pop operation removes the top element from the stack.
 Functionality: When an element is popped from the stack, the top element is removed, and the next element
below it becomes the new top element. The popped element is typically returned as the result of the operation.
 Use Case: This operation is used when you need to retrieve and remove the most recently added item. For
example, when processing expressions in reverse Polish notation or when undoing actions in applications.
 Complexity: The time complexity of the Pop operation is also O(1), as it takes constant time to remove the top
element.

11 - A dictionary, d_city contains the records in the following format:


{state:city}
Define the following functions with the given specifications:
(a) push_city(d_city): It takes the dictionary as an argument and pushes all the cities in the stack CITY whose states are of
more than 4 characters.
(b) pop_city(): This function pops the cities and displays "Stack empty" when there are no more cities in the stack.

ANSWER:

# Initialize an empty stack for cities


CITY = []

def push_city(d_city):
"""
Pushes cities onto the stack CITY where the corresponding state has more than 4 characters.

:param d_city: Dictionary containing state:city pairs


"""
for state, city in d_city.items():
if len(state) > 4: # Check if the state name has more than 4 characters
[Link](city) # Push the city onto the stack

def pop_city():
"""
Pops a city from the stack CITY and displays it.
If the stack is empty, displays "Stack empty".
"""
if CITY: # Check if the stack is not empty
city = [Link]() # Pop the last city from the stack
print(city) # Display the popped city
else:
print("Stack empty") # Display message if the stack is empty
# Example usage:
d_city = {
'California': 'Los Angeles',
'Texas': 'Houston',
'New York': 'New York City',
'Ohio': 'Columbus',
'Florida': 'Miami'
}
# Push cities onto the stack
push_city(d_city)

# Pop cities from the stack


pop_city() # Should display 'Los Angeles' (if California is the only state with more than 4 characters)
pop_city() # Should display 'New York City' (if New York is the next)
pop_city() # Should display 'Stack empty' if all cities have been popped

12 - Consider a list named Nums which contains random integers.


Write the following user defined functions in Python and perform the specified operations on a stack named BigNums.
(a) PushBig(): It checks every number from the list Nums and pushes all such numbers which have 5 or more digits into the
stack BigNums.
(b) PopBig(): It pops the numbers from the stack, BigNums and displays them. The function should also display "Stack
Empty" when there are no more numbers left in the stack.
For example:
If the list Nums contains the following data:
Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]
Then on execution of PushBig(), the stack BigNums should store:
[10025, 254923, 1297653, 31498, 92765]
And on execution of PopBig(), the following output should be displayed:
92765
31498
1297653
254923
10025
Stack Empty

ANSWER:

# Define the stack


BigNums = []

# Sample list of random integers


Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]

def PushBig():
"""Push numbers with 5 or more digits onto the stack BigNums."""
for number in Nums:
if number >= 10000: # Check if the number has 5 or more digits
[Link](number)

def PopBig():
"""Pop numbers from the stack BigNums and display them."""
if not BigNums: # Check if the stack is empty
print("Stack Empty")
else:
while BigNums:
print([Link]()) # Pop and print each number
print("Stack Empty") # Indicate that the stack is now empty

# Execute the functions


PushBig() # Push numbers onto the stack
PopBig() # Pop numbers from the stack
13 - A list contains following record of course details for a University:
[Course_name, Fees, Duration]
Write the following user defined functions to perform given operations on the stack named 'Univ':
(a) Push_element(): To push an object containing the Course_name, Fees, and Duration of a course, which has fee greater
than 100000 to the stack.
(b) Pop_element(): To pop the object from the stack and display it. Also, display "Underflow" when there is no element in
the stack.
For Example:
If the lists of courses details are:
["MCA", 200000, 3]
["MBA", 500000, 2]
["BA", 100000, 3]
The stack should contain:
["MCA", 200000, 3]
["MBA", 500000, 2]

ANSWER

class Course:
def __init__(self, course_name, fees, duration):
self.course_name = course_name
[Link] = fees
[Link] = duration

def __repr__(self):
return f"[{self.course_name}, {[Link]}, {[Link]}]"

class Stack:
def __init__(self):
[Link] = []

def push(self, course):


[Link](course)

def pop(self):
if not self.is_empty():
return [Link]()
else:
return "Underflow"

def is_empty(self):
return len([Link]) == 0

def display(self):
return [Link]

def Push_element(univ_stack, course_details):


course_name, fees, duration = course_details
if fees > 100000:
course = Course(course_name, fees, duration)
univ_stack.push(course)

def Pop_element(univ_stack):
popped_course = univ_stack.pop()
if popped_course == "Underflow":
print(popped_course)
else:
print(f"Popped Course: {popped_course}")
# Example usage
if __name__ == "__main__":
# Create a stack for university courses
Univ = Stack()

# List of course details


courses = [
["MCA", 200000, 3],
["MBA", 500000, 2],
["BA", 100000, 3]
]

# Push elements to the stack


for course_detail in courses:
Push_element(Univ, course_detail)

# Display the current stack


print("Current Stack:", [Link]())

# Pop elements from the stack


Pop_element(Univ)
Pop_element(Univ)
Pop_element(Univ) # This should show "Underflow"

14 - Write separate user defined functions for the following:

(a) PUSH(N) : This function accepts a list of names, N as parameter. It then pushes only those names in the stack named
OnlyA which contain the letter 'A'
(b) POPA(OnlyA) : This function pops each name from the stack OnlyA and displays it. When the stack is empty, the
message "EMPTY" is displayed.
For Example:
If the names in the list N are
['ANKITA','NITISH','ANWAR','DIPLE','HARKIRAT']
Then the stack OnlyA should store
['ANKITA','ANWAR','HARKIRAT']
And the output should be displayed as
HARKIRAT ANWAR ANKITA EMPTY

ANSWER:

def PUSH(N):
OnlyA = [] # Initialize an empty stack
for name in N:
if 'A' in name: # Check if 'A' is in the name
[Link](name) # Push the name onto the stack
return OnlyA # Return the stack

def POPA(OnlyA):
if not OnlyA: # Check if the stack is empty
print("EMPTY")
else:
while OnlyA: # While the stack is not empty
print([Link]()) # Pop and print each name

# Example usage
N = ['ANKITA', 'NITISH', 'ANWAR', 'DIPLE', 'HARKIRAT']
OnlyA = PUSH(N) # Push names containing 'A' onto the stack
POPA(OnlyA) # Pop and display names from the stack
15 - Write the following user defined functions:
(a) pushEven(N) : This function accepts a list of integers named N as parameter. It then pushes only even numbers into the
stack named EVEN.
(b) popEven(EVEN) : This function pops each integer from the stack EVEN and displays the popped value. When the
stack is empty, the message "Stack Empty" is displayed.
For Example:
If the list N contains
[10,5,3,8,15,4]
Then the stack, EVEN should store
[10,8,4]
And the output should be
4 8 10 Stack Empty

ANSWER:

def pushEven(N):
# Initialize an empty stack
EVEN = []

# Push even numbers onto the stack


for number in N:
if number % 2 == 0: # Check if the number is even
[Link](number) # Push the even number onto the stack

return EVEN # Return the stack containing even numbers

def popEven(EVEN):
# Check if the stack is empty
if not EVEN:
print("Stack Empty")
return

# Pop each integer from the stack and display it


while EVEN:
popped_value = [Link]() # Pop the top value from the stack
print(popped_value, end=' ') # Display the popped value

print("Stack Empty") # Indicate that the stack is now empty

# Example usage
N = [10, 5, 3, 8, 15, 4]
EVEN = pushEven(N) # Push even numbers onto the stack
popEven(EVEN) # Pop and display the even numbers

16 - A list contains following record of customer:


[Customer_name, Room_Type]
Write the following user defined function to perform given operations on the stack named 'Hotel':
(a) Push_Cust(): To push customers' names of those who are staying in 'Delux' Room Type.
(b) Pop_Cust(): To pop the names of customers from the stack and display them. Also display "Underflow" when there are
no customers in the stack.
For Example:
If the lists with customer details are as follows:
["Aman","Delux"]
["Rahul","Standard"]
["Jerry","Delux"]
The stack should contain
Jerry
Aman
The output should be
Jerry
Aman
Underflow

ANSWER:
class HotelStack:
def __init__(self):
[Link] = []

def Push_Cust(self, customer_list):


# Push customers' names who are staying in 'Delux' Room Type
for customer in customer_list:
if customer[1] == "Delux":
[Link](customer[0])

def Pop_Cust(self):
# Pop the names of customers from the stack and display them
if not [Link]:
print("Underflow")
else:
while [Link]:
print([Link]())

# Example usage
customer_records = [
["Aman", "Delux"],
["Rahul", "Standard"],
["Jerry", "Delux"]
]

hotel = HotelStack()
hotel.Push_Cust(customer_records)
hotel.Pop_Cust()

17 - Write a function in Python, Push(Vehicle) where, Vehicle is a dictionary containing details of vehicles - {Car_Name:
Maker}
The function should push the name of car manufactured by 'TATA'(including all the possible cases like TaTa, Tata, etc.) to
the stack.
For Example:
If the dictionary contains the following data:
Vehicle={"Santro":"Hyundai","Nexon":"TATA", "Safari":"Tata"}
The stack should contain
Safari
Nexon

ANSWER:

def Push(Vehicle):
# Initialize an empty stack
stack = []
# Iterate through the dictionary
for car_name, maker in [Link]():
# Check if the maker matches 'TATA' in a case-insensitive manner
if [Link]() == 'tata':
# Push the car name onto the stack
[Link](car_name)

return stack

# Example usage
Vehicle = {"Santro": "Hyundai", "Nexon": "TATA", "Safari": "Tata"}
result_stack = Push(Vehicle)

# Print the result


print(result_stack) # Output: ['Nexon', 'Safari']

18 - Given Dictionary Stu_dict containing marks of students for three test series in the form Stu_ID:(TS1,TS2,TS3) as key-
value pairs.
Write a Python program with the following user defined functions to perform the specified operations on a stack named
Stu_Stk
(a) Push_elements(Stu_Stk, Stu_dict): It allows pushing IDs of those students, from the dictionary Stu_dict into the stack
Stu_Stk, Who have scored more than or equal to 80 marks in the TS3 Test.
(b) Pop_elements(Stu_Stk): It removes all elements present inside the stack in LIFO order and prints them. Also, the
function displays 'Stack Empty' when there are no elements in the stack.
Call both functions to execute queries.
For example:
If the dictionary Stu_dict contains the following data:
Stu_dict={5:(87,68,89), 10:(57,54,61),12:(71,67,90), 14: (66,81,80), 18:(80,48,91)}
After executing Push_elements(), Stk_ID should contain [5, 12, 14, 18]
After executing Pop_elements(), the output should be:
18
14
12
5
Stack Empty

ANSWER:

def Push_elements(Stu_Stk, Stu_dict):


# Push student IDs into the stack if they scored >= 80 in TS3
for stu_id, scores in Stu_dict.items():
if scores[2] >= 80: # TS3 is the third element in the tuple
Stu_Stk.append(stu_id)

def Pop_elements(Stu_Stk):
# Pop elements from the stack in LIFO order and print them
if not Stu_Stk:
print("Stack Empty")
else:
while Stu_Stk:
print(Stu_Stk.pop())
# Example dictionary
Stu_dict = {
5: (87, 68, 89),
10: (57, 54, 61),
12: (71, 67, 90),
14: (66, 81, 80),
18: (80, 48, 91)
}
# Initialize an empty stack
Stu_Stk = []

# Call the functions


Push_elements(Stu_Stk, Stu_dict)
print("Stack after pushing elements:", Stu_Stk) # Optional: to show the stack content before popping
Pop_elements(Stu_Stk)

19 - A list contains following record of a customer:

[Customer_name, Phone_number, City]

Write the following user defined functions to perform given operations on the stack named 'status':
(a) Push_element(): To push an object containing name and phone number of customers who live in Goa to the stack.
(b) Pop_element(): To pop the objects from the stack and display them. Also, display "Stack Empty" when there are no
elements in the stack.

ANSWER:

class Customer:
def __init__(self, name, phone_number):
[Link] = name
self.phone_number = phone_number

def __str__(self):
return f"Name: {[Link]}, Phone Number: {self.phone_number}"

class Stack:
def __init__(self):
[Link] = []

def push(self, item):


[Link](item)

def pop(self):
if not self.is_empty():
return [Link]()
else:
return None

def is_empty(self):
return len([Link]) == 0

def peek(self):
if not self.is_empty():
return [Link][-1]
else:
return None

def Push_element(customers, stack):


for customer in customers:
name, phone_number, city = customer
if [Link]() == "goa":
[Link](Customer(name, phone_number))
def Pop_element(stack):
if stack.is_empty():
print("Stack Empty")
else:
while not stack.is_empty():
customer = [Link]()
print(customer)

# Example usage
if __name__ == "__main__":
# Sample customer records
customer_records = [
["Alice", "1234567890", "Goa"],
["Bob", "0987654321", "Mumbai"],
["Charlie", "1122334455", "Goa"],
["David", "2233445566", "Delhi"]
]

# Create a stack
status = Stack()

# Push customers from Goa to the stack


Push_element(customer_records, status)

# Pop and display customers from the stack


Pop_element(status)

20 - Write a function in Python(SItem) where, SItem is a dictionary containing the details of stationary items -
{Sname:Price}.
The function should push the names of those items in the stack who have price greater than 75. Also display the count of
elements pushed into the stack.
For example:
If the dictionary contains the following data:
Ditem={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25}
The stack should contain
Notebook
Pen
The output should be
The count of elements in the stack is 2

ANSWER:

def push_items_to_stack(SItem):
# Initialize an empty stack
stack = []

# Iterate through the dictionary items


for item, price in [Link]():
# Check if the price is greater than 75
if price > 75:
# Push the item name onto the stack
[Link](item)

# Display the items in the stack


for item in stack:
print(item)
# Display the count of elements in the stack
print(f"The count of elements in the stack is {len(stack)}")

# Example usage
Ditem = {"Pen": 106, "Pencil": 59, "Notebook": 80, "Eraser": 25}
push_items_to_stack(Ditem)

21 - A list, NList contains following record as list elements:


[City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user defined functions in Pythons to
perform the specified operations on the stack named travel.
(a) Push_element(NList): It takes the nested list as an argument and pushes a list object containing name of the city and
country, which are not in India and distance is less than 3500 km from Delhi.
(b) Pop_element(): It pops the objects from the stack and displays them. Also, the function should display "Stack Empty:
when there are no elements in the stack.
For example:
If the nested list contains the following data:
NList=[["New York", "USA",11734],["Naypyidaw","Myanmar",
3219],["Dubai","UAE",2194],["London","England",6693],["Gangtok","India",1580],["Columbo","Sri Lanka",3405]]
The stack should contain:
["Naypyidaw","Myanmar"]
["Dubai","UAE"]
["Columbo","Sri Lanka"]
The output should be:
["Columbo","Sri Lanka"]
["Dubai","UAE"]
["Naypyidaw","Myanmar"]
Stack Empty

ANSWER:

class TravelStack:
def __init__(self):
[Link] = []

def Push_element(self, NList):


for record in NList:
city, country, distance = record
# Check if the country is not India and distance is less than 3500 km
if country != "India" and distance < 3500:
[Link]([city, country])

def Pop_element(self):
if not [Link]:
print("Stack Empty")
else:
# Pop the last element from the stack and display it
popped_element = [Link]()
print(popped_element)
# Example usage
NList = [
["New York", "USA", 11734],
["Naypyidaw", "Myanmar", 3219],
["Dubai", "UAE", 2194],
["London", "England", 6693],
["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]
]

travel = TravelStack()
travel.Push_element(NList)

# Pop elements from the stack until it's empty


while True:
travel.Pop_element()

You might also like