Styles of development
This is one of the homework assignments I did not put to much effort in,
unfortunately. This is due to other pressing, and time sensitive matters
that I had to focus on. However, I did something at least and wrote a very
simple calculator which can be seen in the calculator
module.
I mainly did this because I wanted to try out the unittest
package. So
this exercise is poorly done from my side, but as mentioned, I had other
matters to attend during this.
IntCalculator
Source code in src/course_package/calculator.py
| class IntCalculator:
"""
Integer calculator
"""
def __init__(self, expression: str):
"""Initialize class
Args:
expression: Expression to evaluate
"""
self.expression = expression
self.inp = self.parse_input()
self.operation = self.inp[1]
def parse_input(self):
"""Parse input
Parse the input and throw AssertionError if the
input is deviating
"""
inp = self.expression.split()
assert len(inp) == 3, "Check input"
return inp
def add(self):
"""Add method
"""
return int(self.inp[0]) + int(self.inp[2])
def subtract(self):
"""Subtract method
"""
return int(self.inp[0]) - int(self.inp[2])
def divide(self):
"""Divide method
"""
return int(self.inp[0]) / int(self.inp[2])
def multiply(self):
"""Multiply method
"""
return int(self.inp[0]) * int(self.inp[2])
def run(self) -> int | float:
"""Run calculator
Returns:
Answer
"""
hmap = {
"+": self.add(),
"-": self.subtract(),
"/": self.divide(),
"*": self.multiply(),
}
res = hmap[self.operation]
return res
|
__init__(expression)
Parameters:
Name |
Type |
Description |
Default |
expression
|
str
|
|
required
|
Source code in src/course_package/calculator.py
| def __init__(self, expression: str):
"""Initialize class
Args:
expression: Expression to evaluate
"""
self.expression = expression
self.inp = self.parse_input()
self.operation = self.inp[1]
|
add()
Source code in src/course_package/calculator.py
| def add(self):
"""Add method
"""
return int(self.inp[0]) + int(self.inp[2])
|
divide()
Source code in src/course_package/calculator.py
| def divide(self):
"""Divide method
"""
return int(self.inp[0]) / int(self.inp[2])
|
multiply()
Source code in src/course_package/calculator.py
| def multiply(self):
"""Multiply method
"""
return int(self.inp[0]) * int(self.inp[2])
|
Source code in src/course_package/calculator.py
| def parse_input(self):
"""Parse input
Parse the input and throw AssertionError if the
input is deviating
"""
inp = self.expression.split()
assert len(inp) == 3, "Check input"
return inp
|
run()
Returns:
Type |
Description |
int | float
|
|
Source code in src/course_package/calculator.py
| def run(self) -> int | float:
"""Run calculator
Returns:
Answer
"""
hmap = {
"+": self.add(),
"-": self.subtract(),
"/": self.divide(),
"*": self.multiply(),
}
res = hmap[self.operation]
return res
|
subtract()
Source code in src/course_package/calculator.py
| def subtract(self):
"""Subtract method
"""
return int(self.inp[0]) - int(self.inp[2])
|