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.
37 lines
985 B
37 lines
985 B
import itertools
|
|
|
|
|
|
def is_possible(nums, answer, op_list):
|
|
for ops in itertools.product(*[op_list for i in range(len(nums) - 1)]):
|
|
val = nums[0]
|
|
for num, op in zip(nums[1:], ops):
|
|
if op == "+":
|
|
val += num
|
|
elif op == "*":
|
|
val *= num
|
|
elif op == "||":
|
|
val = int(f"{val}{num}")
|
|
if val == answer:
|
|
return answer
|
|
|
|
return 0
|
|
|
|
|
|
def analyze_equations(file, op_list):
|
|
with open(file, "r") as f:
|
|
sol = 0
|
|
for line in f:
|
|
answer = int(line.split(":")[0])
|
|
nums = [int(val) for val in line.split(":")[1].split()]
|
|
sol += is_possible(nums, answer, op_list)
|
|
return sol
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print("Solution to part 1 is {}".format(analyze_equations("input.txt", ["+", "*"])))
|
|
print(
|
|
"Solution to part 2 is {}".format(
|
|
analyze_equations("input.txt", ["+", "*", "||"])
|
|
)
|
|
)
|