PYTHON
re-implement the Calc example meeting the following requirements, which are different than what I was aiming for in that example.
Instead of being objects of classes with a calculate method, calcs are instead functions that take a single argument. For example, the simplest calc might be zero_calc, which you could implement this way:
def zero_calc(n):
return 0
Implement equivalents of all of the calcs from that example in their new form. There is no specific requirement about how you name the functions, but, of course, you should follow the usual Python naming convention for function-naming.
Implement three additional calcs:
One that takes its input and converts it to an integer, failing with a ValueError if that conversion is not possible for the given input.
One that takes an input that is a function that takes no parameters, returning the value that the given function returns.
One that assumes its input is an object that supports Python's in operator and returns True or False, based on whether some value is "in" the input.
Rewrite the run_calcs function, so that it can accept our new form of calcs, instead of the ones that the original example could handle.
Additionally, in a Python script named problem2tests.py, write unit tests (using the unittest module from the Python standard library) for the individual calcs and for your newly-written run_calcs function.
import math
class ZeroCalc:
def calculate(self, n):
return 0
class SquareCalc:
def calculate(self, n):
return n * n
class CubeCalc:
def calculate(self, n):
return n * n * n
class LengthCalc:
def calculate(self, n):
return len(n)
class SquareRootCalc:
def calculate(self, n):
return math.sqrt(n)
class MultiplyByCalc:
def __init__(self, multiplier):
self._multiplier = multiplier
def calculate(self, n):
return n * self._multiplier
def run_calcs(calcs: ['Calc'], starting_value):
current_value = starting_value
for calc in calcs:
current_value = calc.calculate(current_value)
return current_value