【Cython】AtCoderでnumpyを使う方法


はじめに

※AtCoderでのCythonについての記事は以下に書きました:

AtCoderのCythonでnumpyを使う方法の備忘録です。

フォーマット

以下のsetup.pyでコンパイルするフォーマットをPythonで実行することでnumpyを使用できます:

import sys
if sys.argv[-1] == 'ONLINE_JUDGE':
  mycode = r'''
# distutils: language = c++
# cython: language_level = 3
cimport numpy as np # numpyが使える!!
def main():
  pass # ここに書く
if __name__ == 'mycode':
  main()
'''
  with open('mycode.pyx', 'w') as f:
    f.write(mycode)
  setup = r'''
from distutils.core import setup, Extension
from Cython.Build import cythonize
from numpy import get_include
ext = Extension('mycode', sources = ['mycode.pyx'], include_dirs = ['.', get_include()])
setup(name = 'mycode', ext_modules = cythonize([ext]))
'''
  with open('setup.py', 'w') as f:
    f.write(setup)
  import subprocess
  with open('error.txt', 'w') as ef:
    code = subprocess.run('python3.8 setup.py build_ext --inplace'.split(), stderr = ef).returncode
  if code:
    with open('error.txt', 'r') as ef:
      with open('mycode.py', 'w') as f:
        f.write(f'''
import sys
sys.stderr.write("""{ef.read()}""")
exit({code})
''')
  exit()
import mycode