···11+import fileinput
22+33+44+def is_safe(row, x):
55+ """Helper function to read out-of-bounds tiles as safe."""
66+ if x < 0 or x >= len(row):
77+ return True
88+99+ return row[x]
1010+1111+1212+def predict_next_row(row):
1313+ """Given a row, returns the predicted following row."""
1414+ next_row = []
1515+1616+ for i in range(len(row)):
1717+ a, b, c = (is_safe(row, x) for x in range(i-1, i+2))
1818+ next_row.append(predict_safe(a, b, c))
1919+2020+ return tuple(next_row)
2121+2222+2323+def predict_safe(a, b, c):
2424+ if a and b and not c:
2525+ return False
2626+ elif not a and b and c:
2727+ return False
2828+ elif a and not b and not c:
2929+ return False
3030+ elif not a and not b and c:
3131+ return False
3232+3333+ return True
3434+3535+3636+if __name__ == '__main__':
3737+ # Represent safe tiles as True and traps as False
3838+ raw_first_row = fileinput.input()[0].strip()
3939+ row = tuple(True if c == '.' else False for c in raw_first_row)
4040+ safe_tiles = sum(row)
4141+4242+ for _ in range(40 - 1):
4343+ row = predict_next_row(row)
4444+ safe_tiles += sum(row)
4545+4646+ print "Number of safe tiles in first 40 rows:", safe_tiles
4747+4848+ for _ in range(400000 - 40):
4949+ row = predict_next_row(row)
5050+ safe_tiles += sum(row)
5151+5252+ print "Number of safe tiles in all 400000 rows:", safe_tiles