Stack! Stack! Stack! @ Dcoder

in #programming9 months ago

Problem: Practice your stack data structure. You will be given a series of tasks of push, pop, peek operations to perform on a stack. You need to print the sum of the final stack.
Input: First line contains Q, the number of queries.
The next Q lines each contain a query. PUSH queries are accompanied by a positive number N.
Output: Print the topmost element for every 'PEEK' query, each in a newline.
Also, print the sum of the remaining elements of the stack in the end in a newline.
Constraints: 1 ≤ Q ≤ 50
1 ≤ N ≤ 1000
It is guaranteed that there would be no query of pop or peek operation on an empty stack.
Sample Input: 6
PUSH 8
PEEK
POP
PUSH 4
PUSH 3
PEEK
Sample Output:
8
3
7

stack = []
for t in range(int(input())):
  q = input().split()
  if q[0] == 'PUSH':
    stack.append(int(q[1]))
  elif q[0] == 'POP':
    stack .pop()
  else:
    print(stack[-1])
print(sum(stack))