3 ms·
The article conceit is fantastic. That said, is the going-in algo wrong? I see a case for 3 * 5 in here: for n in range(1, 101): if n % 15 == 0:
by Terretta 11mo ago
The article conceit is fantastic. That said, is the going-in algo wrong?
I see a case for 3 * 5 in here:
for n in range(1, 101):
if n % 15 == 0:
print('FizzBuzz')
elif n % 3 == 0:
print('Fizz')
elif n % 5 == 0:
print('Buzz')
else:
print(n)
Why?
If we add 'Bazz' for mod 7, are we going to hardcode:
for n in range(1, 105):
if n % 105 == 0: # 3 * 5 * 7
print('FizzBuzzBazz')
elif n % 15 == 0: # 3 * 5
print('FizzBuzz')
elif n % 21 == 0: # 3 * 7
print('FizzBazz')
elif n % 35 == 0: # 5 * 7
print('BuzzBazz')
elif n % 3 == 0:
print('Fizz')
elif n % 5 == 0:
print('Buzz')
elif n % 7 == 0:
print('Bazz')
else:
print(n)
Or should we have done something like:
for n in range(1, 105):
out = ''
if n % 3 == 0:
out += 'Fizz'
if n % 5 == 0:
out += 'Buzz'
if n % 7 == 0:
out += 'Bazz'
print(out or n)
I've been told sure, but that's a premature optimization, 3 factors wasn't in the spec. OK, but if we changed our minds on even one of the two factors, we're having to find and change 2 lines of code ... still seems off.
Sort of fun to muse whether almost all FizzBuzz implementations are a bit wrong.
- deleted 11mo ago[deleted]
- michaelcampbell 11mo ago> Sort of fun to muse whether almost all FizzBuzz implementations are a bit wrong. They're only wrong if they provide output that isn't in the spec. Adding "bazz" isn't in the spec, and assuming that something indeterminate MIGHT come later is also not part.
- Terretta 11mo agoYep, that's how people answer. Folks really really don't like thinking that "FizzBuzz" case maybe shouldn't be there, future extension or factor edit or no. // And as long as we're just manually computing factor times factor and typing out the results for it like "FizzBuzz" we might as well just hardcode the whole series...
- theendisney 11mo agoI think the reqirement should be to n digits. Then at least we can benchmark it.
- theendisney 11mo agoIf we are going to be like that we should just increment a var by 3,5 or 7 and compare it rather than %3 as the later seems expensive.