Home > Enterprise >  Advent Of Code 2021: Day 3 Part 1 | characters not added to variable in PYTHON
Advent Of Code 2021: Day 3 Part 1 | characters not added to variable in PYTHON

Time:12-28

This is my code and my output doesn't even look like its right, I think the 0 and 1 aren't being concatenated to the variables.

#Day 3 Part 1
one_count = 0
zero_count = 0

gamma = ""
espilon = ""

with open('input3.txt') as f:
    data = f.read()
    nums = [str(num) for num in data.splitlines()]

nums = [list(i) for i in nums]
#print(nums)

for j in range(0, 12):

    for i in range(len(nums)):
        if "1" in nums[i][j]:
            one_count  = 1

        elif "0" in nums[i][j]:
            zero_count  = 1
        

if zero_count > one_count:
    gamma  = "0"
    espilon  = "1"

    zero_count = 0
    one_count = 0

elif one_count > zero_count:
    gamma  = "1"
    espilon  = "0"

    zero_count = 0
    one_count = 0

print(gamma)
print(espilon)

Output:

1
0

I don't think I can add the 1,000 line txt file but you can visit the advent of code 2021 website yourself and check out day 3 part 1's input.

Advent of code Day 3

CodePudding user response:

The thing is that you need ot apply the logic (count zeros and ones) for each bit position (or each column), not just once as your code does

The easiest is to iterate on the columns, use zip to transpose from the rows, then for each find the most and lest common (one is the opposite of the other)

puzzle = """00100\n11110\n10110\n10111\n10101\n01111\n00111\n11100\n10000\n11001\n00010\n01010"""

rows = puzzle.splitlines()  # ['00100', '11110', '10110', ..
cols = list(zip(*rows))  # [('0', '1', '1', '1', '1', '0', '0', '1', '1', '1', '0', '0'), ...
gamma = ""  # most common
epsilon = ""  # least common

for col in cols:
    if col.count('1') > col.count('0'):  # most common is 1
        gamma  = '1'
        epsilon  = '0'
    else:  # most common is 0
        gamma  = '0'
        epsilon  = '1'

gamma = int(gamma, 2)
epsilon = int(epsilon, 2)
power = gamma * epsilon

print(f"{gamma=} {epsilon=} {power=}")  # gamma=22 epsilon=9 power=198

Binary math could be used too

gamma = 0
epsilon = 0
l = len(cols)
for idx, col in enumerate(cols):
    if col.count('1') > col.count('0'):
        gamma  = 2 ** (l - idx - 1)
    else:
        epsilon  = 2 ** (l - idx - 1)
power = gamma * epsilon
  • Related