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 (プログラミング言語)
- Processing 3 (プログラミング言語、統合開発環境、グラフィック機能)
Math Adventures with Python: An Illustrated Guide to Exploring Math with Code (Peter Farrell(著)、No Starch Press)のPART 3(BLAZING YOUR OWN TRAIL)、11(CELLULAR AUTOMATA)、EXERCISE 11-1(MANUALLY GROWING THE CA)の解答を求めてみる。
コード
Python 3
SIZE = 0 GRID_W = 51 GRID_H = 51 cell_list = [] generation = 0 def setup(): global SIZE, cell_list size(600, 600) noStroke() SIZE = width // GRID_W + 1 cell_list = create_cell_list() def draw(): global generation, cell_list for row in cell_list: for cell in row: cell.display() def update(cell_list): new_list = [[Cell(c, r, cell.check_neighbors(cell_list)) for c, cell in enumerate(row)] for r, row in enumerate(cell_list)] return new_list def create_cell_list(): new_list = [[Cell(i, j, 0) for i in range(GRID_W)] for j in range(GRID_H)] new_list[GRID_H // 2][GRID_W // 2].state = 1 return new_list class Cell: def __init__(self, c, r, state=0): self.c = c self.r = r self.state = state def display(self): if self.state == 1: fill(0) else: fill(255) rect(SIZE * self.r, SIZE * self.c, SIZE, SIZE) def check_neighbors(self, cell_list): if self.state == 1: return 1 neighbs = 0 for dr, dc in [[-1, 0], [1, 0], [0, -1], [0, 1]]: try: if cell_list[self.r + dr][self.c + dc].state == 1: neighbs += 1 except IndexError: pass if neighbs in [1, 4]: return 1 return 0 def __repr__(self): return 'Cell(' + str(self.c) + ',' + str(self.r) + ',' + \ str(self.state) + ')' def keyPressed(): global generation, cell_list print(generation) if key == CODED: cell_list = update(cell_list) generation += 1
入出力結果(cmd(コマンドプロンプト)、Terminal、Jupyter(IPython))
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
0 コメント:
コメントを投稿