Advertisement
miniminater

Untitled

May 11th, 2025
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.19 KB | None | 0 0
  1. import pandas as pd
  2.  
  3. # Define the Turing machine
  4. blank = '_'  # blank symbol
  5.  
  6.  
  7. def run_tm(w: str, max_steps: int = 20_000):
  8.     """
  9.    Simulate the 6‑state TM for L = { a^i b^i c^i | i >= 0 } on input `w`.
  10.    Returns (accept?, steps).
  11.    """
  12.     # Tape as a dict mapping index -> symbol (sparse)
  13.     tape = {i: ch for i, ch in enumerate(w)}
  14.     head = 0
  15.     state = 'q0'
  16.     steps = 0
  17.  
  18.     def read():
  19.         return tape.get(head, blank)
  20.  
  21.     def write(ch):
  22.         if ch == blank:
  23.             tape.pop(head, None)
  24.         else:
  25.             tape[head] = ch
  26.  
  27.     while state not in ('qacc', 'qrej') and steps < max_steps:
  28.         steps += 1
  29.         sym = read()
  30.  
  31.         # dispatch
  32.         if state == 'q0':
  33.             if   sym == 'a':  write('X'); head += 1; state = 'q1'
  34.             elif sym == 'X':  head += 1                     # stay q0
  35.             elif sym in 'bc': state = 'qrej'
  36.             elif sym == blank: state = 'qacc'
  37.             else: state = 'qrej'
  38.  
  39.         elif state == 'q1':
  40.             if   sym == 'a':  head += 1
  41.             elif sym == 'X':  head += 1
  42.             elif sym == 'b':  write('X'); head += 1; state = 'q2'
  43.             elif sym in ('c', blank): state = 'qrej'
  44.             else: state = 'qrej'
  45.  
  46.         elif state == 'q2':
  47.             if   sym == 'b':  head += 1
  48.             elif sym == 'X':  head += 1
  49.             elif sym == 'c':  write('X'); head -= 1; state = 'q3'
  50.             elif sym in ('a', blank): state = 'qrej'
  51.             else: state = 'qrej'
  52.  
  53.         elif state == 'q3':
  54.             if   sym in ('a', 'b', 'c', 'X'): head -= 1
  55.             elif sym == blank: head += 1; state = 'q0'
  56.             else: state = 'qrej'
  57.  
  58.         else:  # should never reach
  59.             state = 'qrej'
  60.  
  61.     return (state == 'qacc', steps if steps < max_steps else None)
  62.  
  63.  
  64. tests = [
  65.     "", "abc", "acb", "aabbcc", "aaabbbccc", "aabbbcc", "abcc",
  66.     "bca", "abcabc", "aaaabbbbcccc", "aaabbbcc"
  67. ]
  68.  
  69. results = []
  70. for s in tests:
  71.     accept, steps = run_tm(s)
  72.     results.append({'input': repr(s), 'accepted': accept, 'steps': steps})
  73.  
  74. df = pd.DataFrame(results)
  75. import ace_tools as tools; tools.display_dataframe_to_user("TM test results", df)
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement