Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. from copy import deepcopy
  2.  
  3. def add_borders(arr):
  4.     row_len = len(arr[0])
  5.     arr = [row_len*[0]] + arr + [row_len*[0]]
  6.     r = arr[0]
  7.     return [[0] + row + [0] for row in arr]
  8.  
  9. def read(file_name):
  10.     global n, m, k, a, b
  11.     with open(file_name) as f:
  12.         n, m, k = (int(str_num) for str_num in next(f).split())
  13.         a = []
  14.         b = []
  15.         for line in f:
  16.             a += [[int(str_num) -1 for str_num in line.split()]]
  17.             b += [[0]*len(a[0])]
  18.     return a
  19.  
  20. def write(file_name, arr):
  21.     with open(file_name, "w") as f:
  22.         for r in arr[1:-1]:
  23.             f.write(' '.join((str(num) for num in r[1:-1])) + '\n')
  24.            
  25. def count_1(arr, x, y):
  26.     res = 0
  27.     delta_arr = [-1, 1]
  28.     for d in delta_arr:
  29.         if arr[x + d][y] == 1:
  30.             res += 1
  31.         if arr[x][y + d] == 1:
  32.             res += 1
  33.     return res
  34.  
  35. def count_active(arr, x, y):
  36.     res = 0
  37.     delta_arr = [-1, 1]
  38.     for d in delta_arr:
  39.         if arr[x + d][y]:
  40.             res += 1
  41.         if arr[x][y + d]:
  42.             res += 1
  43.     return res
  44.  
  45. def update(arr):
  46.     global b
  47.     new_arr = deepcopy(arr)
  48.     for i in xrange(1, len(arr) - 1):
  49.         for j in xrange(1, len(arr[0]) - 1):
  50.             new_value = 0
  51.             c1 =count_1(arr, i, j)
  52.             ca = count_active(arr, i, j)
  53.             if c1 > 1:
  54.                 new_value = 1
  55.             elif ca:
  56.                 new_value = 2
  57.             if arr[i][j] != new_value:
  58.                 b[i][j] += 1
  59.                 new_arr[i][j] = new_value
  60.     return new_arr
  61.  
  62. read("input.txt")
  63. a = add_borders(a)
  64. b = add_borders(b)
  65. for i in xrange(k):
  66.     a = update(a)
  67. write("output.txt", b)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement