Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2015
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. # coding=utf-8
  2.  
  3.  
  4. import collections
  5. from operator import add
  6.  
  7. from typing import List, Set
  8.  
  9.  
  10. class Point(collections.namedtuple("Point", "x y")):
  11. __slots__ = ()
  12.  
  13. def __add__(self, other):
  14. if not isinstance(other, self.__class__):
  15. return NotImplemented
  16. return self.__class__._make(map(lambda x: add(*x), zip(self, other))) #abstract as fuck!
  17.  
  18.  
  19. Frame = Set[Point]
  20.  
  21.  
  22. def neighbors(point: Point) -> List[Point]:
  23. yield from (Point(x, y) + point
  24. for y in range(-1, 2)
  25. for x in range(-1, 2)
  26. if (x, y) != (0, 0))
  27.  
  28.  
  29. def next_frame(frame: Frame) -> Frame:
  30. # count neighbors for each cell
  31. neighbor_count = collections.defaultdict(int)
  32. for cell in frame:
  33. for neighbor in neighbors(cell):
  34. neighbor_count[neighbor] += 1
  35.  
  36. # Create output
  37. output = set()
  38. for cell in neighbor_count.keys() | frame:
  39. if cell in frame: # live cell ...
  40. if 2 <= neighbor_count[cell] <= 3:
  41. output.add(cell) # ... lives
  42. else: # dead cell ...
  43. if neighbor_count[cell] == 3:
  44. output.add(cell) # ... lives
  45. return output
  46.  
  47.  
  48. glider = {Point._make(x) for x in [(0, 0), (1, 0), (2, 0), (2, 1), (1, 2)]}
  49. result = glider.copy()
  50. for n in range(4):
  51. result = next_frame(result)
  52.  
  53. print(glider == {item + Point(-1, 1) for item in result})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement