Day 96 - Coding Interview Question [FizzBuzz]

FizzBuzz is a group word game for children to teach them about division. What happens is that players take turns to count numbers incrementally with replacing every number divisible by 3 with the word "Fizz" and the number divisible by 5 with the word "Buzz". Besides being a game for children it is also a common coding interview question to test how much does one understands the programming concepts. I will be implementing FizzBuzz in python in this post.

I will also be trying to make it as small as possible.

for i in range(100):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Here it first checks for whether the number i is divisible by both 3 and 5 and if it does it prints both words "FizzBuzz" else it will print "Fizz" if the number is divisible by 3 and "Buzz" if the word is divisible by 5.

Making it even shorter by using ternary operators in python.

for i in range(100):
    print("FizzBuzz") if i % 3 == 0 and i % 5 == 0 else \
    print("Fizz") if i % 3 == 0 else \
    print("Buzz") if i % 5 == 0 else print(i)

    # Forward Slashes here let us brake
    # a big python line into smaller lines

Now converting this to functions.

def fizz_buzz(num_1, num_2, lim):
    for i in range(lim):
        print("FizzBuzz") if i % num_1 == 0 and i % num_2 == 0 else \
        print("Fizz") if i % num_1 == 0 else \
        print("Buzz") if i % num_2 == 0 else print(i)

def main():
    fizz_buzz(3,5,100)
    return

if __name__ == "__main__":
    main()

Following is the same approach to solve FizzBuzz in Javascript.

for (let i = 1; i <= 100; i++) {
  i % 3 === 0 && i % 5 === 0
    ? console.log("FizzBuzz")
    : i % 3 === 0
    ? console.log("Fizz")
    : i % 5 === 0
    ? console.log("Buzz")
    : console.log(i);
}

zainscizainsci