Created
December 19, 2024 18:50
-
-
Save saintsGrad15/f0e674621befce0ebbe2e05dd01f4ec0 to your computer and use it in GitHub Desktop.
First re-pass at FizzBuzz after an interview
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cache = {} | |
def fizz_buzz(n: int, factor_1: int = 3, factor_2: int = 5) -> None: | |
""" | |
Given an integer n, for a list of integers 1-n, the task is to print, | |
"FizzBuzz" if i is divisible by `factor_1` and `factor_2`, | |
"Fizz" if i is divisible by `factor_1`, | |
"Buzz" if i is divisible by `factor_2` | |
"i" as a string, if none of the conditions are true. | |
:param n: The upper limit, inclusive, of the range to evaluate | |
:param factor_1: The first factor | |
:param factor_2: The second factor | |
""" | |
common_factor = factor_1 * factor_2 | |
# Iterate over 1 to n, inclusive | |
for full_size_num in range(1, n + 1): | |
output = "" | |
# Calculate `constrained_num` as the remainder of `full_size_num` divided by `common_factor` | |
# i.e. 0 <= `constrained_num` < `common_factor` | |
if full_size_num > common_factor: | |
# Constrain `full_size_num` | |
constrained_num = full_size_num % common_factor | |
else: | |
# Do nothing | |
constrained_num = full_size_num | |
if full_size_num not in cache: | |
# `constrained_num` is NOT in `cache` | |
if constrained_num % factor_1 == 0: | |
output += "Fizz" | |
if constrained_num % factor_2 == 0: | |
output += "Buzz" | |
if len(output) < 1: | |
output = str(full_size_num) | |
# Add `output` to `cache` | |
cache[constrained_num] = output | |
else: | |
# `constrained_num` is already in `cache` | |
pass | |
print(cache[constrained_num]) | |
fizz_buzz(61) | |
## Output | |
# 1 | |
# 2 | |
# Fizz | |
# 4 | |
# Buzz | |
# Fizz | |
# 7 | |
# 8 | |
# Fizz | |
# Buzz | |
# 11 | |
# Fizz | |
# 13 | |
# 14 | |
# FizzBuzz | |
# 16 | |
# 17 | |
# Fizz | |
# 19 | |
# Buzz | |
# Fizz | |
# 22 | |
# 23 | |
# Fizz | |
# Buzz | |
# 26 | |
# Fizz | |
# 28 | |
# 29 | |
# FizzBuzz | |
# 31 | |
# 32 | |
# Fizz | |
# 34 | |
# Buzz | |
# Fizz | |
# 37 | |
# 38 | |
# Fizz | |
# Buzz | |
# 41 | |
# Fizz | |
# 43 | |
# 44 | |
# FizzBuzz | |
# 46 | |
# 47 | |
# Fizz | |
# 49 | |
# Buzz | |
# Fizz | |
# 52 | |
# 53 | |
# Fizz | |
# Buzz | |
# 56 | |
# Fizz | |
# 58 | |
# 59 | |
# FizzBuzz | |
# 61 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment