중위 후위 전위 계산 방법 관련해서 답변 부탁드립니다
조회수 1008회
class Node:
def __init__(self,item,link):
self.item=item
self.next=link
def push(item):
global top
global size
top = Node(item, top)
size += 1
def peek():
if size != 0:
return top.item
def pop():
global top
global size
if size != 0:
top_item = top.item
top = top.next
size -= 1
return top_item
def print_stack():
print('top -> \t',end='')
p = top
while p:
if p.next != None:
print(p.item,end='')
print(" ")
else:
print(p.item,end='')
print(" ")
p = p.next
print()
top = None
size = 0
여기까지가 예시로 보여준 코드이고 이 코드를 이용해서 스택을 사용한 전위, 중위, 후위 계산을 하는것이 목적입니다
temp1=0
temp2=0
postfix='4 4 3 * / 2 + 3 -'
for i in postfix:
if i == '1':
push(1)
elif i == '2':
push(2)
elif i == '3':
push(3)
elif i == '4':
push(4)
elif i == '5':
push(5)
elif i == '6':
push(6)
elif i == '7':
push(7)
elif i == '8':
push(8)
elif i == '9':
push(9)
elif i == ' ':
continue
elif i == '+':
temp2=pop()
temp1=pop()
push(temp1+temp2)
elif i == '-':
temp2=pop()
temp1=pop()
push(temp1-temp2)
elif i == '*':
temp2=pop()
temp1=pop()
push(temp1*temp2)
elif i == '/':
temp2=pop()
temp1=pop()
push(int(temp1/temp2))
print_stack()
print("result = " + str(pop()))
이건 제가 만든 후위 계산 법인데 이와 같은 방식으로 전위하고 중위 계산을 어떻게 해야 하나요;
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
전위 후위 중위는 pop/push 순서만 다르게 해주면 되는 것 아닌가요?
elif i == '+': temp2=pop() push(temp1+temp2) temp1=pop() elif i == '-': temp2=pop() push(temp1-temp2) temp1=pop() elif i == '*': temp1=pop() push(temp1*temp2) temp2=pop() elif i == '/': temp1=pop() push(int(temp1/temp2)) temp2=pop()
이런식으로 해보셨나요?
댓글 입력