07
This commit is contained in:
44
07/07-2.py
Normal file
44
07/07-2.py
Normal file
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
file = "./input.txt"
|
||||
#file = "./ex.txt"
|
||||
|
||||
from itertools import product
|
||||
def evaluate_left_to_right(numbers:list[int], operations:list[str]) -> int:
|
||||
result = numbers[0]
|
||||
for i, op in enumerate(operations):
|
||||
if op == '+':
|
||||
result += numbers[i+1]
|
||||
elif op == '*':
|
||||
result *= numbers[i+1]
|
||||
elif op == '-':
|
||||
result = int(str(result)+str(numbers[i+1]))
|
||||
return result
|
||||
def check_combinations(numbers:list[int], target:int) -> bool:
|
||||
operations = ['+', '*', '-']
|
||||
n = len(numbers) - 1
|
||||
for ops in product(operations, repeat=n):
|
||||
if target == evaluate_left_to_right(numbers, ops):
|
||||
return True
|
||||
return False
|
||||
|
||||
def parse_str_to_int_list(number_string:str)->list[int]:
|
||||
result = []
|
||||
tmp = number_string.split()
|
||||
for num in tmp:
|
||||
result.append(int(num))
|
||||
return result
|
||||
|
||||
if __name__ == "__main__":
|
||||
solution = 0
|
||||
input_file = open(file, "r")
|
||||
for line in input_file:
|
||||
line = line.strip()
|
||||
if line == "":
|
||||
continue
|
||||
line = line.split(":")
|
||||
if check_combinations(parse_str_to_int_list(line[1]), int(line[0])):
|
||||
solution += int(line[0])
|
||||
input_file.close()
|
||||
|
||||
print(f'Solution: {solution}')
|
||||
Reference in New Issue
Block a user