#!/usr/bin/env python3 import fileinput from copy import deepcopy numbers = [[int(i) for i in line.strip()] for line in fileinput.input()] bit_count = len(numbers[0]) occurrences = [0] * bit_count for number in numbers: for i, bit in enumerate(number): occurrences[i] += bit gamma, epsilon = 0, 0 for i, freq in enumerate(occurrences): shifted = 1 << (len(occurrences) - 1) >> i if freq > len(numbers) // 2: gamma |= shifted else: epsilon |= shifted print("part 1:", gamma * epsilon) most_common = deepcopy(numbers) least_common = deepcopy(numbers) for i in range(bit_count): ones = sum(number[i] for number in most_common) lc = int(ones * 2 >= len(most_common)) most_common = [number for number in most_common if number[i] == lc] if len(most_common) == 1: break for i in range(bit_count): zeros = sum(not number[i] for number in least_common) lc = int(zeros * 2 > len(least_common)) least_common = [number for number in least_common if number[i] == lc] if len(least_common) == 1: break mc = int("".join(str(x) for x in most_common[0]), 2) lc = int("".join(str(x) for x in least_common[0]), 2) print("part 2:", mc * lc)