Skip to content

Instantly share code, notes, and snippets.

@curtisforrester
Created May 19, 2016 16:09
Show Gist options
  • Save curtisforrester/a3ac4afba18d7b5230264c708ece8a7d to your computer and use it in GitHub Desktop.
Save curtisforrester/a3ac4afba18d7b5230264c708ece8a7d to your computer and use it in GitHub Desktop.
Python FizzBuzz with modulo comparisons
import cProfile
import pstats
import StringIO
pr = cProfile.Profile()
pr.enable()
iNot = set()
iFizz = set()
iBuzz = set()
iFizzBuzz = set()
span = range(1, 101)
def calc2():
for num in span:
if num % 3.0 == 0 and num % 5.0 == 0:
iFizzBuzz.add(num)
elif num % 3.0 == 0:
iFizz.add(num)
elif num % 5.0 == 0:
iBuzz.add(num)
else:
iNot.add(num)
def calc1():
for num in span:
if num % 3.0 == 0 or num % 5.0 == 0:
if num % 3.0 == 0 and (num % 5.0 == 0):
iFizzBuzz.add(num)
elif num % 5.0 == 0:
iBuzz.add(num)
else:
iFizz.add(num)
else:
iNot.add(num)
def calc3():
for num in span:
is_mod3 = (num % 3.0 == 0)
is_mod5 = (num % 5.0 == 0)
if not (is_mod3 or is_mod5):
iNot.add(num)
elif is_mod3 and not is_mod5:
iFizz.add(num)
elif is_mod5 and not is_mod3:
iBuzz.add(num)
else:
iFizzBuzz.add(num)
def calc():
for num in span:
if (num % 3) == 0 and (num % 5 == 0):
iFizzBuzz.add(num)
elif num % 3 == 0:
iFizz.add(num)
elif num % 5 == 0:
iBuzz.add(num)
else:
iNot.add(num)
for i in xrange(0, 1000000):
iNot.clear()
iFizz.clear()
iBuzz.clear()
iFizzBuzz.clear()
calc()
pr.disable()
print "3's: {}".format(len(iFizz))
print "5's: {}".format(len(iBuzz))
print "both: {}".format(len(iFizzBuzz))
print "neither: {}".format(len(iNot))
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print s.getvalue()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment