Solution to problem 4 in Python
This commit is contained in:
parent
94fbfb0f1a
commit
f8a68ef39a
@ -91,7 +91,7 @@ with open("files/P4.txt") as f:
|
|||||||
sorted_schedule = sorted(schedule)
|
sorted_schedule = sorted(schedule)
|
||||||
|
|
||||||
|
|
||||||
def part_1() -> None:
|
def part_1():
|
||||||
schedule_dict = defaultdict(list)
|
schedule_dict = defaultdict(list)
|
||||||
for line in sorted_schedule:
|
for line in sorted_schedule:
|
||||||
split_str = re.split(r"] | #| |\[", line)
|
split_str = re.split(r"] | #| |\[", line)
|
||||||
@ -124,10 +124,36 @@ def part_1() -> None:
|
|||||||
# get the most common minute for the guard who sleep the most
|
# get the most common minute for the guard who sleep the most
|
||||||
most_common_min = most_common_dict[max_sleep_length][0][0]
|
most_common_min = most_common_dict[max_sleep_length][0][0]
|
||||||
|
|
||||||
print(
|
print(f"Result (part 1): {int(max_sleep_length) * int(most_common_min)}")
|
||||||
f"The result we are looking for is {int(max_sleep_length) * int(most_common_min)}"
|
|
||||||
)
|
return most_common_dict
|
||||||
|
|
||||||
|
|
||||||
|
# --- Part Two ---
|
||||||
|
|
||||||
|
# Strategy 2: Of all guards, which guard is most frequently asleep on the same
|
||||||
|
# minute?
|
||||||
|
|
||||||
|
# In the example above, Guard #99 spent minute 45 asleep more than any other
|
||||||
|
# guard or minute - three times in total. (In all other cases, any guard spent
|
||||||
|
# any minute asleep at most twice.)
|
||||||
|
|
||||||
|
# What is the ID of the guard you chose multiplied by the minute you chose?
|
||||||
|
# (In the above example, the answer would be 99 * 45 = 4455.)
|
||||||
|
|
||||||
|
|
||||||
|
def part_2():
|
||||||
|
most_common_dict = part_1()
|
||||||
|
|
||||||
|
# get most frequently asleep minute for any guard
|
||||||
|
most_frequent_min = max(v[0][1] for v in most_common_dict.values())
|
||||||
|
|
||||||
|
for k, v in most_common_dict.items():
|
||||||
|
# get the key for that particular value
|
||||||
|
if most_frequent_min in v[0]:
|
||||||
|
print(f"Result (part 2): {int(k) * int(v[0][0])}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
part_1()
|
# part_1()
|
||||||
|
part_2()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user