ssuperjun 님의 블로그
[과제 2] 사칙연산 계산기 만들기 본문
요구 조건
- 숫자, 사칙연산 입력 하여 사칙 연산 가능한 계산기 만들기
- 그만둘 때까지 계속 입력 가능
- 그만두면 지금까지 계산한 결과 값 출력
예시
Input Number : 1
Input the four fundamental arithmetic operations : +
Input Number : 2
Will you stop? NO
Input the four fundamental arithmetic operations : -
Input Number : 1
Will you stop? YES
Result : 2
구현
python 사용
예외 처리
사칙연산 외의 문자가 입력된 경우, 사칙연산 재요구
나누기 0인 경우, 0이 아닐 때까지 숫자 요구
그만두기 문자가 다를 경우, YES/NO 재입력 요구
코드
# Simple Calculator
result = float(input("Input Number : "))
while True:
operator = input("Input the four fundamental arithmetic operations : ")
operand = int(input("Input Number : "))
if operator == "+":
result += operand
elif operator == "-":
result -= operand
elif operator == "*":
result *= operand
elif operator == "/":
if operand == 0:
while operand == 0:
print("Error: Division by zero is not allowed.")
operand = int(input("Input Number (non-zero) : "))
result /= operand
else:
print("Invalid operator. Please use +, -, *, or /.")
continue
stop_flag = False
while True:
print("Will you stop? (YES/NO) : ",end="")
stop = input()
if stop.upper() == "YES" or stop.upper() == "Y":
stop_flag = True
break
elif stop.upper() == "NO" or stop.upper() == "N":
break
else:
print("Invalid input. Please respond with YES or NO.")
continue
if stop_flag:
break
print("Result : %.2f" % result)
클라우드 인스턴스에서 실행
로컬에서 인스턴스로 python 파일 이동 명령어
scp -i <pem키 경로> <로컬파일> ubuntu@<서버IP>:/home/ubuntu
이동이 불가능해, 인스턴스 내에서 calculator.py 새로 생성
vi calculator.py
실행
python3 calculator.py
추가 구현
- 사칙연산의 우선순위 적용 ( *, / 우선순위 적용 )
- 예시)
Input Number : 100
Input the four fundamental arithmetic operations : + # 덧셈
Input Number : 30
Will you stop? (YES/NO) : NO
Input the four fundamental arithmetic operations : / # 나눗셈 (우선순위 적용)
Input Number : 2
Will you stop? (YES/NO) : N
Result : 80.00
추상화
stack을 이용해 중위 표기식을 후위 표기식으로 변경
후위 표기식을 계산
참고한 알고리즘
후위 표기식으로 변경 방법
1. 괄호가 여는 괄호이면 무조건 push한다.
2. 괄호가 닫는 괄호이면 stack에서 여는 괄호가 나올 때 까지 pop을 한 후 출력한다.
3. 여는 괄호가 스택에 push된 후 닫는 괄호가 나올 때 까지 여는 괄호가 pop이 되면 안되므로 여는 괄호의 우선순위는 제일 작다. (위의 간단한 후위 표기법 알고리즘 3번 조건)
4. 괄호는 출력하지 않는다.
나머지는 위와 동일.
중위 표기식 ( A + B ) * ( C + D ) 를 후위 표기법을 사용해 다시 수식을 써보면 A B + C D + * 가 된다.
후위 표기식 계산 방법
1. 피연산자면 스택에 push한다.
2. 연산자를 만나면 pop을 두번하고 각각 값을 저장한 후, 연산자에 맞는 계산을 한다.
3. 계산을 한 뒤, 결과 값은 다시 스택에 넣는다. 이 과정을 수식이 끝날 때 까지 반복한다.
4. 수식이 끝났다면 스택에 마지막 남은 값이 결과 값이 된다.
실제 식을 사용해 후위 표기식을 계산해보자.
중위 표기식 2 * ( 4 + 5 ) -> 후위 표기식 2 4 5 + *
출처: https://jamanbbo.tistory.com/53
코드
# Calculator v2
stack = [] # 후위표기식 계산용 스택
postfix = [] # 후위표기식
first_num = int(input("Input Number : "))
postfix.append(first_num)
while True:
# 연산자 처리
operator = input("Input the four fundamental arithmetic operations : ")
if operator not in ["+", "-", "*", "/"]:
print("Invalid operator. Please use +, -, *, or /.")
continue
# 우선순위가 같거나 낮은 연산자들 스택에서 꺼내기
while stack and ((stack[-1] in ["*", "/"]) or (stack[-1] in ["+", "-"] and operator in ["+", "-"])):
postfix.append(stack.pop())
stack.append(operator)
# 피연산자(숫자) 처리
operand = int(input("Input Number : "))
if operator == "/" and operand == 0:
while operand == 0:
print("Error: Division by zero is not allowed.")
operand = int(input("Input Number (non-zero) : "))
postfix.append(operand)
# 종료 여부 확인
stop_flag = False
while True:
print("Will you stop? (YES/NO) : ",end="")
stop = input()
if stop.upper() == "YES" or stop.upper() == "Y":
stop_flag = True
break
elif stop.upper() == "NO" or stop.upper() == "N":
break
else:
print("Invalid input. Please respond with YES or NO.")
continue
if stop_flag:
while stack:
postfix.append(stack.pop())
break
# 후위표기식 계산
stack = []
for token in postfix:
if token in ["+", "-", "*", "/"]:
b = stack.pop()
a = stack.pop()
if token == "+":
stack.append(a + b)
elif token == "-":
stack.append(a - b)
elif token == "*":
stack.append(a * b)
elif token == "/":
stack.append(float(a) / float(b))
else:
stack.append(token)
result = stack.pop()
print("Result : %.2f" % result)
'인턴' 카테고리의 다른 글
| [과제 4-1] MySQL 자동 설치 스크립트 생성 - apt 레포지터리 이용 (0) | 2026.01.07 |
|---|---|
| [과제 3-1] NHN Cloud 인스턴스에서 MySQL 설치 - apt 레포지터리 이용 (0) | 2026.01.06 |
| [과제 1] bash, vi 기본 커맨드 익히기 (1) | 2026.01.06 |
| NHN Cloud 콘솔에서 인스턴스 생성 (0) | 2026.01.06 |
| 첫 글 (0) | 2026.01.05 |