by strogonoff · 5y ago · 0 comments
for i in range(1, 100):
divisible_by_3 = i % 3 == 0
divisible_by_5 = i % 5 == 0
fizz = 'Fizz' if divisible_by_3 else ''
buzz = 'Buzz' if divisible_by_5 else ''
num = '' if divisible_by_3 or divisible_by_5 else i
print "{0}{1}{2}".format(fizz, buzz, num)
(In reality, of course, I would likely have had to look up the modulo operator first.)I was not disappointed.
> Meanwhile, we want there to be at most one place that outputs fizz, buzz, or the string representation, and each test to be performed only once.
These do intuitively seem like the properties of an elegant solution.
for (let i = 1; i <= 100; i++) {
console.log(
(i % 3 == 0 ? "Fizz" : "") + (i % 5 == 0 ? "Buzz" : "")
|| i
);
}
Whether or not you consider this more elegant is a matter of taste, though. fizzbuzz n = case (n^4 `mod` 15) of
1 -> show n
6 -> "fizz"
10 -> "buzz"
0 -> "fizzbuzz"
main :: IO ()
main = print $ map fizzbuzz [1..30]I think it is an elegant solution.
import functools
def fizzbuzz(n):
if not n % 3: yield (r := "fizz")
if not n % 5: yield (r := "buzz")
if not "r" in locals(): yield n
compose = lambda f, g: lambda *args: f(g(*args))
functions = "".join, functools.partial(map, str), fizzbuzz
transform = functools.reduce(compose, functions)
print("\n".join(map(transform, range(1, 100)))) import itertools
# this block is just for simple functional pipes
class B:
def __init__(self, f): self.f = f
class Pipe (B): __ror__ = lambda self, x: self.f(x)
class Map (B): __ror__ = lambda self, x: map (self.f, x)
class MapValues(B): __ror__ = lambda self, it: it | Map(lambda kv: (kv[0], self.f(kv[1])))
# here the actual FizzBuzz
(
range(1, 100)
| Map(lambda i: (i, itertools.compress(('Fizz', 'Buzz'), (i % 3 == 0, i % 5 == 0))))
| MapValues(''.join)
| Map(lambda kv: kv[1] or kv[0])
| Pipe(list)
)
[1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz', 16, 17, ... ]
if you're interested in pipes like above - here my simple library for that (no install needed, just copy some lines)