[PYTHON] Write FizzBuzz using map (), reduce (), filter (), recursion

After practicing map (), reduce (), filter (), recursion, I wrote FizzBuzz using map (), reduce (), filter (), recursion.

First, I made a fizzbuzz (n) function.

def fizzbuzz(n):
  if (n % 15) == 0:
    return "FizzBuzz"
  elif (n % 3) == 0:
    return "Fizz"
  elif (n % 5) == 0:
    return "Buzz"
  else:
    return str(n)

map simply calls the above function.

for s in map(fizzbuzz,range(1,101)):
  print s

For reduce (), I made an mrg function.

def mrg(msg,n):
  msg = str(msg)
  if msg == '0':
    return str(fizzbuzz(n))
  else:
    return msg + '\n' + str(fizzbuzz(n))
print reduce(mrg,range(0,101))

About filter (), I wrote it quite forcibly. I wonder if there is a good way to write it.

ls = range(1,101)
msg = range(1,101)
for i in filter(lambda x: (x%3)==0,ls):
  msg[i-1] = "Fizz"
for i in  filter(lambda x: (x%5)==0,ls):
  if msg[i-1] == "Fizz":
    msg[i-1] += "Buzz"
  else:
    msg[i-1] = "Buzz"

for s in msg:
  print s

And recursion. This looks the simplest because there is no for.

START = 1
FINISH = 100
def fzbz(n):
  if n == FINISH:
    return fizzbuzz(n)
  else:
    return fizzbuzz(n)+"\n"+fzbz(n+1)
print fzbz(START)

Recommended Posts

Write FizzBuzz using map (), reduce (), filter (), recursion
Write FizzBuzz without using "="
Write test-driven FizzBuzz code using Python doctest.
Merge sort using recursion
Median filter using xarray (median filter)
Low-pass filter using closure