Python Exercise 15 : Perform calculation on a string
Tags: beginners, python, challenge
Published: 2022-06-24 08:58:00

## Question
- Create a function to perform basic arithmetic operations 
	- that includes **addition**, **subtraction**, **multiplication** and **division** 
	- on a string number 

-  For the challenge, we are going to have only two numbers and 1 valid operator in between.
- The return value should be a number.

### Restriction

- `eval()` is not allowed.

-  In case of division, whenever the second number equals "0" return `-1`.

```python
"15 // 0"  ➞ -1
```

### Example

```python
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
```
## My attempt
- algorithm

```
>>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
```
- code

```python
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
```



## Other solution

```python
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
```

## Easiest understand method

```python
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)
```

## My reflection
- I have learned that import statement can be exist inside a function. When you expect an error would occur, should use exceptional handling to deal with it.

## Credit
challenge on [edabit](https://edabit.com/challenge/peezjw73G8BBGfHdW)