문제
정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 다섯 가지이다.
입력
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.
출력
출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.
import sys
input = sys.stdin.readline
class backjoonStack:
__list = []
def __init__(self):
self.main()
def push (self,data):
self.__list.append(data)
def pop (self):
if len(self.__list) == 0:
print(-1)
else:
print(self.__list[len(self.__list)-1])
self.__list.pop()
def size (self):
print(len(self.__list))
def empty (self):
if len(self.__list) > 0:
print(0)
else:
print(1)
def top (self):
if self.__list :
print(self.__list[-1])
else:
print(-1)
def main(self):
#print("숫자를 입력하세요:")
N = int(input())
for i in range(N):
#print("인풋을 입력하세요:")
variance = input().strip().split(' ')
variance.append("")
pre = variance[0]
if variance[1] != '':
qual = int(variance[1])
if pre == "push":
self.push(qual)
elif pre == "pop":
self.pop()
elif pre == "size":
self.size()
elif pre == "empty":
self.empty()
elif pre =="top":
self.top()
#print("현재 데이터: ",self.__list)
#answer = print(self.__list)
backjoonStack_ttt = backjoonStack()
후기: 너무 길다.
문제
입력
출력
문제
입력
출력
문제
입력
출력
문제
입력
출력
list가 비어있는걸 if조건문으로 만들 때 len()을 굳이 쓰지 않아도 됩니다!
def empty (self):
print(1 if self.__list else 0)
이렇게도 될 수 있겠네요!
또, 리스트의 원소를 뒤에서부터 가져오고 싶다면, list[-1] 이렇게 가져올 수 있습니다.
def pop (self):
if not self.list:
print(-1)
else:
print(self.list[-1])
self.__list.pop()
수고하셨습니다~!!