如何修改create_initial_grid函数,基于坐标列表初始化细胞初始位置
Fixing
create_initial_grid to Use Specified Coordinates from katt.txt Got it, let's adjust your Game of Life code so the initial grid uses the coordinates from katt.txt instead of random generation. Here are the key fixes and the full corrected code:
Key Modifications
- Convert coordinates to a set: The original
zip()returns an iterator, which can only be used once. Using aset()lets us reuse the coordinates and makes membership checks way faster. - Fix row/column iteration: The original
create_initial_gridhad a bug where it iterated over columns for rows (usingrange(cols)instead ofrange(rows)), which would break grids where rows ≠ cols. - Proper coordinate matching: The function now correctly maps each (row, column) pair from the coordinate set to live cells in the grid.
Corrected Full Code
import time # Read coordinates from katt.txt and store as a set for fast lookups with open('katt.txt') as f: numbers = [int(elem) for elem in f.read().split()] # Convert to a set to avoid iterator exhaustion and enable O(1) lookups coordinates = set(zip(numbers[::2], numbers[1::2])) def create_initial_grid(rows, cols, coordinates): # Initialize grid: 1 if (row, col) is in coordinates, else 0 return [[1 if (x, y) in coordinates else 0 for y in range(cols)] for x in range(rows)] def print_grid(rows, cols, grid, generation): output_str = "" output_str += "Generation {0} - To exit the program early press <Ctrl-C>\n\r".format(generation) for row in range(rows): for col in range(cols): output_str += "*" if grid[row][col] == 1 else "-" output_str += "\n\r" print(output_str, end=" ") def create_next_grid(rows, cols, grid, next_grid): for row in range(rows): for col in range(cols): live_neighbors = get_live_neighbors(row, col, rows, cols, grid) if live_neighbors < 2 or live_neighbors > 3: next_grid[row][col] = 0 elif live_neighbors == 3 and grid[row][col] == 0: next_grid[row][col] = 1 else: next_grid[row][col] = grid[row][col] def get_live_neighbors(row, col, rows, cols, grid): life_sum = 0 for i in range(-1, 2): for j in range(-1, 2): if not (i == 0 and j == 0): life_sum += grid[((row + i) % rows)][((col + j) % cols)] return life_sum def grid_changing(rows, cols, grid, next_grid): for row in range(rows): for col in range(cols): if grid[row][col] != next_grid[row][col]: return True return False def get_integer_value(prompt, low, high): while True: try: value = int(input(prompt)) except ValueError: print("Input was not a valid integer value.") continue if value < low or value > high: print(f"Input was not inside the bounds (value < {low} or value > {high}).") else: break return value def run_game(): rows = get_integer_value("Enter the number of rows (10-30): ", 10, 30) cols = get_integer_value("Enter the number of cols (10-30): ", 10, 30) generations = get_integer_value("Enter the number of generations (1-100000): ", 1, 100000) # Initialize grids: current uses the coordinates, next starts as a blank grid current_generation = create_initial_grid(rows, cols, coordinates) next_generation = [[0 for _ in range(cols)] for _ in range(rows)] gen = 1 for gen in range(1, generations + 1): if not grid_changing(rows, cols, current_generation, next_generation): break print_grid(rows, cols, current_generation, gen) create_next_grid(rows, cols, current_generation, next_generation) time.sleep(1 / 5.0) # Swap grids for next iteration current_generation, next_generation = next_generation, current_generation print_grid(rows, cols, current_generation, gen) input("Press <Enter> to exit.") # Start the Game of Life run_game()
Additional Notes
- Any coordinates from
katt.txtthat fall outside the user-specified grid dimensions (rows/cols) will be ignored (since those positions don't exist in the grid). - Using a
setfor coordinates ensures that checking if a cell should be live is almost instant, which is better for performance than using a list or iterator.
内容的提问来源于stack exchange,提问作者MaxR
相关产品推荐
相关产品推荐

