Skip to content

Instantly share code, notes, and snippets.

@anthonyclays
Created March 28, 2016 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonyclays/a16f22adaca2951e8f85 to your computer and use it in GitHub Desktop.
Save anthonyclays/a16f22adaca2951e8f85 to your computer and use it in GitHub Desktop.
meta-FizzBuzz
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from itertools import combinations
from operator import mul
def all_combinations(things):
for i in xrange(len(things), 0, -1):
for result in combinations(things, i):
yield result
def fizzbuzz(nums, strs):
assert len(nums) == len(strs)
n = reduce(mul, nums, 1) # n = prod(nums)
print 'def fizzbuzz(nums, strs, n):\n for i in xrange(1, n+1):\n if False: pass'
for (ns, ss) in zip(all_combinations(nums), all_combinations(strs)):
print ' elif ' + ' and '.join('i % {} == 0'.format(num) for num in ns) + ':'
print ' print \'' + ''.join(str(s) for s in ss) + '\''
print ' else: print i'
print 'fizzbuzz({nums}, {strs}, {n})'.format(**locals())
fizzbuzz((3, 5, 7, 11, 17), ('Fizz', 'Buzz', 'Foo', 'Bar', 'Quux'))
@wouterdb
Copy link

I prefer

def make(nrs, strings):

    body="\n".join(f"""
        if i % {nr} == 0:
            out += "{string}\"""" for nr,string in zip(nrs, strings))

    print(f"""def fixbuzz(n):
    for i in xrange(1, n+1):
        out = ""
        {body}
        
        if not out:
            out = str(i)
        
        print(out)
    """)

make((3, 5, 7, 11, 17), ('Fizz', 'Buzz', 'Foo', 'Bar', 'Quux'))

as the resulting code is more compact (linear in input size instead of combinatorial)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment