Python Stack Practice Questions


  1. 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 Python to perform the specified operations on the stack named travel.

    (i) 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.

    (ii) 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", "U.S.A.", 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
    
  2. travel = []
    def Push_element(NList):
          for L in NList:
                if L[1] != "India" and L[2]<3500:
                      travel.append( [L[0], L[1]] )
    
    def Pop_element( ):
          while len(travel):
                print(travel.pop( ) )
          else:
                print("Stack Empty")