-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPuzzle3.py
More file actions
86 lines (64 loc) · 2.2 KB
/
Puzzle3.py
File metadata and controls
86 lines (64 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import re
from re import findall
file_path = 'Input3.txt'
# Define the regex pattern
pattern = r'mul\(\d{1,3},\d{1,3}\)'
pattern_number = r'\d{1,3}'
pattern2 = r'do\(\)(?:(?!do\(\)|dont\(\)).)*mul\(\d{1,3},\d{1,3}\)'
pattern3 = r'^(?:(?!do\(\)|dont\(\)|mul\(\d{1,3},\d{1,3}\)).)*mul\(\d{1,3},\d{1,3}\)'
pattern_do = r'(do\(\))|(don\'t\(\))'
pattern4 = r'do\(\)(?:(?!do\(\)|dont\(\)|mul\(\d{1,3},\d{1,3}\)).)*mul\(\d{1,3},\d{1,3}\)'
matches = []
numbers = []
def task_1():
# Open the file and read it line by line
result = 0
with open(file_path, 'r') as file:
for line in file:
line_matches = re.findall(pattern, line)
matches.extend(line_matches)
for match in matches:
num = re.findall(pattern_number, match)
numbers.extend(num)
result += (int(num[0]) * int(num[1]))
num.clear()
return result
def task_2():
result = 0
with open(file_path, 'r') as file:
content = file.read()
First_do = re.search(pattern_do, content)
if First_do:
cut_content = content[:First_do.start()]
first_matches = re.findall(pattern, cut_content)
for match in first_matches:
num = re.findall(pattern_number, match)
numbers.extend(num)
result += (int(num[0]) * int(num[1]))
num.clear()
return result
def task2_2():
result = 0
with open(file_path, 'r') as file:
content = file.read()
matches = list(re.finditer(pattern_do, content))
do_parts = []
if matches:
for i in range(len(matches) - 1):
if matches[i].group() == "do()":
start = matches[i].start()
end = matches[i + 1].start()
do_parts.append(content[start:end])
# Handle the last "do()" call
if matches[-1].group() == "do()":
do_parts.append(content[matches[-1].start():])
for part in do_parts:
part_matches = re.findall(pattern, part)
for match in part_matches:
num = re.findall(pattern_number, match)
numbers.extend(num)
result += (int(num[0]) * int(num[1]))
num.clear()
return result
final_result = task_2() + task2_2()
print(final_result)