8 points · by viebel · 10y ago · 16 comments
from itertools import cycle, imap, count, islice
from operator import add
def fizzbuzz(n):
fizzes = cycle(["", "", "Fizz"])
buzzes = cycle(["", "", "", "", "Buzz"])
words = imap(add, fizzes, buzzes)
numbers = imap(str, count(1))
_fizzbuzz = imap(max, words, numbers)
return list(islice(_fizzbuzz, n))While it doesn't use the spiffy lazy lists of itertools, and does have the typical "if x % n == 0" test, it does generalize easily to the "and print Baz every 37th number" case.
def joinmap(func, elements, separator):
return separator.join(map(func, elements))
def fb_value(x, fb={3:'Fizz', 5:'Buzz'}):
words = joinmap(lambda n: fb[n] if x % n == 0 else '', fb.keys(), '')
return words if words else str(x)
def fb_range(low=1, high=100):
return joinmap(fb_value, range(low, 1 + high), '\n')
print fb_range()Treating a dictionary as an iterator automatically iterates over its .keys(), so you can remove the .keys() in fb.keys() and just map over fb itself.
>>> map(lambda x: x+x, {2: "who", 4: "do", 6: "we", 8: "appreciate"})
[16, 4, 8, 12]
A problem that this highlights is that the order in which the Fizz and Buzz and other strings get concatenated depends on the order of the underlying dictionary hash, which can be thought of as random. In Python 3 it even changes from run to run.
https://docs.python.org/3/whatsnew/3.3.html#summary-release-...
$ python3 -c 'print(list({"foo": "bar", "baz": "qux"}))'
['foo', 'baz']
$ python3 -c 'print(list({"foo": "bar", "baz": "qux"}))'
['baz', 'foo']
For predictable behavior across larger sets of divisors, and for consistent behavior on Python 3, you'd probably want to use collections.OrderedDict.
(Except infix/prefix)
Take a look here: http://blog.klipse.tech/klipse/2016/09/09/klipse-languages.h...
But unfortunately, itertools is not (yet?) supported by skulpt :(
(with-out-str (doseq [n (range 1 11)]
(println
(match [(mod n 3) (mod n 5)]
[0 0] "FizzBuzz"
[0 _] "Fizz"
[_ 0] "Buzz"
:else n)))) object Fizzbuzz
{
val fizzes = List (None, None, Some ("Fizz")).toStream;
val buzzes = List (None, None, None, None, Some ("Buzz")).toStream;
val reducer : (Option[String], Option[String]) => Option[String] =
(a, b) => Option ((a ++ b).mkString).filterNot (_.isEmpty);
def apply (amount : Int) : Seq[String] =
Stream.continually (fizzes)
.flatten
.zip (Stream.continually (buzzes).flatten)
.map (reducer.tupled)
.zipWithIndex
.map {
case (s, n) => s.getOrElse ((n + 1).toString);
}
.take (amount);
}
Fizzbuzz (100).foreach (println)However, below is another version which employs idioms more commonly found:
object Fizzbuzz
{
val fizzes = None :: None :: Some ("Fizz") :: Nil;
val buzzes = None :: None :: None :: None :: Some ("Buzz") :: Nil;
def apply (amount : Int) : TraversableOnce[String] =
{
val alternates = Stream.continually (fizzes).flatten
.zip (Stream.continually (buzzes).flatten)
.take (amount)
.toArray;
0.until (amount).map { n =>
alternates (n) match {
case (Some (f), Some (b)) => f + b;
case (Some (f), None) => f;
case (None, Some (b)) => b;
case _ => (n + 1).toString
}
}
}
}
Fizzbuzz (100).foreach (println);But still I prefer the clojure version using pattern matching over the scala one: http://blog.klipse.tech/clojure/2016/10/25/core-match.html#f...
But I think that the point of functional programming is to provide a layer of programming that exposes a clean API. You know: now side effects, no global variables etc..
And maybe: no if!