Skip to content

Instantly share code, notes, and snippets.

@curtisforrester
Created May 19, 2016 16:07
Show Gist options
  • Save curtisforrester/393a04a0e7c76f2f2e4366f5ad744f58 to your computer and use it in GitHub Desktop.
Save curtisforrester/393a04a0e7c76f2f2e4366f5ad744f58 to your computer and use it in GitHub Desktop.
Python FizzBuzz with lookup sets
import cProfile
import pstats
import StringIO
pr = cProfile.Profile()
pr.enable()
threes = {num for num in range(3, 100, 3)}
fives = {num for num in range(5, 100, 5)}
not_in = {num for num in range(1, 100) if num not in threes and num not in fives}
both = threes.intersection(fives)
iNot = set()
iFizz = set()
iBuzz = set()
iFizzBuzz = set()
span = range(1, 101)
def calc():
for num in span:
if num in not_in:
iNot.add(num)
elif num in both:
iFizzBuzz.add(num)
elif num in threes:
iFizz.add(num)
else:
iBuzz.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