alex0sunny

search_with_dics

Sep 18th, 2021 (edited)
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. N_RESULTS = 5
  2.  
  3. n = int(input())
  4. texts_dics = []
  5. for _ in range(n):
  6.     text_dic = {}
  7.     for word in input().split():
  8.         word_hash = hash(word)
  9.         text_dic[word_hash] = text_dic.get(word_hash, 0) + 1
  10.     texts_dics.append(text_dic)
  11.  
  12. m = int(input())
  13. queries_dic = {}
  14. for i in range(m):
  15.     for word in input().split():
  16.         word_hash = hash(word)
  17.         if word_hash not in queries_dic:
  18.             queries_dic[word_hash] = set()
  19.         queries_dic[word_hash].add(i)
  20.  
  21.  
  22. def search_words(m, texts_dics, queries_dic):
  23.     queries_texts_dic = {i: {} for i in range(m)}
  24.     for text_i, text_dic in enumerate(texts_dics):
  25.         for w in text_dic.keys():
  26.             if w in queries_dic:
  27.                 for query_i in queries_dic[w]:
  28.                     queries_texts_dic[query_i][text_i] = \
  29.                         queries_texts_dic[query_i].get(text_i, 0) + text_dic[w]
  30.     result = []
  31.     for query_i in range(m):
  32.         counts_inds = sorted([[-count, i]
  33.                               for i, count in queries_texts_dic[query_i].items()])
  34.         result.append([i + 1 for _, i in counts_inds][:N_RESULTS])
  35.     return result
  36.  
  37.  
  38. [print(' '.join([str(x) for x in inds])) for inds in search_words(m, texts_dics, queries_dic)]
  39.  
Add Comment
Please, Sign In to add comment