Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prints Duplicates BuzzFizz game

n = 0
toTest = [
    3,
    5,
    7
]
outputCanBe = [
    "Fizz",
    "Buzz",
    "Bizz"
]
outputIndex = 0
iteration = (len(toTest)) 
while n <= 100:
    n += 1
    output = ""
    for num in range(iteration):
        if n%toTest[num] == 0:
            outputIndex = num
            output += outputCanBe[outputIndex]
        else:
            output += str(n)  
        print(output)
        output = ""

So, basically, the issue is, in my for num in range(iteration), I am looping this action to check if the number might also be a multiple of 5 and 7, not just 3. However, this outputs results in numbers that are not multiples of 5 and 7, to print duplicates of themselves such as:

1
1
1
2
2
2
Fizz
3
3

This is undesired, how can I go about fixing this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Add the "Fizz" "Buzz" "Bizz" if the division is possible, at the end if nothing has been added, it means that you have to print the number itself.

n = 0
toTest = [
    3,
    5,
    7
]
outputCanBe = [
    "Fizz",
    "Buzz",
    "Bizz"
]
outputIndex = 0
iteration = (len(toTest)) 
while n <= 25:
    n += 1
    output = ""
    for num in range(iteration):
        if n%toTest[num] == 0:
            outputIndex = num
            output += outputCanBe[outputIndex]
    if not output:
        print(n)
    else:
        print(output)

EDIT :

Here’s a cleaner and shorter version :

words = {3: "Fizz", 5: "Buzz", 7: "Bizz"}
size = 100
for n in range(size):
    output = ""
    for (numb, word) in words.items():
        if n % numb == 0:
            output += word
    print(n) if not output else print(output)

I used a dictionnary to connect a numb (example : 3) and its word (example : "Fizz").

Doing a for loop is just for shorter code.

The .items() method is meant to unpack the (key,value) of a dictionnary.

Python consider that if a str is empty its bool value is False. If it’s not empty, no matter what it contains it’s True. That’s what the if not ouput is for, to check if output is empty (divided by none of these numbers) or not.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading