Python 연습 15: 문자열에 대한 계산 수행
의문
기본 산술 연산을 수행하는 함수 만들기
제한
eval()
허용되지 않습니다. -1
를 반환합니다."15 // 0" ➞ -1
예시
arithmetic_operation("12 + 12") ➞ 24 // 12 + 12 = 24
arithmetic_operation("12 - 12") ➞ 24 // 12 - 12 = 0
arithmetic_operation("12 * 12") ➞ 144 // 12 * 12 = 144
arithmetic_operation("12 // 0") ➞ -1 // 12 / 0 = -1
내 시도
>>separate the number and operator in the string by space
call split() method
>>perfrom action based whether it is a number or valid operator
import operator module
build a dictionary with key=the operator string, value = the equivent function
check the second separated part, which must be operator, to call the equivent function from the dictionary
pass the first and thrid element as argument to the function
>>return the result
import operator
def arithmetic_operation(math_sting: str):
# split the string
splited_list = math_sting.split()
first_num = int(splited_list[0])
second_num = int(splited_list[-1])
operation_to_call = splited_list[1]
# In case of division, whenever the second number equals "0" return`-1`.
if operation_to_call == "//" and second_num == 0:
return -1
# setup dictionary to call the maths operation
math_dictionary = {"+": operator.add(first_num, second_num),
"-": operator.sub(first_num, second_num),
"*": operator.mul(first_num, second_num),
"//": operator.floordiv(first_num, second_num)}
# find the equivalent operation from the dictionary and store the result
result = math_dictionary[operation_to_call]
return result
기타 솔루션
def arithmetic_operation(equation):
'''
Returns the result of evaluating the string equation '''
from operator import add, sub, floordiv, mul
operator_dict = {'+': add, '-': sub, '*': mul, '//': floordiv}
# split the equation into three part
first_num, operation, second_num = equation.split()
try:
# call the operation from the dictionary and perform the calculation
return operator_dict[operation](int(first_num), int(second_num))
# In case of division, whenever the second number equals "0" return`-1`.
except ZeroDivisionError:
return -1
가장 이해하기 쉬운 방법
def arithmetic_operation(equation):
first_num, operation, second_num = equation.split()
if operation == '+':
return int(first_num) + int(second_num)
if operation == '-':
return int(first_num) - int(second_num)
if operation == '*':
return int(first_num) * int(second_num)
if operation == '//' and second_num == '0':
return -1
return int(first_num) // int(second_num)
내 반성
신용 거래
챌린지 온edabit
Reference
이 문제에 관하여(Python 연습 15: 문자열에 대한 계산 수행), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/mathewchan/python-exercise-15-perform-calculation-on-a-string-1khg텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)