Refactoring problem 4

This commit is contained in:
David Doblas Jiménez 2022-02-19 15:24:51 +01:00
parent 760dfa1746
commit 94fbfb0f1a

View File

@ -106,21 +106,27 @@ def part_1() -> None:
for i in range(starting_time, ending_time):
schedule_dict[date, guard_no].append(i)
list_dict = defaultdict(list)
# flatten lists of values for each key
flat_dict = defaultdict(list)
for k, v in schedule_dict.items():
for val in v:
list_dict[k[1]].append(val)
flat_dict[k[1]].append(val)
max_dict = defaultdict(list)
longest_dict = defaultdict(int)
for k, v in list_dict.items():
max_dict[k].append(Counter(v).most_common()[0])
longest_dict[k] += len(v)
# get most common minute for each guard
most_common_dict = defaultdict(list)
# get number of minutes each guard is sleeping
sleep_length_dict = defaultdict(int)
for k, v in flat_dict.items():
most_common_dict[k].append(Counter(v).most_common()[0])
sleep_length_dict[k] += len(v)
max_key = max(longest_dict, key=longest_dict.get)
max_min = int(max_dict[max_key][0][0])
max_sleep_length = max(sleep_length_dict, key=sleep_length_dict.get)
# get the most common minute for the guard who sleep the most
most_common_min = most_common_dict[max_sleep_length][0][0]
print(int(max_key) * max_min)
print(
f"The result we are looking for is {int(max_sleep_length) * int(most_common_min)}"
)
if __name__ == "__main__":