Advertisement
ronAmit

Untitled

Mar 11th, 2022
957
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. from typing import List, Dict, Tuple, Sequence
  2. import string
  3.  
  4. def solution(A: int, B: int, C: int):
  5.     return solution_aux(A, B, C, "", {})
  6.  
  7.  
  8. def diversity_friendly(new_leter, last_two):
  9.     if len(last_two) < 2:
  10.         return True
  11.  
  12.     return not(new_leter == last_two[0] == last_two[1])
  13.  
  14. def get_canonical(A, B, C, last_two):
  15.     let_counts = [A, B, C]
  16.     counts_ordered = sorted(enumerate(let_counts), key=lambda x: x[1])
  17.     A_t, B_t, C_t = [cnt for i, cnt in counts_ordered]
  18.     trans = {k: 'abc'[counts_ordered[i][0]] for i, k in enumerate('abc')}
  19.     inv_trans = {trans[let]: let for let in 'abc'}
  20.     last_two_t = last_two.translate(trans)
  21.     return A_t, B_t, C_t, last_two_t, trans, inv_trans
  22.  
  23.  
  24.  
  25. def solution_aux(A, B, C, last_two, cache):
  26.  
  27.     A_t, B_t, C_t, last_two_t, trans, inv_trans = get_canonical(A, B, C, last_two)
  28.  
  29.     if (A_t, B_t, C_t, last_two_t) in cache:
  30.         best_res_t = cache[(A_t, B_t, C_t, last_two_t)]
  31.         best_res = best_res_t.translate(inv_trans)
  32.         return best_res
  33.  
  34.     best_res = ''
  35.     letters_counts = {'a': A, 'b': B, 'c': C}
  36.  
  37.     for letter, count in letters_counts.items():
  38.         if count == 0 or not diversity_friendly(letter, last_two):
  39.             continue
  40.  
  41.         letters_counts[letter] -= 1
  42.         cur_res = letter + solution_aux(letters_counts['a'], letters_counts['b'], letters_counts['c'],
  43.                                         last_two[-1] + letter if last_two else letter,
  44.                                         cache)
  45.  
  46.         if len(cur_res) > len(best_res):
  47.             best_res = cur_res
  48.  
  49.         letters_counts[letter] += 1
  50.  
  51.     cache[(A_t, B_t, C_t, last_two_t)] = best_res.translate(trans)
  52.     return best_res
  53.  
  54.  
  55. if __name__ == '__main__':
  56.     A = 100
  57.     B = 100
  58.     C = 100
  59.     print(f'A={A}, B={B}, C={C}')
  60.     from time import perf_counter
  61.     start = perf_counter()
  62.     sol = solution(A, B, C)
  63.     total = perf_counter() - start
  64.     print(sol)
  65.     print(f'time = {total}s')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement