Advertisement
kosievdmerwe

Untitled

Nov 8th, 2021
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. PUZZLE_LEN = 7
  2.  
  3. class Solution:
  4.     def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
  5.         norm_word_counters = [Counter() for _ in range(26)]
  6.        
  7.         for word in words:
  8.             norm_word = self.calc_norm_word(word)
  9.             if bin(norm_word).count("1") > PUZZLE_LEN:
  10.                 continue
  11.                
  12.             for fli in range(26):  # First letter index
  13.                 if (1 << fli) & norm_word == 0:
  14.                     continue
  15.                 norm_word_counters[fli][norm_word] += 1
  16.        
  17.         ans = [0] * len(puzzles)
  18.         for pi, puzzle in enumerate(puzzles):
  19.             fli = ord(puzzle[0]) - ord('a')
  20.             normed_letters = [(1 << (ord(c) - ord('a'))) for c in puzzle]
  21.            
  22.             for subset in self.powerset(normed_letters):
  23.                 norm_puzzle = sum(subset)
  24.                 ans[pi] += norm_word_counters[fli][norm_puzzle]
  25.         return ans
  26.  
  27.     def calc_norm_word(self, word: str) -> int:
  28.         normed = 0
  29.         for c in word:
  30.             normed |= 1 << (ord(c) - ord('a'))
  31.         return normed
  32.    
  33.     def powerset(self, elems):
  34.         return chain.from_iterable(
  35.             combinations(elems, r) for r in range(1, len(elems)+1)
  36.         )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement