word count engine

🏠

https://www.pramp.com/challenge/W5EJq2Jld3t2ny9jyZXG

Nailed it.

 1 from collections import defaultdict
 2 
 3 class Entry:
 4 
 5   def __init__(self, count, first_pos):
 6     self.count = count
 7     self.first_pos = first_pos
 8   
 9   def __lt__(self, other):
10     if self.count == other.count:
11       return self.first_pos > other.first_pos
12     return self.count < other.count
13 
14 def word_count_engine(document):
15   c = {}
16   for i, w in enumerate(document.split(' ')):
17     w = ''.join(filter(str.isalnum, w)).lower()
18     if w:
19       if w in c:
20         c[w].count += 1
21       else:
22         c[w] = Entry(1, i)
23   words_sorted = sorted(c.items(), key=lambda x: x[1], reverse=True)
24   return [[w, str(e.count)] for w, e in words_sorted]
25 
26 # time: O(n^2 + nlogn)
27 # space: O(n)
28 
29 document = "Practice makes perfect. you'll only get Perfect by practice. just practice!"
30 output = [ ["practice", "3"], ["perfect", "2"], ["makes", "1"], ["youll", "1"], ["only", "1"], 
31           ["get", "1"], ["by", "1"], ["just", "1"] ]
32 
33 r = word_count_engine(document)
34 print(r)