첫 번째 시도
class Deque:
def __init__(self):
self.deque = []
def push_front(self, x):
self.deque = [int(x)] + self.deque
return
def push_back(self, x):
self.deque = self.deque + [int(x)]
return
def pop_front(self):
if self.deque == []:
return -1
else:
n = self.deque[0]
self.deque = self.deque[1:]
return n
def pop_back(self):
if self.deque == []:
return -1
else:
n = self.deque[-1]
self.deque = self.deque[:-1]
return n
def size(self):
n = len(self.deque)
return n
def empty(self):
if self.deque == []:
return 1
else:
return 0
def front(self):
if self.deque == []:
return -1
else:
return self.deque[0]
def back(self):
if self.deque == []:
return -1
else:
return self.deque[-1]
dq = Deque()
for _ in range(int(input())):
cmd = input().split()
if cmd[0] == "push_front":
dq.push_front(int(cmd[1]))
elif cmd[0] == "push_back":
dq.push_back(int(cmd[1]))
elif cmd[0] == "pop_front":
print(dq.pop_front())
elif cmd[0] == "pop_back":
print(dq.pop_back())
elif cmd[0] == "size":
print(dq.size())
elif cmd[0] == "empty":
print(dq.empty())
elif cmd[0] == "front":
print(dq.front())
elif cmd[0] == "back":
print(dq.back())
호기롭게 Deque을 구현해보자!해서 class을 만들었지만 태생이 list인지라 역시나 시간초과에 걸렸다. 답은 올바르게 나오지만(ㅋㅋ) class
연습했다고 생각하자.
두 번째 시도
from collections import deque
import sys
input = sys.stdin.readline
dq = deque()
for _ in range(int(input())):
cmd = input().split()
if cmd[0] == "push_front":
dq.appendleft(int(cmd[1]))
elif cmd[0] == "push_back":
dq.append(int(cmd[1]))
elif cmd[0] == "pop_front":
try:
print(dq.popleft())
except:
print(-1)
elif cmd[0] == "pop_back":
try:
print(dq.pop())
except:
print(-1)
elif cmd[0] == "size":
print(len(dq))
elif cmd[0] == "empty":
if len(dq) == 0:
print(1)
else:
print(0)
else:
if len(dq) == 0:
print(-1)
else:
if cmd[0] == "front":
print(dq[0])
elif cmd[0] == "back":
print(dq[-1])
collections
라이브러리의 deque
을 이용했다. 라이브러리를 사용하다보니 코드에서 고민할 부분은 예외 처리
말고는 딱히 없었다.
고수의 풀이
n,*l=open(0);a,p=[],print
for i in l:
if"h_f"in(q:=(j:=i.split())[0]):a=[j[1]]+a
elif"h_b"in q:a+=[j[1]]
elif"p_f"in q:p(a.pop(0)if a else-1)
elif"p_b"in q:p(a.pop()if a else-1)
elif"i"in q:p(len(a))
elif"m"in q:p(+(len(a)<1))
elif"r"in q:p(a[0]if a else-1)
else:p(a[len(a)-1]if a else-1)