Question:hard

Write a Python program to accept 10 integers from the user. If the entered number is a three-digit even integer, push it onto a stack. After all inputs are taken, pop all the three-digit even integers from the stack and display them. For example, if the user enters 12, 31, 320, 457, 6, 92, 924, 220, 1, 218, then the stack should contain:

320, 924, 220, 218

and the output of the program should be:

218 220 924 320

Show Hint

Push n only if it is even and has three digits. Then pop from the end of the list until it is empty.
Updated On: Oct 20, 2026
Show Solution

Solution and Explanation

Step 1: Think about the order of output:
The expected output 218 220 924 320 is the reverse of the order in which the numbers were pushed. That is how a stack behaves, so popping from the end of a list gives the right order.

Step 2: Choose the test for three digits:
The number of digits is the length of the number written as text. The call len(str(abs(n))) gives that length, and abs() keeps a negative sign from being counted.

Step 3: Write the program:
st = []
for i in range(10):
    n = int(input('Enter an integer: '))
    if n % 2 == 0 and len(str(abs(n))) == 3:
        st.append(n)
while len(st) > 0:
    print(st.pop(), end=' ')

The first loop reads 10 numbers and does the pushing. The while loop runs until the stack is empty and pops each element.

Step 4: Run it on the example:
Only 320, 924, 220 and 218 pass both tests. For 457 the length is 3 but the remainder is not 0. For 92 the remainder is 0 but the length is 2.
Popping the stack [320, 924, 220, 218] prints 218 220 924 320. This is the output I got when I ran the program.

Final Answer:
The program pushes the three-digit even numbers and then pops and prints them as 218 220 924 320.
Was this answer helpful?
0