fork download
  1. #!/usr/bin/env python3
  2.  
  3. from PIL import Image, ImageDraw
  4. from functools import reduce
  5.  
  6. # ニュートン法はfunctools.reduceを使った方がシンプルに書ける
  7. def newton(x):
  8. return reduce(lambda j, i: j - (j**3 - 1) / (3 * j**2), range(10), x)
  9.  
  10. def plot(draw, s):
  11. tpl = (255, 0, 0)
  12. # 右辺のtplの「回転結果」のリスト要素は左辺に「構造化代入」される
  13. red, green, blue = [tpl[i:] + tpl[:i] for i in range(3, 0, -1)]
  14. # ローカル関数fooを定義する
  15. def foo(x, y):
  16. # Pythonはマトモなスコープが無いので、ローカル関数から数値等の単項データ
  17. # (この場合はs)を参照出来ないので、nonlocal宣言を使う
  18. nonlocal s
  19. # hs の定義はローカル関数内にあった方がいい(ここ以外では使われていない)
  20. hs = s // 2
  21. z = newton(complex(x - hs + 0.5, -y + hs + 0.5) / s * 4)
  22. # 条件分岐「文」ではなく、条件分岐「式」に慣れよう
  23. return red if z.real > 0 else \
  24. green if z.real < 0 and z.imag > 0 else \
  25. blue
  26. # Pythonではfor文を使うよりリスト内包表記を使った方がスマートだ
  27. [draw.rectangle([x, y, x + 1, y + 1], fill = foo(x, y)) \
  28. for y in range(s) for x in range(s)]
  29.  
  30. # スクリプトとして起動する
  31. if __name__ == '__main__':
  32. size = 512
  33. img = Image.new('RGB', (size, size))
  34. plot(ImageDraw.Draw(img), size)
  35. img.show()
  36. img.save('img.png')
  37.  
Runtime error #stdin #stdout #stderr 2.95s 32344KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "./prog.py", line 36, in <module>
  File "/usr/local/lib/python3.9/dist-packages/PIL/Image.py", line 2237, in save
    fp = builtins.open(filename, "w+b")
PermissionError: [Errno 13] Permission denied: 'img.png'