Advertisement
JoelSjogren

Untitled

Nov 18th, 2020 (edited)
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. ######## compile word to dfa
  2.  
  3. alphabet = 'abcdefghijklmnopqrstuvwxyz'
  4.  
  5. def bitstoint(bs):
  6. n = 0
  7. for b in reversed(bs):
  8. n = 2*n + b
  9. return n
  10.  
  11. def compile_word_to_dfa_that_matches_it_as_substring(word):
  12. """
  13.  
  14. The state of the automaton must tell, for each i, whether the
  15. input so far ends in word[:i].
  16.  
  17. If the input so far ends in word[:i], and the next character is
  18. indeed word[i], then the input so far ends in word[:i+1];
  19. otherwise it doesn't.
  20.  
  21. As an exception to this rule, if the input so far ends in word,
  22. then this will forever be the state of the automaton.
  23. """
  24. assert set(word) <= set(alphabet)
  25. N = 2**(len(word) + 1) # all states are 0 <= s < N; (s & (1 << i)) is valid for 0 <= i <= len(word)
  26. def transition(s, c):
  27. if s == N-1:
  28. return N-1 # accepting state
  29. if s & (1 << (len(word)-1)) and word[-1] == c:
  30. return N-1
  31. return 1 + 2*bitstoint([
  32. int(s & (1 << i) and word[i] == c)
  33. for i in range(len(word))
  34. ])
  35.  
  36. transition_matrices = {
  37. c: [[int(transition(i, c) == j) for j in range(N)] for i in range(N)]
  38. for c in alphabet
  39. }
  40. initial_state = 1
  41. final_state = N-1
  42. return (transition_matrices, initial_state, final_state)
  43.  
  44. ######## (optional: optimize the dfa)
  45.  
  46.  
  47. ######## probability calculation
  48.  
  49. import numpy as np
  50.  
  51. def calculate_acceptance_probability(dfa, q, t):
  52. transition_matrices, initial_state, final_state = dfa
  53. Aq = sum([np.array(transition_matrices[c])*q[c] for c in alphabet]).transpose()
  54. N = Aq.shape[0]
  55. v = np.array([int(i == initial_state) for i in range(N)])
  56. for _ in range(t):
  57. v = np.dot(Aq, v)
  58. return v[final_state]
  59.  
  60. ######## demo
  61.  
  62. word = 'joel' # the 4 letter word
  63. t = 8 # the total number of letters
  64.  
  65. dfa = compile_word_to_dfa_that_matches_it_as_substring(word)
  66. q = {c: 1/len(alphabet) for c in alphabet}
  67. answer = calculate_acceptance_probability(dfa, q, t)
  68.  
  69. print(f"The accepted stackexchange answer: {5/26**4}")
  70. print(f"The exact answer with automaton: {answer}")
  71.  
  72.  
  73. """ demo output
  74.  
  75. box% python -i main.py
  76. The accepted stackexchange answer: 1.094149364518049e-05
  77. The exact answer with automaton: 1.094148885652915e-05
  78. >>>
  79.  
  80. """
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement