[PYTHON] poor man's fizzbuzz using srcgen

Use srcgen to generate a fizzbuzz written by a dumb and serious person.

# -*- coding:utf-8 -*-
from srcgen.python import PythonModule

m = PythonModule()


def fizzbuzz(i):
    r = []
    if i % 3 == 0:
        r.append("fizz")
    if i % 5 == 0:
        r.append("buzz")
    return "".join(r) if r else i


def genfizzbuzz(m, beg, end):
    def genfn():
        with m.def_("fizzbuzz", "n"):
            with m.if_("n == {}".format(beg)):
                m.return_(repr(fizzbuzz(beg)))

            for i in range(beg + 1, end + 1):
                with m.elif_("n == {}".format(i)):
                    m.return_(repr(fizzbuzz(i)))

            with m.else_():
                m.raise_("NotImplementedError('hmm')")

    def genmain():
        with m.if_("__name__ == '__main__'"):
            m.import_("sys")
            m.stmt("print(fizzbuzz(int(sys.argv[1])))")
    genfn()
    genmain()
    return m


if __name__ == "__main__":
    import sys
    try:
        beg, end = sys.argv[1:]
    except ValueError:
        beg, end = 1, 100
    m = PythonModule()
    print(genfizzbuzz(m, int(beg), int(end)))

How to use

$ python poormans_fizzbuzz.py 1 100 > fizzbuzz.py
$ python fizzbuzz.py 3
fizz

Generated code

def fizzbuzz(n):
    if n == 1:
        return 1
    elif n == 2:
        return 2
    elif n == 3:
        return 'fizz'
    elif n == 4:
        return 4
    elif n == 5:
        return 'buzz'
    elif n == 6:
 # ...abridgement
    elif n == 100:
        return 'buzz'
    else:
        raise NotImplementedError('hmm')

if __name__ == '__main__':
    import sys
    print(fizzbuzz(int(sys.argv[1])))

appendix

If any function is too big, will it fail in the middle of the analysis?

$ python poormans_fizzbuzz.py 1 10000 > fizzbuzz.py
$ python fizzbuzz.py 
RuntimeError: maximum recursion depth exceeded during compilation

Recommended Posts

poor man's fizzbuzz using srcgen
Write FizzBuzz without using "="