Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- my_colony = """
- * ** * *
- * * * * * **
- * * * *
- * * * * * *
- * ** * ***
- """
- def check_borders(colony):
- size = [len(colony), len(colony[0])]
- try:
- crop = [
- min([i for i in range(size[0]) if any(colony[i])]),
- max([i for i in range(size[0]) if any(colony[i])]),
- min([j for j in range(size[1]) if any([c[j] for c in colony])]),
- max([j for j in range(size[1]) if any([c[j] for c in colony])]),
- ]
- except ValueError:
- crop = [0,0,0,0]
- colony = [[colony[i][j] for j in range(crop[2], crop[3]+1)] for i in range(crop[0],crop[1]+1)]
- colony = [[0]*len(colony[0])] + colony + [[0]*len(colony[0])]
- colony = [[0]+c+[0] for c in colony]
- return colony
- def from_string(string):
- colony = [s for s in string.split('\n') if s!='']
- colony = [[0 if c == ' ' else 1 for c in g] for g in colony]
- longest_line = len(max(colony, key = len))
- colony = [[g[i] if i<len(g) else 0 for i in range(longest_line)] for g in colony]
- return check_borders(colony)
- def from_RLE(RLE):
- # described here:
- # http://www.conwaylife.com/wiki/Run_Length_Encoded
- print(RLE)
- string = re.sub(
- r'(\d+)([ob$])',
- lambda x: int(x.group(0)[:-1])*x.group(0)[-1],
- RLE)
- print(string)
- string = re.sub('b', ' ', string)
- string = re.sub(r'\$', ' \n', string)
- return from_string(string)
- def progress(colony):
- neighborings = [
- [-1,-1], [-1,0], [-1,+1],
- [ 0,-1], [ 0,+1],
- [+1,-1], [+1,0], [+1,+1],
- ]
- size = [len(colony), len(colony[0])]
- new_colony = [i.copy() for i in colony]
- for i in range(size[0]):
- for j in range(size[1]):
- neighbors = 0
- for n in neighborings:
- if all([
- 0 <= i+n[0] < size[0],
- 0 <= j+n[1] < size[1],
- ]):
- if colony[i+n[0]][j+n[1]]:
- neighbors += 1
- if neighbors < 2: new_colony[i][j] = 0
- if neighbors > 3: new_colony[i][j] = 0
- if neighbors == 3: new_colony[i][j] = 1
- return check_borders(new_colony)
- def show(colony):
- for g in colony:
- print(''.join([' ' + ('o' if c else '·') for c in g]))
- if __name__ == '__main__':
- colony = from_string(my_colony)
- ## colony = from_RLE('4b2o$3b4o2$2b6o$3b4o2$2b2o2b2o$2obo2bob2o$3bo2bo3$4b2o$4b2o')
- alive = True
- phases = set()
- generation = 0
- while alive:
- cells_no = sum([sum(i) for i in colony])
- print('Generation {}, {} cells:'.format(generation, cells_no))
- show(colony)
- colony = progress(colony)
- generation += 1
- fingerprint = hash(repr(colony))
- if fingerprint in phases:
- alive = False
- else:
- phases |= {fingerprint}
Advertisement
Add Comment
Please, Sign In to add comment