FizzBuzz

A FizzBuzz solution created using a test-driven development approach.

Solution #1 - inefficient

""" fizzbuzz1.py - experiment in TDD """

# usage: python3 fizzbuzz1.py


def fizzbuzz(natural_number):
    """ fizz if divisible by 3, buzz if divisible by 5 else natural_number """
    assert natural_number > 0
    return 'fizzbuzz' if natural_number % 15 == 0 else (
             'fizz' if natural_number % 3 == 0 else (
               'buzz' if natural_number % 5 == 0 else (
                 str(natural_number))))


if __name__ == '__main__':
    try:
        fizzbuzz(0)
    except AssertionError:
        pass
    else:
        raise AssertionError('Allowed a negative or zero argument.')

    assert fizzbuzz(1) == '1'
    assert fizzbuzz(2) == '2'
    assert fizzbuzz(3) == 'fizz'
    assert fizzbuzz(4) == '4'
    assert fizzbuzz(5) == 'buzz'
    assert fizzbuzz(6) == 'fizz'
    assert fizzbuzz(7) == '7'
    assert fizzbuzz(8) == '8'
    assert fizzbuzz(9) == 'fizz'
    assert fizzbuzz(10) == 'buzz'
    assert fizzbuzz(11) == '11'
    assert fizzbuzz(15) == 'fizzbuzz'

    print('tests passed')

Solution #2 - improved

""" fizzbuzz2.py """

# usage: python3 fizzbuzz2.py


def fizzbuzz(natural_number):
    """ fizz if divisible by 3, buzz if divisible by 5 else natural_number """
    assert natural_number > 0
    output = ''
    if natural_number % 3 == 0:
        output = 'fizz'
    if natural_number % 5 == 0:
        output += 'buzz'
    if output == '':
        output = str(natural_number)
    return output


if __name__ == '__main__':
    try:
        fizzbuzz(0)
    except AssertionError:
        pass
    else:
        raise AssertionError('Allowed a negative or zero argument.')

    assert fizzbuzz(1) == '1'
    assert fizzbuzz(2) == '2'
    assert fizzbuzz(3) == 'fizz'
    assert fizzbuzz(4) == '4'
    assert fizzbuzz(5) == 'buzz'
    assert fizzbuzz(6) == 'fizz'
    assert fizzbuzz(7) == '7'
    assert fizzbuzz(8) == '8'
    assert fizzbuzz(9) == 'fizz'
    assert fizzbuzz(10) == 'buzz'
    assert fizzbuzz(11) == '11'
    assert fizzbuzz(15) == 'fizzbuzz'

    print('tests passed')