Header Ads

Header ADS

5 Design a Program for creating a machine that accepts the string always ending with 101.

 class EndingWith101Machine:

    def __init__(self):

        self.current_state = 'start'


    def transition(self, symbol):

        transitions = {

            'start': {'1': 'one', '0': 'start', 'default': 'reject'},

            'one': {'1': 'one', '0': 'zero', 'default': 'reject'},

            'zero': {'1': 'accept', '0': 'zero', 'default': 'reject'},

            'accept': {'1': 'accept', '0': 'accept', 'default': 'reject'},

            'reject': {'1': 'reject', '0': 'reject', 'default': 'reject'}

        }


        self.current_state = transitions.get(self.current_state, {}).get(symbol, transitions[self.current_state]['default'])


    def reset(self):

        self.current_state = 'start'


    def is_accepting(self):

        return self.current_state == 'accept'



def check_ending_with_101(input_string):

    machine = EndingWith101Machine()


    for symbol in input_string:

        machine.transition(symbol)


    return machine.is_accepting()



# Test the machine

input_strings = ["00101", "101", "0101", "111101", "101101"]

for input_str in input_strings:

    result = check_ending_with_101(input_str)

    print(f'The string "{input_str}" always ends with "101": {result}')


No comments

Powered by Blogger.