Advent of Code 2021 | Day 3 | Solution in Python3
I explore the solutions for the Advent of Code 2021 in Python3, for both the parts. Problem Link.
Contents hide
Part 1 Solution
def get_input(): data = [] with open("input.txt") as f: data = f.readlines() return data def solve(data): gamma, epsilon = "", "" for i in range(12): if sum(bits[i] == "1" for bits in data) > len(data)//2: gamma += "1" epsilon += "0" else: gamma += "0" epsilon += "1" return int(gamma, 2) * int(epsilon, 2) print(solve(get_input()))
Part 2 Solution
from collections import Counter def get_input(): data = [] with open("input.txt") as f: data = f.readlines() return data def solve(data): data = get_input() i = 0 while len(data) > 1: val = "" c = Counter([bits[i] for bits in data]) val = "1" if c["1"] >= c["0"] else "0" data = [bits for bits in data if bits[i] == val] i += 1 oxy = data[0] data = get_input() i = 0 while len(data) > 1: val = "" c = Counter([bits[i] for bits in data]) val = "0" if c["0"] <= c["1"] else "1" data = [bits for bits in data if bits[i] == val] i += 1 co2 = data[0] return int(oxy, 2) * int(co2, 2) print(solve(get_input()))
Recommended Posts
Majority Element | InterviewBit | Solution Explained
June 13, 2022
Advent of Code 2021 | Day 6 | Solutions in Python3
December 6, 2021