Test Index
Stack
© examsnet.com
Question : 6 of 12
Marks:
+1,
-0
A dictionary,
d_city contains the records in the following format :{state:city}Define the following functions with the given specifications :(i) 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.(ii) pop_city(): This function pops the cities and displays "Stack empty" when there are no more cities in the stack.[CBSE 2024 Compartment]
Solution:
(i)
CITY = []def push_city(d_city): for state in d_city: if len(state) > 4: CITY.append(d_city[state])(ii)
def pop_city(): while CITY: print(CITY.pop()) print("Stack empty")Explanation:The list CITY is used as a stack; its end is the top.push_city(): the loop visits each key (state); if the state name has more than 4 characters, its city is pushed with append().pop_city(): while the stack is not empty, pop() removes and prints the top city (last in, first out). When nothing is left (underflow), "Stack empty" is displayed.Example: d_city = {'Kerala': 'Kochi', 'Goa': 'Panaji', 'Punjab': 'Amritsar'}push_city pushes Kochi and Amritsar (Goa has only 3 characters). pop_city prints:AmritsarKochiStack empty
© examsnet.com
Go to Question: