4 ms·
Nice idea. Here is the (rough) equivalent in Python. from itertools import cycle fizz = cycle(['', '', 'Fizz']) buzz = cycle(['', '', '', '', 'Buzz'])
by jamesdhutton 7y ago
Nice idea. Here is the (rough) equivalent in Python.
from itertools import cycle
fizz = cycle(['', '', 'Fizz'])
buzz = cycle(['', '', '', '', 'Buzz'])
for n in range(1, 100):
fizzbuzz = next(fizz) + next(buzz)
print (fizzbuzz if fizzbuzz else n)
- _old_dude_ 7y agoAnd the one in Java, less cool because neither cycle nor zip exist :( <T> Iterator<T> cycle(List<T> list) { return IntStream.iterate(0, x -> (x + 1) % list.size()).mapToObj(list::get).iterator(); } <T, U, V> Iterator<V> zip(Iterator<T> it1, Iterator<U> it2, BiFunction<T,U,V> merger) { return Stream.generate(() -> merger.apply(it1.next(), it2.next())).iterator(); } var fizz = cycle(List.of("Fizz", "", "")); var buzz = cycle(List.of("Buzz", "", "", "", "")); var ints = IntStream.iterate(0, x -> x + 1).boxed().iterator(); var fizzbuzz = zip( zip(fizz, buzz, String::concat), ints, (f, i) -> f.isEmpty()? "" + i: f); Stream.generate(fizzbuzz::next).skip(1).limit(100) .forEach(System.out::println);
- deleted 7y ago[deleted]
- kortilla 7y agoConditionals are so 2019. from itertools import cycle fizz = cycle([lambda x: ''] * 2 + [lambda x: 'Fizz']) buzz = cycle([lambda x: ''] * 4 + [lambda x: 'Buzz']) numb = cycle([lambda x: x] * 2 + [lambda x: '', lambda x: x, lambda x: '']) for n in range(1, 100): print(next(fizz)(n) + next(buzz)(n) + next(buzz)(n))
- twa927 7y agoThat's very nice code and Python is non-functional. I love its generators. That's my version to make it more "functional": from itertools import cycle, islice from operator import add fizz = cycle(['', '', 'Fizz']) buzz = cycle(['', '', '', '', 'Buzz']) strings = map(add, fizz, buzz) strings_or_nos = (s or i for i, s in enumerate(strings, start=1)) print(list(islice(strings_or_nos, 100)))
- raverbashing 7y agoCool, you just need to join the list with '\n' before printing ;)
- Skunkleton 7y agoThis is where I ended up: from itertools import islice, cycle print("\n".join(islice(( f + b if f or b else str(i+1) for i, (f, b) in enumerate( zip(cycle(["", "", "Fizz"]), cycle(["", "", "", "", "Buzz"])) )), 100)))
- kbob 7y agoHere's my somewhat obfuscated version of same. https://gist.github.com/kbob/f46776fdc950e6a948b04c76bc23e874 https://gist.github.com/kbob/f46776fdc950e6a948b04c76bc23e87...