Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- class Program:
- def __init__(self, program_from_file):
- self.dct = program_from_file
- def next_command(self, current_symbol: str, current_state: int):
- next_com = self.dct[current_symbol][current_state]
- next_sym, next_state = re.split('[<>.]', next_com, 1)
- direction = re.findall('[<>.]', next_com)[0]
- return next_sym, direction, next_state
- class Parser:
- def __init__(self, path_to_file):
- self.path = path_to_file
- self._program_dct = {}
- self.parser()
- self._program = Program(self._program_dct)
- def parser(self):
- # Прочитываем файл и заносим все данные в словарь
- with open(self.path, 'r') as file:
- for line in file.readlines():
- line = line.rstrip('\n').split('\t')
- self._program_dct[line[0]] = {num: sym for num, sym in
- enumerate(line[1:], start=1)}
- @property
- def program(self):
- return self._program
- class TuringMachine:
- def __init__(self, line: str, program: Program):
- self.line: list = list(line)
- self.head_index = line.index('q')
- del self.line[self.head_index]
- self.start_line = self.line.copy()
- self.program = program
- self.count_command = 0
- self.current_state = 1
- def run(self):
- # line = "q111X11"
- while str(self.current_state) != '0':
- self.count_command += 1
- print(f'-- COMMAND NUM: {self.count_command} --')
- viewed_symbol = self.get_viewed_symbol()
- print(f' State: {self.current_state} -> ', end='')
- next_com = self.program.next_command(viewed_symbol,
- self.current_state)
- if not next_com:
- print('--- STOP ---')
- break
- set_symbol, direction, next_state = next_com
- self.current_state = int(next_state)
- print_line = self.line.copy()
- print_line[self.head_index] = 'q' + print_line[self.head_index]
- print(f'{self.current_state}; Sym: {set_symbol}; '
- f'Dir: {direction}; Line: "{"".join(print_line)}" -> ',
- end='')
- self.set_symbol(set_symbol)
- self.move_head(direction)
- print_line = self.line.copy()
- print_line[self.head_index] = 'q' + print_line[self.head_index]
- print(f'"{"".join(print_line)}"')
- print(f'Convert line: "{"".join(self.start_line)}" -> '
- f'"{"".join(self.line)}"')
- def set_symbol(self, symbol):
- if symbol == "_":
- symbol = ' '
- self.line[self.head_index] = symbol
- def move_head(self, direction):
- # Пережвигаем головку машины
- if direction == '>':
- self.head_index += 1
- elif direction == '<':
- self.head_index -= 1
- # Если вышли за размеры линии, то сразу изменяем ее размер
- # (так проще всего вышло сделать для логов)
- if self.head_index >= len(self.line):
- self.line.extend([' ' for i in range(self.head_index -
- (len(self.line) - 1))])
- if self.head_index < 0:
- for _ in range(abs(self.head_index)):
- self.line.insert(0, ' ')
- self.head_index = 0
- def get_viewed_symbol(self):
- symbol = ' '
- if self.head_index < len(self.line):
- symbol = self.line[self.head_index]
- return symbol
- def print_result(self):
- print(f'All viewed cell count: {len(self.line)}')
- print(f'Command count: {self.count_command}')
- tur_machine = TuringMachine('111q1',
- Parser('lab_3_programs/4.4.txt').program)
- tur_machine.run()
- tur_machine.print_result()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement