4 ms·
If you don't know about modulus, you don't have to re-implement it. For Fizzbuzz you're looping anyway, so you can just maintain two counters, one that counts t
by benhoyt 10y ago
If you don't know about modulus, you don't have to re-implement it. For Fizzbuzz you're looping anyway, so you can just maintain two counters, one that counts to 3 and resets, and one that counts to 5 and resets. When one of the counters resets, you know the main loop counter is a multiple of 3 or 5. Like so:
def fizzbuzz_no_modulo():
counter_three = 1
counter_five = 1
for i in range(1, 101):
output = []
if counter_three == 3:
output.append('Fizz')
counter_three = 0
if counter_five == 5:
output.append('Buzz')
counter_five = 0
if not output:
output.append(str(i))
print(''.join(output))
counter_three += 1
counter_five += 1
- squeaky-clean 10y agoThere's a lot of ways you can do it. I think it's fun to see how people solve it when they're not allowed to use the obvious answers (note: I don't interview people and probably would not choose no-modulo-fizzbuzz as an interview question). Similar to your solution, instead of two counters, you can have two iterators that cycle every 3 / 5 elements, and add them. Then fill in any blank elements with their index+1. from itertools import cycle, zip_longest, islice fizz_list = ['', '', 'fizz'] buzz_list = ['', '', '', '', 'buzz'] output = [ fizz + buzz for fizz, buzz in islice(zip_longest(cycle(fizz_list), cycle(buzz_list)), 0, 100) ] for i in range(len(output)): print(output[i] or i+1)