Advertisement
gg-master

Untitled

Apr 23rd, 2022
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.04 KB | None | 0 0
  1. import re
  2.  
  3.  
  4. class Program:
  5.     def __init__(self, program_from_file):
  6.         self.dct = program_from_file
  7.  
  8.     def next_command(self, current_symbol: str, current_state: int):
  9.         next_com = self.dct[current_symbol][current_state]
  10.         next_sym, next_state = re.split('[<>.]', next_com, 1)
  11.         direction = re.findall('[<>.]', next_com)[0]
  12.         return next_sym, direction, next_state
  13.  
  14.  
  15. class Parser:
  16.     def __init__(self, path_to_file):
  17.         self.path = path_to_file
  18.         self._program_dct = {}
  19.  
  20.         self.parser()
  21.         self._program = Program(self._program_dct)
  22.  
  23.     def parser(self):
  24.         # Прочитываем файл и заносим все данные в словарь
  25.         with open(self.path, 'r') as file:
  26.             for line in file.readlines():
  27.                 line = line.rstrip('\n').split('\t')
  28.                 self._program_dct[line[0]] = {num: sym for num, sym in
  29.                                               enumerate(line[1:], start=1)}
  30.  
  31.     @property
  32.     def program(self):
  33.         return self._program
  34.  
  35.  
  36. class TuringMachine:
  37.     def __init__(self, line: str, program: Program):
  38.         self.line: list = list(line)
  39.         self.head_index = line.index('q')
  40.         del self.line[self.head_index]
  41.  
  42.         self.start_line = self.line.copy()
  43.  
  44.         self.program = program
  45.         self.count_command = 0
  46.  
  47.         self.current_state = 1
  48.  
  49.     def run(self):
  50.         # line = "q111X11"
  51.  
  52.         while str(self.current_state) != '0':
  53.             self.count_command += 1
  54.             print(f'-- COMMAND NUM: {self.count_command} --')
  55.  
  56.             viewed_symbol = self.get_viewed_symbol()
  57.             print(f'    State: {self.current_state} -> ', end='')
  58.             next_com = self.program.next_command(viewed_symbol,
  59.                                                  self.current_state)
  60.             if not next_com:
  61.                 print('--- STOP ---')
  62.                 break
  63.  
  64.             set_symbol, direction, next_state = next_com
  65.             self.current_state = int(next_state)
  66.  
  67.             print_line = self.line.copy()
  68.             print_line[self.head_index] = 'q' + print_line[self.head_index]
  69.             print(f'{self.current_state}; Sym: {set_symbol}; '
  70.                   f'Dir: {direction}; Line: "{"".join(print_line)}" -> ',
  71.                   end='')
  72.  
  73.             self.set_symbol(set_symbol)
  74.             self.move_head(direction)
  75.  
  76.             print_line = self.line.copy()
  77.             print_line[self.head_index] = 'q' + print_line[self.head_index]
  78.             print(f'"{"".join(print_line)}"')
  79.  
  80.         print(f'Convert line: "{"".join(self.start_line)}" -> '
  81.               f'"{"".join(self.line)}"')
  82.  
  83.     def set_symbol(self, symbol):
  84.         if symbol == "_":
  85.             symbol = ' '
  86.         self.line[self.head_index] = symbol
  87.  
  88.     def move_head(self, direction):
  89.         # Пережвигаем головку машины
  90.         if direction == '>':
  91.             self.head_index += 1
  92.         elif direction == '<':
  93.             self.head_index -= 1
  94.  
  95.         # Если вышли за размеры линии, то сразу изменяем ее размер
  96.         # (так проще всего вышло сделать для логов)
  97.         if self.head_index >= len(self.line):
  98.             self.line.extend([' ' for i in range(self.head_index -
  99.                                                  (len(self.line) - 1))])
  100.         if self.head_index < 0:
  101.             for _ in range(self.head_index - (len(self.line) - 1)):
  102.                 self.line.insert(0, ' ')
  103.  
  104.     def get_viewed_symbol(self):
  105.         symbol = ' '
  106.         if self.head_index < len(self.line):
  107.             symbol = self.line[self.head_index]
  108.         return symbol
  109.  
  110.     def print_result(self):
  111.         print(f'All viewed cell count: {len(self.line)}')
  112.         print(f'Command count: {self.count_command}')
  113.  
  114.  
  115. tur_machine = TuringMachine('q1x1111',
  116.                             Parser('lab_3_programs/2.55(в).txt').program)
  117. tur_machine.run()
  118. tur_machine.print_result()
  119.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement