Guest User

Untitled

a guest
Apr 2nd, 2023
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. PAIRINGS = {
  2.     '{' : '}',
  3.     '[' : ']',
  4.     '(' : ')',
  5.     '<' : '>'
  6. }
  7.  
  8. def valid_parentheses_count(s: str) -> int:
  9.     stack = []
  10.     s = list(s)
  11.     memo = {}
  12.     res = impl(s, 0, stack, memo)
  13.     print("Result: ", res, "(", "".join(s), ")")
  14.    
  15.  
  16. def impl(s, index, stack, memo):
  17.     if index >= len(s):
  18.         return 1 if len(stack) == 0 else 0
  19.     if len(stack) > len(s) - index:
  20.         return 0
  21.     curr_char = s[index]
  22.     if curr_char == '?':
  23.         total = 0
  24.         for sel_char in list(PAIRINGS.keys()) + list(PAIRINGS.values()):
  25.             if index < 3 and len(s) > 15:
  26.                 print(index, sel_char)
  27.             s[index] = sel_char
  28.             total += impl(s, index, stack, memo)
  29.         s[index] = '?'
  30.         return total
  31.     elif curr_char in PAIRINGS:
  32.         stack.append(curr_char)
  33.         res = impl(s, index+1, stack, memo)
  34.         stack.pop()
  35.         return res
  36.     else:
  37.         if len(stack) == 0:
  38.             return 0
  39.         matching = stack.pop()
  40.         if PAIRINGS[matching] != curr_char:
  41.             res = 0
  42.         elif ("".join(stack), index) in memo:
  43.             res = memo[("".join(stack), index)]
  44.         else:
  45.             res = impl(s, index+1, stack, memo)
  46.             memo[("".join(stack), index)] = res
  47.         stack.append(matching)
  48.         return res
  49.  
  50. # Test cases
  51. valid_parentheses_count("?[??")  # Output: 4
  52. valid_parentheses_count("?)??")  # Output: 4
  53. valid_parentheses_count("?[??")  # Output: 4
  54. valid_parentheses_count("??")
  55. valid_parentheses_count("????")
  56. valid_parentheses_count("??????")
  57. valid_parentheses_count("????????")
  58. valid_parentheses_count("??????????")
  59. valid_parentheses_count("????????????")
  60. valid_parentheses_count("??????????????")
  61. valid_parentheses_count(")???")  # Output: 0
  62. valid_parentheses_count("?<????????????)??]???????}??")
Advertisement
Add Comment
Please, Sign In to add comment