Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
#!/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'))

This comment has been minimized.

Copy link

@wouterdb wouterdb commented Apr 18, 2019

I prefer

def make(nrs, strings):

        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 = ""
        if not out:
            out = str(i)

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