my solutions for advent of code 2022
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.0 KiB

with open('input21.txt','r') as f:
inp = f.read().splitlines(keepends=False)
_monkeys = {}
for line in inp:
monkey, value = line.split(': ')
_monkeys[monkey] = value
Equation1 = _monkeys['root'].split()[0]
Equation2 = _monkeys['root'].split()[2]
print(Equation1, Equation2)
n = 0
done = False
monkeys = _monkeys.copy()
monkeys['humn'] = 'humn'
while not done:
done = True
for item in Equation1.split():
if item not in ['-','+','/','*','humn','(',')'] and not item.isnumeric():
if monkeys[item].isnumeric():
insert = monkeys[item]
else:
insert = '( ' + monkeys[item] + ' )'
Equation1 = Equation1.replace(item, insert)
done = False
break
done = False
while not done:
done = True
for item in Equation2.split():
if item not in ['-','+','/','*','humn','(',')'] and not item.isnumeric():
if monkeys[item].isnumeric():
insert = monkeys[item]
else:
insert = '( ' + monkeys[item] + ' )'
Equation2 = Equation2.replace(item, insert)
done = False
break
if 'humn' in Equation1:
Equation1 = Equation1.replace('humn', 'x')
Equation = eval('lambda x:' + Equation1)
else:
Equation1 = eval('lambda x:' + Equation1)
number = Equation1(1)
if 'humn' in Equation2:
Equation2 = Equation2.replace('humn', 'x')
Equation = eval('lambda x:' + Equation2)
else:
Equation2 = eval('lambda x:' + Equation2)
number = Equation2(1)
if Equation(0) < number:
increase = False
else:
increase = True
step = 100000000
while not Equation(n) == number:
print(n, Equation(n), number)
if increase:
if Equation(n) < number:
increase = False
step /= 10
else:
n += step
else:
if Equation(n) > number:
increase = True
step /= 10
else:
n -= step
print(n)
print(Equation1,'\n', Equation2)