![]() I would not have code top-level like you have it here. It's gathering information then returning a decision. I'd also rename update, as is isn't actually updating anything. You could also clean up that long list comprehension guard by creating a is_inbounds function that checks if a point is i bounds or not. I would make that an external function, and I would call it n_neighbors or count_neighbors or something similar to make it clearer that it's a function that counts neighbors, not a collection of neighbors. You do break some of that functionality off into a local function neighbors, but I don't think it's ideal the way you've done it. I would, for example, create a function called should_live or something similar that is passed the cell's current state and number of neighbors, and returns if the cell should be alive the next tick or not. I think that function is far too large, and doing too much explicitly. For the most part, you have everything tucked inside of update. I don't think you're making good use of functions here. I'm on my phone, so I can't write anything too elaborate. Neighbors = convolve(universe, kernel, mode='constant')Īlive = np.logical_or(np.logical_and(universe=1, neighbors=2), neighbors=3) You could write this using np.where and like so: import numpy as np These libraries are full of functions for operating on arrays. New_val = 1 # birth (or no change if already a 1) Maybe rearrange it to make it easier to understand when you look at it in a year: if num_neighbors = 2: I took awhile to understand the logic for setting new_val. Just pass in the generator, a la: num_neighbours = sum(universe for i in neighbors(x, y)) Return sum(universe(nx, ny) for nx,ny in xy if 0<=nx<=ny ![]() They are generally good for very short functions to pass as an argument to another function. If you want to give the function a name, then it shouldn't be a lambda. New_universe = update(universe, x, y)Īni = animation.FuncAnimation(fig, update_figure, blit=True) If universe and not 2 <= num_neighbours <= 3: Num_neighbours = sum( for i in neighbors(x, y)]) Neighbors = lambda x, y: [(x2, y2) for x2 in range(x - 1, x + 2) Universe = np.zeros((size_grid_x, size_grid_y)) I am very curious, if this code follows common best practices and I am wondering how to improve the code in terms of performance and readability. As a practice exercise, I implemented a cellular automaton (Conway's Game of Life) in python (with help from this tutorial). ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |