3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

srcgenを使って poor man's fizzbuzz

Posted at

srcgen を使って頭の悪いまじめな人が書くfizzbuzzを生成する。

# -*- 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)))

使い方

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

生成されたコード

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:
 # ... 省略
    elif n == 100:
        return 'buzz'
    else:
        raise NotImplementedError('hmm')

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

appendix

何か関数が大きすぎると解析の途中で失敗する?

$ python poormans_fizzbuzz.py 1 10000 > fizzbuzz.py
$ python fizzbuzz.py 
RuntimeError: maximum recursion depth exceeded during compilation
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?