Advertisement
Guest User

life lines

a guest
Aug 23rd, 2012
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. def step(live_cells):
  2.    
  3.     def get_neighbors(cell):
  4.         e  = [cell[0] + 1, cell[1] - 0]
  5.         n  = [cell[0] + 0, cell[1] + 1]
  6.         s  = [cell[0] - 0, cell[1] - 1]
  7.         w  = [cell[0] - 1, cell[1] + 0]
  8.         se = [cell[0] + 1, cell[1] - 1]
  9.         ne = [cell[0] + 1, cell[1] + 1]
  10.         sw = [cell[0] - 1, cell[1] - 1]
  11.         nw = [cell[0] - 1, cell[1] + 1]
  12.  
  13.         neighbors = [e, n, s, w, se, ne, sw, nw]
  14.            
  15.         return neighbors
  16.  
  17.     def neighbor_count(live_cells, neighbors):
  18.         return sum(1 for a in neighbors if a in live_cells)
  19.  
  20.     new_live_cells = []
  21.     neighbor_list = []
  22.     # live cells with 2 or 3 neighbors live
  23.     for cell in live_cells:
  24.         neighbors = get_neighbors(cell)
  25.         if neighbor_count(live_cells, neighbors) in [2, 3]:
  26.             if cell not in new_live_cells:
  27.                 new_live_cells.append(cell)
  28.         for a in neighbors:
  29.             if a not in live_cells:
  30.                 neighbor_list.append(a)
  31.            
  32.     # dead cells with exactly 3 neighbors become live
  33.     for a in neighbor_list:
  34.         if neighbor_list.count(a) == 3:
  35.             if a not in new_live_cells:
  36.                 new_live_cells.append(a)
  37.     return new_live_cells
  38.  
  39. def get_cells(n):
  40.     return [[0, i] for i in range(n)]
  41.  
  42. def get_final_state(n):
  43.     live_cells = get_cells(n)
  44.     all_states = []
  45.     count = 0
  46.     while True:
  47.         live_cells = step(live_cells)
  48.         count += 1
  49.         if count > 1000:
  50.             return 'no resolution'
  51.         if live_cells == []:
  52.             return ['disappears', count, 0]
  53.         if live_cells in all_states:
  54.             return ['stable', count, count - all_states.index(live_cells) - 1]
  55.         all_states.append([i for i in live_cells])
  56.  
  57. for i in range(1, 101):
  58.     print i, get_final_state(i)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement