我想在python中使用SOLID原理解决fizzbuzz问题 我写了这段代码:
class tester(object):
def check(self, number, string):
return ", ".join(self.check_numbers(number, string))
def check_numbers(self, number, string):
number_list = []
for n in range (1, 101):
if n%number==0:
number_list.append(string)
else:
number_list.append(str(n))
return number_list
效果很好。运行代码时,我通过以下方式创建对象:em = tester()
,然后调用检查功能,例如:em.check(3, "Fizz")
他们说:规则应该是对象,因此我可以动态地或通过依赖注入将它们添加/注册到规则执行器中 我想到了JSON文件来存储所有规则,然后将它们作为对象读入.py文件中,但是我被卡住了。
有什么帮助吗?
答案 0 :(得分:0)
我终于有了解决方案,这里是:
from collections import namedtuple
def is_divisible(number, modulo):
return number % modulo == 0
FizzBuzz = namedtuple('FizzBuzz', 'number, name')
fizz_buzz_words = [
FizzBuzz( 3, 'Fizz'),
FizzBuzz( 4, 'Buzz'),
FizzBuzz( 7, 'Bang'),
FizzBuzz(11, 'Boom'),
]
def to_fizz_buzz_string(n):
fizz_buzzes = [fb.name for fb in fizz_buzz_words if is_divisible(n,
fb.number)]
return ''.join(fizz_buzzes) if fizz_buzzes else str(n)
for a in range(124, 134):
print to_fizz_buzz_string(a)
print ', '.join(to_fizz_buzz_string(n) for n in range(923, 935))