Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.9 kB
1
Indexable
Never
class TuringMachine:
    def __init__(self, tape):
        self.tape = tape
        self.head = 0
        self.state = 'q0'

    def transition(self):
        while self.state != 'q_accept' and self.state != 'q_reject':
            if self.state == 'q0':
                if self.tape[self.head] == '0':
                    self.tape[self.head] = 'X'
                    self.head += 1
                    self.state = 'q1'
                else:
                    self.state = 'q_reject'
            elif self.state == 'q1':
                if self.tape[self.head] == '0':
                    self.head += 1
                elif self.tape[self.head] == '1':
                    self.head += 1
                    self.state = 'q2'
                else:
                    self.state = 'q_reject'
            elif self.state == 'q2':
                if self.tape[self.head] == '1':
                    self.tape[self.head] = 'Y'
                    self.head -= 1
                    self.state = 'q3'
                else:
                    self.state = 'q_reject'
            elif self.state == 'q3':
                if self.tape[self.head] == '1':
                    self.head -= 1
                elif self.tape[self.head] == '0':
                    self.head -= 1
                    self.state = 'q4'
                else:
                    self.state = 'q_reject'
            elif self.state == 'q4':
                if self.tape[self.head] == '0':
                    self.tape[self.head] = 'Z'
                    self.head += 1
                else:
                    self.state = 'q_reject'

        print("Accepted" if self.state == 'q_accept' else "Rejected")

# Example usage:
input_string = list(input("Enter a string: "))  # Input string as a list of characters
tm = TuringMachine(input_string)
tm.transition()
Leave a Comment