-
Notifications
You must be signed in to change notification settings - Fork 247
FizzBuzz
Sar Champagne Bielert edited this page Apr 8, 2024
·
6 revisions
Unit 1 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Will
n
always be a positive integer?- Yes.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Loop through each number less than or equal to n
, printing the appropriate result for each number.
1) Loop from 1 to `n` (inclusive)
a) If the number is evenly divisible by both 3 and 5, print "Fizzbuzz"
b) If the number is evenly divisible by 3, print "Fizz"
c) If the number is evenly divisible by 5, print "Buzz"
d) Otherwise, print the number
- A number is "evenly divisible" when the remainder of the division is zero. How can we check for that in python?
def fizzbuzz(n):
for i in range(1, n + 1):
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)
Alternative solution:
def fizzbuzz(n):
for i in range(1, n + 1):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)