Пример #1
0
def main():
    (options, args) = parse_args()
    cardsFilePath = args[0]
    tape = Tape(options.defaultValue, options.tapeSize)
    maxIterations = options.maxIterations
    with open(cardsFilePath, "r") as handle:
        cards = json.load(handle)

    currentState = "start"
    iterationCount = 0
    while (currentState != "halt") and (iterationCount < maxIterations):
        instructions = cards[currentState][tape.read()]
        tape.write(instructions["write"])
        tape.move(instructions["move"])
        currentState = instructions["next"]
        print currentState
        print tape.statusToString()
        iterationCount += 1

    if currentState != "halt":
        print "maximum iterations exceeded!"
Пример #2
0
class TuringMachine(object):
    """
    TuringMachine(machine_config, tape_content)

        machine_config is a list of attributes of the Turing machine that must be like following:
            position 0: List of the input alphabet
            position 1: List of the tape alphabet
            position 2: Symbol that represents the blank space
            position 3: List of the states
            position 4: The initial state
            position 5: List of the final states
            position 6: Number of tapes (This Turing machine simulator currently accepts only single-tape machines)
            position 7 to forward: Transactions in a list format that must be like:
                position 0: Currently state
                position 1: Next state
                position 2: The symbol of tape in current position
                position 3: The New symbol of tape in current position
                position 4: The indication of movement (R to right, L to left and S to stay)

        tape_content is a String that represents the content on the tape at begin of Turing machine computing
    """
    def __init__(self, machine_config, tape_content):
        self.input_alphabet = machine_config[0]
        self.tape_alphabet = machine_config[1]
        self.blank_symbol = ''.join(machine_config[2])
        self.states = machine_config[3]
        self.init_state = ''.join(machine_config[4])
        self.final_states = machine_config[5]
        self.qnt_tapes = int(''.join(machine_config[6]))
        self.transictions = machine_config[7:]
        self.tape_content = tape_content
        self.tape = Tape(self.tape_content, self.blank_symbol)

    def initialize_computing(self):
        """
        initialize_computing()

        Initializes the Turing machine computing
        """
        self.print_information()
        current_state = self.init_state
        queue = [self.tape]
        while queue:
            if current_state in self.final_states:
                print(self.tape.tape_content)
                print('Accept')
                exit(0)

            valid_transitions = self.valid_transitions(current_state)

            for transition in valid_transitions:
                current_state = self.aply_transaction(transition)


    def validate_input(self):
        """
        validate_input()

        Input format validation

        returns 0 if the input format is valid or one of the following for invalid:
            1 if has no one input alphabet detected
            2 if has no one tape alphabet detected
            3 if has no one blank symbol detected
            4 if has no one states detected
            5 if has no one init state detected
            6 if has no one final state detected
            7 if the quantity of tapes is different of 1
            8 if has no one transition detected
        """
        if self.input_alphabet == ['']:
            return 1
        if self.tape_alphabet == ['']:
            return 2
        if self.blank_symbol == '':
            return 3
        if self.states == ['']:
            return 4
        if self.init_state == '':
            return 5
        if self.final_states == ['']:
            return 6
        if self.qnt_tapes != 1:
            return 7
        if self.transictions == []:
            return 8
        for character in list(self.tape_content)
        if self.transictions == []:
            return
        return 0

    def print_information(self):
        print('Input alphabet: ', self.input_alphabet)
        print('Tape alphabet: ', self.tape_alphabet)
        print('Blank symbol: ', self.blank_symbol)
        print('States: ', self.states)
        print('Initial state: ', self.init_state)
        print('Final states: ', self.final_states)
        print('Quantity of tapes', self.qnt_tapes)

    def aply_transaction(self, transition):
        self.tape.write(transition[3])
        self.tape.move(transition[4])
        return transition[1]

    def valid_transitions(self, state):
        valid_transitions = []
        for transiction in self.transictions:
            if transiction[0] == state:
                if self.tape.read() == transiction[2]:
                    valid_transitions.append(transiction)
        return valid_transitions
class TuringMachine:
    def __init__(self):
        self.TransitionTable = []
        self.tape1 = Tape()
        self.tape2 = Tape()
        self.tape3 = Tape()

    def __str__(self):
        """Makes the machine pretty to read."""
        M = str(self.tape1) + "\n" + str(self.tape2) + "\n" + str(self.tape3)
        return M

    def lookup_transition(self, state, in2):
        """Searches for a transition in the table, can return None."""
        for tuple in self.TransitionTable:
            if (tuple[0] == state and tuple[1] == in2):
                return tuple
        return None

    def set_head_on_transition(self, transition):
        """Sets the head of the tape on the given transition."""
        index = self.TransitionTable.index(transition)
        index = index * 6 + 1
        self.tape1.head = index

    def add_transition(self, state, in2, out2, mov2, next_state):
        """Adds a new transition to the machine's transition table."""
        new_tuple = (state, in2, out2, mov2, next_state)
        # We check that the current state has a transition
        # for the desired inputs, if it does we overwrite it
        old_tuple = self.lookup_transition(state, in2)
        if old_tuple:
            old_tuple = new_tuple
        else:
            # If there is no transition for this state and inputs
            # we simply add it to the machine's transition table
            self.TransitionTable.append(new_tuple)

    def print_transition_table(self):
        """Prints all of the transitions in the Machine."""
        for tuple in self.TransitionTable:
            print tuple

    def tape_setup(self, word, initial_state):
        """Prepares the Machine's tapes for execution."""
        # Setting up the three tapes, we cheat here and
        # don't use the tape's movement and writing methods
        # for simplicity and efficiency.
        for transition in self.TransitionTable:
            for char in transition:
                self.tape1.tape.append(str(char))
            self.tape1.tape.append(";")
        for char in word:
            self.tape2.tape.append(char)
        self.tape3.move("R")
        self.tape3.write(initial_state)

    def execute(self, word, initial_state, halt_state, verbose = False):
        """Executes the machine, prints if the word is Accepted or Crashes."""
        self.tape_setup(word, initial_state)
        # Main Universal Turing Machine execution loop
        # while our tape3 (the state tape) isn't pointing to halt
        # we keep executing according to our transition table.
        # Do note that the machine can infinite loop if its
        # not programmed properly.
        while self.tape3.read() != halt_state:
            current_state = self.tape3.read()
            input2 = self.tape2.read()
            instruction = self.lookup_transition(current_state, input2)
            if instruction:
                output = instruction[2]
                movement = instruction[3]
                next_state = instruction[4]
            else:
                raise MachineException("CRASH")
            yield self
            self.tape2.write(output)
            self.set_head_on_transition(instruction)
            self.tape2.move(movement)
            self.tape3.write(next_state)
        yield self
        print "ACCEPT"