S
Steven D'Aprano
Just for fun:
class Numberator:
def __init__(self, number):
self.__number = number
def evaluate(self):
return self.__number
class Multiplier:
def __init__(self, multiplier, multiplicand):
self.multiplier = multiplier
self.multiplicand = multiplicand
def evaluate(self):
return self.multiplier * self.multiplicand.evaluate()
class FactorialBuilder:
def __init__(self, number):
if not isinstance(number, int):
raise TypeError
if number < 0:
raise ValueError
self.__number = number
def build(self):
multiplicand = Numberator(1)
for n in range(2, self.__number + 1):
multiplicand = Multiplier(n, multiplicand)
return Factorialiser(multiplicand)
class Factorialiser:
def __init__(self, evaluatorix):
self.__evaluatorix = evaluatorix
def calculate(self):
return self.__evaluatorix.evaluate()
for i in range(16):
print(i, FactorialBuilder(i).build().calculate())
And the output is:
0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
11 39916800
12 479001600
13 6227020800
14 87178291200
15 1307674368000
It goes without saying that this isn't Pythonic
class Numberator:
def __init__(self, number):
self.__number = number
def evaluate(self):
return self.__number
class Multiplier:
def __init__(self, multiplier, multiplicand):
self.multiplier = multiplier
self.multiplicand = multiplicand
def evaluate(self):
return self.multiplier * self.multiplicand.evaluate()
class FactorialBuilder:
def __init__(self, number):
if not isinstance(number, int):
raise TypeError
if number < 0:
raise ValueError
self.__number = number
def build(self):
multiplicand = Numberator(1)
for n in range(2, self.__number + 1):
multiplicand = Multiplier(n, multiplicand)
return Factorialiser(multiplicand)
class Factorialiser:
def __init__(self, evaluatorix):
self.__evaluatorix = evaluatorix
def calculate(self):
return self.__evaluatorix.evaluate()
for i in range(16):
print(i, FactorialBuilder(i).build().calculate())
And the output is:
0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
11 39916800
12 479001600
13 6227020800
14 87178291200
15 1307674368000
It goes without saying that this isn't Pythonic