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