Day 4 - Python

Problem Statement: FIZZBUZZ

You are given a number N. Your task is to implement a function fizzbuzz(N) that generates the following lists:

  • A list of numbers divisible by 3 and 5, denoted as "FizzBuzz".
  • A list of numbers divisible by only 3, denoted as "Fizz".
  • A list of numbers divisible by only 5, denoted as "Buzz".

Your function should return a dictionary containing these lists.

Function Signature:

def fizzbuzz(n: int) -> dict:

    pass

Input:

An integer N representing the upper limit (inclusive) of the range of numbers to consider.

Output:

A dictionary containing three keys:

"FizzBuzz": A list of integers divisible by both 3 and 5.

"Fizz": A list of integers divisible by only 3.

"Buzz": A list of integers divisible by only 5.

Constraints:

1 ≤ N ≤ 10^5

Example:

Input:

15

Output:

{'FizzBuzz': [15], 'Fizz': [3, 6, 9, 12], 'Buzz': [5, 10]}

Explanation:

Numbers from 1 to 15 are considered.

3, 6, 9, and 12 are divisible by 3 (hence listed under "Fizz").

5 and 10 are divisible by 5 (hence listed under "Buzz").

15 is divisible by both 3 and 5 (hence listed under "FizzBuzz").


SOLUTION

def fizzbuzz(n):

    result = {"FizzBuzz": [], "Fizz": [], "Buzz": []}

    for i in range(1, n+1):

        if i % 3 == 0 and i % 5 == 0:

            result["FizzBuzz"].append(i)

        elif i % 3 == 0:

            result["Fizz"].append(i)

        elif i % 5 == 0:

            result["Buzz"].append(i)

    return result


n = int(input())

output = fizzbuzz(n)


print(output)


Insights:

  1. Check if the input provided is a positive integer. The function should handle invalid inputs gracefully. Test the input with simple if else in main method. Give a try!
  2. Append the numbers to the corresponding lists based on their divisibility.
  3. Think why the for loop is from 1 to n+1 and not 0 to n.
  4. Change the order of the if else and check whether you are encountering any logical errors.
  5. Make sure that the function is returning a dictionary and not list or string. If so, the test case will not be passed.
  6. Try converting the dictionary into a DataFrame using Pandas and print in the tabular format. Use necessary pre-processing for the same!
  7. Have a careful and thorough look over the constraints and the sample test cases. 

Enjoy Coding! :)

Comments