Math Adventures with Python
An Illustrated Guide to Exploring Math with Code
楽天ブックス(Kobo)
紀伊国屋書店(Kinoppy)
開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
Math Adventures with Python: An Illustrated Guide to Exploring Math with Code (Peter Farrell(著)、No Starch Press)のPART Ⅰ(HITCHIN' UP YOUR PYTHON WAGON)、1(DRAWING POLYGONS WITH THE TURTLE MODULE)、EXERCISE1-4(POLYGON FUNCTIONS)の解答を求めてみる。
コード
Python 3
#!/usr/bin/env python3 import time import turtle # 保存用 import io from PIL import Image turtle.shape('turtle') turtle.speed(0) def polygon(sides=3, side_length=100): triangle_count = sides - 2 internal_angle = 180 * triangle_count / sides external_angle = 180 - internal_angle for _ in range(sides): turtle.forward(side_length) turtle.right(external_angle) colors = ['red', 'green', 'blue', 'orange', 'brown'] color_len = len(colors) for i, color in enumerate(colors): sides = color_len - i + 2 turtle.pencolor(color) side_length = 20 * sides for _ in range(3): polygon(sides, side_length) turtle.right(120) # 保存 ps = turtle.getscreen().getcanvas().postscript() with io.BytesIO() as buffer: buffer.write(ps.encode('ascii')) im = Image.open(buffer) im.save(f'sample4.png')
入出力結果(cmd(コマンドプロンプト)、Terminal、Jupyter(IPython))
$ python3 sample4.py $
0 コメント:
コメントを投稿