Advent of Code #3

source_file = open("data.txt", "r")
contents = source_file.read()
data_list = contents.split("\n")
source_file.close()
my_array=[]
counter=0
def invert(binary):
bit_s = binary
inverse_s = ''
for i in bit_s:
if i == '0':
inverse_s += '1'
else:
inverse_s += '0'
return (inverse_s)
## function end
def my_function(pos):
bit0_count=0
bit1_count=0
for x in data_list:
if (x[pos]) == "0" :
bit0_count+=1
else:
bit1_count+=1
if (bit0_count > bit1_count):
my_array.append("0")
else :
my_array.append("1")
## function end
for i in range(12) :
my_function(counter)
counter+=1
gamma= ("".join(my_array))
epsilon=invert(gamma)
a=(int(gamma, 2))
b=(int(epsilon, 2))
answer=a * b
print("answer = ",answer)



Copyright 2018. All rights reserved.

Posted December 3, 2021 by sal in category "code