Decode Function Calls
Python
Hard
3 views
Problem Description
Read n commands: PUSH x, POP, TOP. Use functions do_push, do_pop, do_top on a stack and output TOP outputs (or EMPTY).
Input Format
First line n. Next n lines commands.
Output Format
Outputs for TOP.
Sample Test Case
Input:
7
PUSH 5
TOP
PUSH 3
TOP
POP
TOP
POP
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
n=int(lines[0].strip())
st=[]
out=[]
def do_push(x):
st.append(x)
def do_pop():
if st:
st.pop()
def do_top():
out.append(str(st[-1]) if st else 'EMPTY')
for i in range(1,1+n):
parts=(lines[i] if i<len(lines) else '').split()
if not parts: continue
if parts[0]=='PUSH':
do_push(int(parts[1]))
elif parts[0]=='POP':
do_pop()
else:
do_top()
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!