Search code examples
pythonjsonfizzbuzz

Read json data entries as objects in python file


I want to solve fizzbuzz problem using SOLID principles in python I wrote this code:

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

It works well. When I run the code I create an object by: em = tester() and then call the check function like: em.check(3, "Fizz")

They say: rules should be objects so I can add/register them to the rules executor dynamically, or via dependency injection I thought of JSON file to store all the rules in and read them as objects in a .py file, but I got stuck.

Is there any help?


Solution

  • I finally have a solution and here it is:

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