Guest User

Advent of Code 2017 - Day 4 Solution - Python 3

a guest
Dec 4th, 2017
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. """Day 4: check for valid passwords: no duplicate words """
  5.  
  6. from collections import Counter
  7.  
  8. # Input file
  9. with open('Day4input.txt', 'r') as f:
  10.     # Parse lines into lists of separate strings
  11.     passphrases = [s.strip().split() for s in f.read().splitlines()]
  12.  
  13.  
  14. def valid(counter):
  15.     """Test if passphrase has repeated words."""
  16.     if any(x > 1 for x in counter.values()):
  17.         return 0
  18.     return 1
  19.  
  20.  
  21. # Part 1
  22. total = 0
  23. for p in passphrases:
  24.     total += valid(Counter(p))
  25.  
  26. print(total)
  27.  
  28. # Part 2
  29. total2 = 0
  30. for p in passphrases:
  31.     # sort the words in the passphrase alphabetically to make Counting possible
  32.     sorted_list = list(map(lambda x: ''.join(sorted(x)), p))
  33.     c = Counter(sorted_list)
  34.     total2 += valid(c)
  35.  
  36.  
  37. print(total2)
Advertisement
Add Comment
Please, Sign In to add comment