Edited at

Python で FizzBuzz / Sequence を作る

@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()