So I don't want to go into whether this is the most perfect code for the FizzBuzz challenge.
For those unfamiliar with FizzBuzz, there are four rules in printing out a range of 1-100:
- Print out all numbers;
- If the number is divisible by 3, print "Fizz" instead;
- If the number is divisible by 5, print "Buzz" instead;
- If the number is divisible by both 3 and 5, print "FizzBuzz".)
I ran two implementations, to compare their speed:
# Code A
%%timeit
for i in range(1,10001):
if i % 15 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
# Code B
%%timeit
for i in range(1,10001):
if i % 5 == 0 and i % 3 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
Despite the extra if evaluation of Code B, it consistently ran quicker than Code A. Does a larger number result in a slower modulo? What is the underlying reason for this?