CS/알고리즘_문제풀이(파이썬)

접시

Jedy_Kim 2021. 5. 24. 17:06
728x90

문제

접시 a, b, c, d 가 있고, 알파벳 순으로 한쪽이 막혀 있는 세척기에 들어간다고 할 때, b a c d 순으로 꺼내기 위해서는 push, push, pop, pop, push, pop, push, pop을 하면 된다. 세척기에서 꺼내는 순서가 주어질 때 그 동작을 출력하는 프로그램을 작성하시오. 만약 주어진 순서대로 접시를 꺼낼 수 없다면 “impossible”을 출력한다.

 

입력

첫째 줄에 소문자 알파벳이 주어진다. 중복된 소문자 알파벳은 입력되지 않는다. 알파벳 소문자는 26개이다. 입력되는 알파벳의 길이는 최대 26 자리이다.  

출력

접시를 꺼내는 것이 가능한 경우 push, pop의 순서를 출력한다. 이것이 불가능하다면 impossible을 출력한다.  

예제 입력 

bacd

예제 출력 

push

push

pop

pop

push

pop

push

pop

예제 입력 

dabc

예제 출력 

impossible

 

#코드(문제 통과는 되었지만 코드리뷰가 필요하다.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import sys
getStr = sys.stdin.readline()
 
cursorPointer = 0
stack_list = list()
pop_list = list()
history_list = list()
isPossible = True
 
while True
  if len(stack_list) == 0:
    stack_list.append(getStr[cursorPointer])
    history_list.append('push')
    cursorPointer += 1
    
  if cursorPointer >= len(getStr):
    for i in range(len(stack_list)):
      temp = stack_list[-1]
      del stack_list[-1]
      history_list.append('pop')
      pop_list.append(temp)
    for i in range(len(pop_list)-1):
      if ord(pop_list[i]) > ord(pop_list[i+1]):
        isPossible = False
    break 
  if getStr[cursorPointer-1> getStr[cursorPointer]:
    stack_list.append(getStr[cursorPointer])
    history_list.append('push')
    cursorPointer += 1
  elif getStr[cursorPointer-1< getStr[cursorPointer]:
    temp = stack_list[-1]
    del stack_list[-1]
    pop_list.append(temp)
    history_list.append('pop')
    
 
if isPossible == True:
  for i in history_list:
    print(i)
else:
  print('impossible')
cs

 

반응형

'CS > 알고리즘_문제풀이(파이썬)' 카테고리의 다른 글

car  (0) 2021.05.25
괄호  (0) 2021.05.24
스택 구현하기  (0) 2021.05.24
조회 알고리즘  (0) 2021.05.23
2차원 조회  (0) 2021.05.23