with open('INPUT.txt', 'r') as f: lines = f.readlines() w, h = map(int, lines[0].split()) image1 = [] for i in range(1, h + 1): image1.append(lines[i].strip()) image2 = [] for i in range(h + 1, 2 * h + 1): image2.append(lines[i].strip()) operation_line = lines[2 * h + 1].strip() if ' ' in operation_line: operation = operation_line.split() else: operation = list(operation_line) result = [] for row in range(h): result_row = "" for col in range(w): pixel1 = int(image1[row][col]) pixel2 = int(image2[row][col]) if pixel1 == 0 and pixel2 == 0: result_pixel = operation[0] elif pixel1 == 0 and pixel2 == 1: result_pixel = operation[1] elif pixel1 == 1 and pixel2 == 0: result_pixel = operation[2] else: result_pixel = operation[3] result_row += result_pixel result.append(result_row) with open('OUTPUT.txt', 'w') as f: for row in result: f.write(row + '\n')