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-5(TURTLE SPIRAL)の解答を求めてみる。
コード
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) def square(side_length=100): return polygon(4, side_length=side_length) side_length = 5 for _ in range(60): print(side_length) square(side_length) turtle.right(5) side_length += 5 # 保存 ps = turtle.getscreen().getcanvas().postscript() with io.BytesIO() as buffer: buffer.write(ps.encode('ascii')) im = Image.open(buffer) im.save(f'sample5.png')
入出力結果(cmd(コマンドプロンプト)、Terminal、Jupyter(IPython))
$ python3 sample5.py 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175 180 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260 265 270 275 280 285 290 295 300 $
0 コメント:
コメントを投稿