Created
March 28, 2016 15:34
-
-
Save anthonyclays/a16f22adaca2951e8f85 to your computer and use it in GitHub Desktop.
meta-FizzBuzz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I prefer
as the resulting code is more compact (linear in input size instead of combinatorial)