StackStack

스택의 기본구조 :by List

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
class :

def __init__(self):
self.stack = []

def SisEmpty(self):
return len(self.stack) == 0

def SPush(self, val):
self.stack.append(val)

def SPop(self):
if self.SisEmpty():
return None
else:
return self.stack.pop()

def SPeek(self):
index = len(self.stack) - 1
if self.SisEmpty():
return None
else:
return self.stack[index]


## Result

if __name__ == '__main__':
s_stack = Stack()
s_stack.SPush(10)
s_stack.SPush(20)
s_stack.SPush(30)
s_stack.SPush(40)

print(s_stack.SisEmpty()) #false
print(s_stack.SPeek()) #40
print(s_stack.SPop()) #40
print(s_stack.SPop()) #30
print(s_stack.SPeek()) #20

스택을 이용한 연산 후위 표기법

ADT

1
2
3
4
5
6
7
8
convertToPostfix
# 입력받은 연산자를 후위연산자로 변환한다.

getOpPrec
#연산자의 가중치를 리턴한다.

get_postfix_exp
#후위연산자를 리턴한다.

Rule

  1. ( 는 무조건 stack에 담는다.
  2. ) 를 만나면 무조건 그 이전까지 stack에 담겨있던 것들을 결과물로 옮긴다. (단, 자기자신은 제거될 것)
  3. 숫자가 아닌 연산자는 stack에 쌓는다.

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from stack import Stack

class PostfixCalculate:
# 원래 주어진 수식
# origin_exp
# 결과 (후위 수식)
# postfix_exp

# method
def __init__(self, origin):
self.origin_exp = origin
self.postfix_exp = None

def getOpPrec(self,op):
if op == '*' or op == '/':
return 5
elif op == '+' or op == '-':
return 3
elif op == '(':
return 1
else:
return -1 # 등록되지 않은 수식


def convertToPostfix(self):
exp_list = []
operate_stack = Stack()

#숫자와 수식을 구별한다
for i in self.origin_exp:

if i.isdigit():
exp_list.append(i)
else:
# ( 거나 스택이 비었을 경우
if i == '(' or operate_stack.SisEmpty():
operate_stack.SPush(i)
# ) 경우 연산자를 모두 배열에 넣기
elif i == ')':
operation = operate_stack.SPop()
exp_list.append(operation)
# 기존의 연산자보다 비중이 높다면 그대로 유지
elif self.getOpPrec(i) > self.getOpPrec(operate_stack.SPeek()):
operate_stack.SPush(i)
# 기존의 연산자보다 비중이 같거나 낮을때
else:

while not operate_stack.SisEmpty() and self.getOpPrec(i) <= self.getOpPrec(operate_stack.SPeek()):
operation = operate_stack.SPop()
exp_list.append(operation)
operate_stack.SPush(i)

while not operate_stack.SisEmpty():
op = operate_stack.SPop()
exp_list.append(op)
self.postfix_exp = ''.join(exp_list)

def get_postfix_exp(self):
if not self.postfix_exp:
self.convertToPostfix()

return self.postfix_exp


if __name__ == '__main__':
origin = input("수식을 입력해주세요: ")

calcurate = PostfixCalculate(origin)
calcurate.convertToPostfix()
print("resutl:", calcurate.get_postfix_exp())