Skip to content

Commit 511f16c

Browse files
committed
Dict: New module used for day 04
- Sortable dictionary - Get sorted strings with arbitrary length
1 parent b0300e4 commit 511f16c

File tree

3 files changed

+29
-7
lines changed

3 files changed

+29
-7
lines changed

04/solution.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from lib import solution
2+
from lib.dict import Dict
23
import re
3-
import collections
4-
import operator
54

65

76
class Solution(solution.Solution):
@@ -34,12 +33,11 @@ def process_room_list(self):
3433

3534
@staticmethod
3635
def get_checksum(string):
37-
d = collections.defaultdict(int)
36+
dictionary = Dict()
3837
for c in string:
3938
if c.isalpha():
40-
d[c] -= 1
41-
s = collections.OrderedDict(sorted(d.items(), key=operator.itemgetter(1, 0)))
42-
checksum = "".join(str(x) for x in s)[:5]
39+
dictionary.add(c)
40+
checksum = dictionary.get_sorted_string_by_value_and_key(5)
4341
return checksum
4442

4543
@staticmethod

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,15 @@ My solutions for [adventofcode.com (2016)](http://adventofcode.com/2016) with Py
3636
- Set and get side lengths
3737
- Check if triangle is possible
3838

39+
### Dict
40+
- Sortable dictionary
41+
- Get sorted strings with arbitrary length
42+
3943
## My solutions
4044
| Day | Task | Python modules | My modules |
4145
| --- | ---- | -------------- | ---------- |
4246
| 01 | Find shortest path and cross point | copy, math, PIL | Point2D, Map |
4347
| 02 | Find codes at keypads | os, json | Keypad |
4448
| 03 | Check triangles | re | Triangle |
45-
| 04 | Encrypt and check room names | re, collections, operator | - |
49+
| 04 | Encrypt and check room names | re, collections, operator | Dict |
4650
| 05 | Create password from MD5 hashes | hashlib | - |

lib/dict.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import collections
2+
import operator
3+
4+
5+
class Dict:
6+
def __init__(self):
7+
self.dict = collections.defaultdict(int)
8+
9+
def reset(self):
10+
self.dict.clear()
11+
12+
def add(self, key):
13+
self.dict[key] -= 1
14+
15+
def get_sorted_string_by_value_and_key(self, length, reverse=False):
16+
sorted_list = self.get_sorted_list_by_value_and_key(reverse)
17+
return "".join(str(x) for x in sorted_list)[:length]
18+
19+
def get_sorted_list_by_value_and_key(self, reverse=False):
20+
return collections.OrderedDict(sorted(self.dict.items(), key=operator.itemgetter(1, 0), reverse=reverse))

0 commit comments

Comments
 (0)