59 lines
1.4 KiB
Python
59 lines
1.4 KiB
Python
# Python!
|
|
|
|
import collections
|
|
|
|
# Count occurences of a letter in a string (excluding dashes)
|
|
# and return a list of the five most frequent, sorted first
|
|
# by frequency (desc) and then alphabetically( asc)
|
|
def letter_frequency(string):
|
|
letter_counts = collections.defaultdict(int)
|
|
for char in string.replace('-', ''):
|
|
letter_counts[char] += 1
|
|
|
|
sortable = []
|
|
for count in letter_counts:
|
|
sortable.append([count, letter_counts[count]])
|
|
|
|
sortable = sorted(sortable, key=lambda x: x[0])
|
|
sortable = sorted(sortable, key=lambda x: x[1], reverse=True)
|
|
|
|
frequencies = ''
|
|
for n in range(5):
|
|
frequencies += sortable[n][0]
|
|
|
|
return frequencies
|
|
|
|
# Alphabetically shift each letter in the encrypted room name
|
|
# by the sector #; replace dashes with spaces
|
|
def decrypt(room_data):
|
|
alphabet = collections.deque('abcdefghijklmnopqrstuvwxyz')
|
|
decrypted = ''
|
|
for char in room_data['letters']:
|
|
if char == '-':
|
|
decrypted += ' '
|
|
else:
|
|
i = alphabet.index(char)
|
|
alphabet.rotate(-1 * room_data['sector'])
|
|
decrypted += alphabet[i]
|
|
|
|
return (decrypted, room_data['sector'])
|
|
|
|
|
|
with open('04.txt') as file:
|
|
lines = file.read().splitlines()
|
|
|
|
rooms = []
|
|
for line in lines:
|
|
data = {
|
|
'letters': line[:-11],
|
|
'sector': int(line[-10:-7]),
|
|
'most_common': line[-6:-1],
|
|
}
|
|
|
|
if letter_frequency(data['letters']) == data['most_common']:
|
|
rooms.append(decrypt(data))
|
|
|
|
rooms.sort(key=lambda k: k[0])
|
|
|
|
for room in rooms:
|
|
print(room) |