|
| 1 | +# https://en.wikipedia.org/wiki/Fizz_buzz#Programming |
| 2 | + |
| 3 | + |
| 4 | +def fizz_buzz(number: int, iterations: int) -> str: |
| 5 | + """ |
| 6 | + Plays FizzBuzz. |
| 7 | + Prints Fizz if number is a multiple of 3. |
| 8 | + Prints Buzz if its a multiple of 5. |
| 9 | + Prints FizzBuzz if its a multiple of both 3 and 5 or 15. |
| 10 | + Else Prints The Number Itself. |
| 11 | + >>> fizz_buzz(1,7) |
| 12 | + '1 2 Fizz 4 Buzz Fizz 7 ' |
| 13 | + >>> fizz_buzz(1,0) |
| 14 | + Traceback (most recent call last): |
| 15 | + ... |
| 16 | + ValueError: Iterations must be done more than 0 times to play FizzBuzz |
| 17 | + >>> fizz_buzz(-5,5) |
| 18 | + Traceback (most recent call last): |
| 19 | + ... |
| 20 | + ValueError: starting number must be |
| 21 | + and integer and be more than 0 |
| 22 | + >>> fizz_buzz(10,-5) |
| 23 | + Traceback (most recent call last): |
| 24 | + ... |
| 25 | + ValueError: Iterations must be done more than 0 times to play FizzBuzz |
| 26 | + >>> fizz_buzz(1.5,5) |
| 27 | + Traceback (most recent call last): |
| 28 | + ... |
| 29 | + ValueError: starting number must be |
| 30 | + and integer and be more than 0 |
| 31 | + >>> fizz_buzz(1,5.5) |
| 32 | + Traceback (most recent call last): |
| 33 | + ... |
| 34 | + ValueError: iterations must be defined as integers |
| 35 | + """ |
| 36 | + |
| 37 | + if not type(iterations) == int: |
| 38 | + raise ValueError("iterations must be defined as integers") |
| 39 | + if not type(number) == int or not number >= 1: |
| 40 | + raise ValueError( |
| 41 | + """starting number must be |
| 42 | + and integer and be more than 0""" |
| 43 | + ) |
| 44 | + if not iterations >= 1: |
| 45 | + raise ValueError("Iterations must be done more than 0 times to play FizzBuzz") |
| 46 | + |
| 47 | + out = "" |
| 48 | + while number <= iterations: |
| 49 | + if number % 3 == 0: |
| 50 | + out += "Fizz" |
| 51 | + if number % 5 == 0: |
| 52 | + out += "Buzz" |
| 53 | + if not number % 3 == 0 and not number % 5 == 0: |
| 54 | + out += str(number) |
| 55 | + |
| 56 | + # print(out) |
| 57 | + number += 1 |
| 58 | + out += " " |
| 59 | + return out |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + import doctest |
| 64 | + |
| 65 | + doctest.testmod() |
0 commit comments