무냐의 개발일지

[자료구조] 파이썬으로 계산기 만들기 (Stack) 본문

데싸 추가 독학

[자료구조] 파이썬으로 계산기 만들기 (Stack)

무냐코드 2024. 4. 9. 18:16

 

 

와 이거 진짜 오래걸렸네 ㅜㅜㅜ 흑흑

그래도 끈질기게 해서 결국 해냈다 !!!!

 

첫번째 방법

#정상작동하는 코드
Operators = ['+', '-', '*', '/', '(', ')', '^']  # collection of Operators
Priority = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities of Operators
 
 
def infixToPostfix(expression): 
    stack = [] # initialization of empty stack
    output = '' 

    for character in expression:
        if character not in Operators:  #숫자/문자들은 결과에 추가
            output+= character 
        elif character=='(':  			# ( 로 시작하면 stack에 추가 
            stack.append('(')
        elif character==')':			# ) 가 들어오면, ( 가 나올때까지 뽑아서 결과에 추가
            while stack and stack[-1]!= '(':
                output+=stack.pop()
            stack.pop()					# ) 가 나오면 삭제
        else: 
            while stack and stack[-1]!='(' and Priority[character]<=Priority[stack[-1]]:
                output+=stack.pop()		# 연산기호들 간의 우선순위 지정! 우선순위 더 낮은 애가 들어오면, 있던 애는 결과에 넣어주고 
            stack.append(character)		# 새로 들어온 애는 stack에 넣어준다

    while stack:						# stack에 남아있는 애들 다 빼서, 결과에 넣어준다
        output+=stack.pop()
    return output


expression = 'm*n+(p-q)+r'
print('infix notation: ',expression)
print('postfix notation: ',infixToPostfix(expression))

 

 

두번째 방법

class Stack:
	def __init__(self):
		self.items = []
	def push(self,val):					#추가하는거
		self.items.append(val)
	def pop(self):
		try:
			return self.items.pop()		#일단 제거하는 기능
		except IndexError:				#에러나면 스택에 아무것도 없는거
			print('Stack Empty')
	def top(self):
		try:
			return self.items[-1]		#맨위에 있는거 표출
		except IndexError:
			print('Stack Empty')		#에러나면 아무것도 없는거
	def __len__(self):
		return len(self.items)			#스택의 길이
	def isEmpty(self):					#스택이 비었는지 True, False로 알려준다
		return len(self.items) == 0
	

# WORKING !!!!!
def infix_to_postfix(infix):
	precedence = {'(':0, '+':1, '-':1, '*':2, '/':2}
	stack = Stack()   	#잠깐 연산자를 담아두는 주머니
	result = []  			#실제 계산되는 대상
	operator = ['+', '-', '*', '/', '(', ')', '^']

	for token in infix:
		if token not in operator:
			result.append(token)					#숫자면(operand), outstack에 넣는다
		elif token == '(':							#여는 괄호 '('면, stack에 넣는다
			stack.push(token)
		elif token == ')':
			while stack and stack.top() != '(':	#stack이 비어있지 않고, 가장 위에있는 값이 ( 가 아닐 때,
				result.append(stack.pop())		# '(' 가 나올때까지 연산자 뽑아서 outstack에 넣기
			stack.pop()							# while문이 끝나고, '(' 가 나오면 삭제해버린다 ()가 같이 사라지는거임 ! 
		else:
			while stack and precedence[stack.top()] >= precedence[token]:	#get(가려오려는 키, 키 없을때 반환할 기본값)
				result.append(stack.pop())
			stack.push(token)
		
	while stack:				   				#opstack이 비어있지 않을때, 라는 뜻이다
		result.append(stack.pop())			#나머지 다 뽑아서 outstack에 넣기 
	print(''.join(result))


# exp = input("Enter an infix expression: ").split()
infix = 'm*n+(p-q)+r'
print(infix)

infix_to_postfix(infix)