1. """模拟生命繁衍"""
    2. import itertools
    3. def get_board(size, alive_cons):
    4. return [[1 if (i, j) in alive_cons else 0
    5. for j in range(size)]
    6. for i in range(size)]
    7. def get_neighbors(con):
    8. x, y = con
    9. neighbors = [(x + i, y + j)
    10. for i in range(-1, 2)
    11. for j in range(-1, 2)
    12. if not i == j == 0]
    13. return neighbors
    14. def calculate_alive_neighbors(con, alive_cons):
    15. con_live = filter(lambda x: x in alive_cons, get_neighbors(con))
    16. return len(list(con_live))
    17. def is_alive_con(con, alive_cons):
    18. alive_neighbors = calculate_alive_neighbors(con, alive_cons)
    19. if (alive_neighbors == 3 or (alive_neighbors == 2 and con in alive_cons)):
    20. return True
    21. return False
    22. def new_step(alive_cons):
    23. board = itertools.chain(*map(get_neighbors, alive_cons))
    24. new_board = set([con for con in board if is_alive_con(con, alive_cons)])
    25. return list(new_board)
    26. def is_correct_con(size, con):
    27. x, y = con
    28. return all(0 <= coord <= size - 1 for coord in [x, y])
    29. def correct_cons(size, cons):
    30. return list(filter(lambda x: is_correct_con(size, x), cons))
    31. def print_board(board):
    32. for line in board:
    33. print(line)
    34. print()
    35. def main():
    36. size = 5
    37. board = [(0, 2), (1, 1), (1, 2), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
    38. print_board(get_board(size, board))
    39. for _ in range(10):
    40. board = correct_cons(size, new_step(board))
    41. print_board(get_board(size, board))
    42. if __name__ == '__main__':
    43. main()