본문 바로가기
코딩테스트/파이썬

[python] 큰 수식 찾기

by onggury 2023. 6. 12.

문제

정수와 더하기, 빼기, 곱하기 기호로 이루어진 두 개의 수식 A, B가 주어진다. 주어지는 수식은 모두 올바른 수식이며, 구체적으로는 다음 조건들을 만족한다.

  • 수식의 첫 문자와 마지막 문자는 항상 숫자이다.
  • 수의 맨 첫 문자가 0인 경우는 없다. 예를 들어 031과 같은 수는 주어지지 않는다.
  • 연산자가 최소 하나 이상 포함되어 있다.
  • 연산자가 붙어서 등장하는 경우는 없다.
  • 수식에 포함된 정수와 수식의 계산 결과는 모두 절댓값으로 10^14 이하이다.

각 수식을 연산자 우선순위에 따라 계산했을 때, 두 수식의 계산 결과 중 더 큰 값을 출력하시오.

 

 

입력

첫째 줄에 수식 A, B가 공백을 두고 주어진다.

  • 수식은 숫자와 +, *, - 기호로만 이루어져 있다.
  • 주어지는 수식의 길이는 3 이상 20 이하이다.
  • 수식은 지문에서 주어진 조건을 항상 만족한다. 

 

 

난 너무 무식하게 풀었다...

def makeList(operation):
	oper_str = ''
	oper_list = []
	
	for i in operation:
		if i.isdigit():
			oper_str += i
		else:
			oper_list.append(oper_str)
			oper_list.append(i)
			oper_str = ''

	oper_list.append(oper_str)
	
	return oper_list

def strOperation(operation):
	result = 0
	oper = ""
	
	stack_list = []
	
	idx = 0
	while idx < len(operation):
		if operation[idx] == "*":
			idx += 1
			result = int(stack_list.pop()) * int(operation[idx])
			stack_list.append(result)
		else:
			stack_list.append(operation[idx])
			
		idx += 1
	
	result = int(stack_list[0])
	for i in range(1, len(stack_list)-1):
		if stack_list[i] == "+":
			result += int(stack_list[i+1])
		elif stack_list[i] == "-":
			result -= int(stack_list[i+1])
	
	return result
	

a, b = input().split()

operA_list = makeList(a)
operB_list = makeList(b)

result_a = strOperation(operA_list)
result_b = strOperation(operB_list)

if result_a > result_b:
	print(result_a)
else:
	print(result_b)

 

 

파이썬에는 eval() 이란 함수가 있었다...

 

A, B = input().split()
print(max(eval(A), eval(B)))

파이썬의 연산자 우선순위로 수식을 바로 계산해주는 함수이다.

 

 

 

※출처

https://multicampus-kdt.goorm.io/lecture/38996/멀티잇-코딩테스트-러닝클래스-python-6월반