Advertisement
avisrivastava254084

Untitled

Oct 31st, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. import heapq
  2. from collections import defaultdict
  3. from typing import List
  4.  
  5.  
  6. class AutocompleteSystem:
  7.  
  8.     def __init__(self, sentences: List[str], times: List[int]):
  9.         self.historical_data = defaultdict(int)
  10.         self.freq_sorted_sentences = []
  11.         for sentence, count in zip(sentences, times):
  12.             self.historical_data[sentence] = count
  13.         self.curr_input = ''
  14.         self.potential_sentences = sentences
  15.         self.char_counter = 0
  16.         self.ans = []
  17.  
  18.     def input(self, c: str) -> List[str]:
  19.         if c == '#':
  20.             self.historical_data[self.curr_input] += 1
  21.             self.curr_input = ''
  22.             self.char_counter = 0
  23.             self.potential_sentences = []
  24.             for sentence in self.historical_data.keys():
  25.                 self.potential_sentences.append(sentence)
  26.             self.freq_sorted_sentences = []
  27.             self.ans = []
  28.             return []
  29.         if c == '':
  30.             return None
  31.         self.curr_input += c
  32.         self.ans = []
  33.         further_potential_sentences = []
  34.         for sentence in self.potential_sentences:
  35.             if len(sentence)-1 < self.char_counter:
  36.                 continue
  37.             if sentence[self.char_counter] == c:
  38.                 further_potential_sentences.append(sentence)
  39.                 heapq.heappush(self.freq_sorted_sentences,
  40.                                (-1 * self.historical_data[sentence], sentence))
  41.         self.potential_sentences = further_potential_sentences
  42.         self.char_counter += 1
  43.         try:
  44.             self.ans.append(heapq.heappop(self.freq_sorted_sentences)[1])
  45.             self.ans.append(heapq.heappop(self.freq_sorted_sentences)[1])
  46.             self.ans.append(heapq.heappop(self.freq_sorted_sentences)[1])
  47.         except IndexError:
  48.             pass
  49.         self.freq_sorted_sentences = []
  50.         return self.ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement