import re import argparse parser = argparse.ArgumentParser() parser.add_argument("filename", help="the file from which to take data") args = parser.parse_args() with open(args.filename, "r") as f: contents = f.read() big_matrix = [] for line in contents.strip().split("\n"): big_matrix.append(list(map(int, line))) def print_matrix(mat): for row in mat: print("".join(map(str, row))) visibility = [] for row in big_matrix: new_row = [] for col in row: new_row.append(False) visibility.append(new_row) def update_visibility(trees, visibles): top = -1 for i, t in enumerate(trees): if t>top: visibles[i] = True top = t def watch_from_west(mat, vis): for trees, vision in zip(mat, vis): update_visibility(trees, vision) watch_from_west(big_matrix, visibility) # look from the west big_matrix = list(map(list, map(reversed, big_matrix))) visibility = list(map(list, map(reversed, visibility))) watch_from_west(big_matrix, visibility) # look from the east big_matrix = list(map(list,zip(*big_matrix))) visibility = list(map(list,zip(*visibility))) watch_from_west(big_matrix, visibility) # look from the... north? big_matrix = list(map(list, map(reversed, big_matrix))) visibility = list(map(list, map(reversed, visibility))) watch_from_west(big_matrix, visibility) # look from the south f_l = lambda i: filter(lambda x: x, i) answer = sum(map(len, map(list, map(f_l, visibility)))) print_matrix(visibility) print("visible trees are {} in number".format(answer)) def look(forest, x, y): n = look_at(forest, x, y, 0, -1) s = look_at(forest, x, y, 0, 1) e = look_at(forest, x, y, 1, 0) w = look_at(forest, x, y, -1, 0) return n*s*e*w def look_at(forest, x, y, dx, dy): count = 0 treehouse = forest[y][x] tx = x + dx ty = y + dy while tx >= 0 and tx < len(forest[0]) and ty >= 0 and ty < len(forest): if forest[ty][tx] >= treehouse: count += 1 break count += 1 tx = tx + dx ty = ty + dy return count best_score = 0 for y, row in enumerate(big_matrix): for x, tree in enumerate(row): score = look(big_matrix, x, y) if score > best_score: best_score = score print("the highest score we found was {}".format(best_score))