Python/공통이론
Python - push pop 구현
zeroup
2023. 4. 6. 21:46
1. 후위 표기법(RPN)
: n1 ? n2 > n1 n2 ? 로 표기하는 기법
ex1) 10 5 * 7 3 + /
> (10 * 5) / (7 + 3)
ex2) 2 3 2 3 7 + + + +
> 2 + (3 + (2 + (3 + 7)))
2. push/pop을 이용한 후위표기법 계산 프로그램
>>> the_stack = []
>>>
>>> def main():
>>> s = input('Enter RPN string : ')
>>> a_list = s.split()
>>>
>>> for item in a_list :
>>> if item.isdisit() :
>>> the_stack.append(float(item))
>>> else :
>>> if the_stack.count() < 2
>>> print('ERROR : Too few stack')
>>> return
>>>
>>> op2 = the_stack.pop()
>>> op1 = the_stack.pop()
>>> if item == '+' :
>>> the_stack.append(op1 + op2)
>>> elif item == '-' :
>>> the_stack.append(op1 - op2)
>>> elif item == '*' :
>>> the_stack.append(op1 * op2)
>>> else item == '/' :
>>> the_stack.append(op1 / op2)
>>> else :
>>> print('ERROR : Operation out of range')
>>> return
>>>
>>> print(the_stack.pop())
>>>
>>> main()