Advertisement
Guest User

Advent of Code Day 21

a guest
Dec 22nd, 2020
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. """Day 22 of Advent of Code 2020 Solution"""
  2. from collections import Counter
  3.  
  4.  
  5. def allergen_io(file_location):
  6.     word_count = Counter()
  7.     word_sets = {}
  8.     with open(file_location, 'r') as f:
  9.         for line in f.readlines():
  10.             line = line.strip()[:-1].split('(')
  11.             line[0] = line[0].strip().split(' ')
  12.             line[1] = line[1][9:].strip().split(', ')
  13.             word_count.update(line[0])
  14.             for allergen in line[1]:
  15.                 if allergen in word_sets:
  16.                     word_sets[allergen].intersection_update(line[0])
  17.                 else:
  18.                     word_sets[allergen] = {*line[0]}
  19.     return word_count, word_sets
  20.  
  21.  
  22. def part_a(file_location):
  23.     word_count, word_sets = allergen_io(file_location)
  24.     allergen_set = set()
  25.     for allergen in word_sets.values():
  26.         allergen_set.update(allergen)
  27.     n_non_allergen_words = 0
  28.     for word in word_count:
  29.         if word not in allergen_set:
  30.             n_non_allergen_words += word_count[word]
  31.     return n_non_allergen_words
  32.  
  33.  
  34. def part_b(file_location):
  35.     _, word_sets = allergen_io(file_location)
  36.     while not all([len(v) == 1 for v in word_sets.values()]):
  37.         allergens = sorted([*word_sets.keys()], key=lambda x: len(word_sets[x]))
  38.         for i, allergen_1 in enumerate(allergens):
  39.             for allergen_2 in allergens[i + 1:]:
  40.                 if len(word_sets[allergen_1]) == 1:
  41.                     word_sets[allergen_2].difference_update(word_sets[allergen_1])
  42.     return ','.join([word_sets[key].pop() for key in sorted([*word_sets.keys()])])
  43.  
  44.  
  45. if __name__ == '__main__':
  46.     file_location = r"data\day21.txt"
  47.     print(part_a(file_location))
  48.     print(part_b(file_location))
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement