Python FizzBuzz

后端 未结 8 813
刺人心
刺人心 2020-12-20 10:34

I have been given this question to do in Python:

Take in a list of numbers from the user and run FizzBuzz on that list.

When you loop through the list rememb

8条回答
  •  没有蜡笔的小新
    2020-12-20 11:19

    Here's how I did it using generators. Explanations are added as comments.

    # the factors to check for, along with its
    # associated text data.
    FACTORS = {
        3 : "Fizz",
        5 : "Buzz",
    }
    
    
    def fizzbuzz(start, stop):
        """FizzBuzz printer"""
        for i in range(start, stop+1):
            string = ""  # build string
    
            # iterate through all factors
            for j, dat in FACTORS.items():
                # test for divisibility
                if i % j == 0:
                    # add data to string if divisible
                    string += dat
    
            if not string:
                # if string's length is 0, it means,
                # all the factors returned non-zero
                # modulus, so return only the number
                yield str(i)
            else:
                # factor had returned modulo as 0,
                # return the string
                yield string
    
    
    if __name__ == "__main__":
        for each in fizzbuzz(1, 100):
            print(each)
    

    This version has the advantage of not depending on any extra factor checks.

提交回复
热议问题