LoginSignup
5
2

More than 5 years have passed since last update.

Python で FizzBuzz / Sequence を作る

Last updated at Posted at 2019-02-02

@sdkei さんの「Kotlin で FizzBuzz / Sequence を使う」を真似できるかな? という出来心で・・・

Kotlin版
fun main() {
    (1..100)
        .map {
            when {
                it % (3 * 5) == 0 -> "FizzBuzz"
                it % 3 == 0 -> "Fizz"
                it % 5 == 0 -> "Buzz"
                else -> it.toString()
            }
        }
        .forEach {
            println(it)
        }
}
Python版
def main(): (
    seq(1, 100)
        .map (
            lambda it: (
                it % (3 * 5) == 0 and "FizzBuzz" or
                it % 3 == 0 and "Fizz" or
                it % 5 == 0 and "Buzz" or
                it
            )
        )
        .forEach (
            print
        )
)

class Sequence:

    def __init__(self, iterable):
        self.iterable = iterable

    def __iter__(self):
        return iter(self.iterable)

    def map(self, func):
        return Sequence(map(func, self.iterable))

    def forEach(self, func):
        for item in self.iterable:
            func(item)


def seq(start, stop=None, step=None):
    if stop is None:
        return Sequence(range(start))
    if step is None:
        step = 1
    return Sequence(range(start, stop + (-1, 1)[start <= stop], step))


if __name__ == '__main__':
    main()
5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2