Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TuringMachine(object):
- def __init__(self, alphabet, states, initial_state, accept_state, initial_tape):
- '''
- alphabet is a string of non-whitespace characters. They determine the possible values of the tape
- states is a string of whitespace-separated characters. They are the states that the machine can use
- initial_state is a string that is one element of states. It determines the starting state of the machine
- accept_state is a string that is one element of states. If accept_state gets called, the machine halts
- initial_tape is the starting tape of the machine
- '''
- self.alphabet = [e for e in alphabet]
- self.states = states.split()
- self.curr_state = initial_state
- if self.curr_state not in states:
- raise ValueError('initial_state not in states')
- self.accept_state = accept_state
- if self.accept_state not in states:
- raise ValueError('accept_state not in states')
- self.tape = [e for e in initial_tape]
- for e in self.tape:
- if e not in self.alphabet:
- raise ValueError('tape contains arguments that are not in alphabet')
- self.rules = {}
- self.position = 0
- def add_rule(self, rule):
- '''
- rule is string in the format StateBefore SymbolBefore = StateAfter SymbolAfter DirectionToMove
- '''
- rule = rule.split()
- self.rules[(rule[0], rule[1])] = (rule[3],rule[4],rule[5])
- def add_rulebook(self, rulebook):
- for e in rulebook.splitlines():
- self.add_rule(e)
- def next(self):
- "executes one cycle"
- if self.position >= self.tape.__len__():
- self.tape.append('_')
- rule = self.rules[(self.curr_state, self.tape[self.position])]
- self.curr_state = rule[0]
- self.tape[self.position] = rule[1]
- if rule[2] == '>':
- self.position += 1
- elif rule[2] == '<':
- self.position -= 1
- def print(self):
- for e in self.tape:
- print(e,end = '')
- print()
- print('|',end = '')
- for e in range(1, self.tape.__len__()):
- if e == self.position:
- print('^', end = '')
- else:
- print(' ', end = '')
- print('',end = '\n')
- def execute(self):
- while self.curr_state != self.accept_state:
- self.next()
- self.print()
- alphabet = input('alphabet: ')
- states = input('states: ')
- initial_state = input('initial_state: ')
- accept_state = input('accept_state: ')
- initial_tape = input('initial_tape: ')
- t = TuringMachine(alphabet, states, initial_state, accept_state, initial_tape)
- for line in iter(input('rulebook', '')):
- t.add_rule(line)
- t.execute()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement