Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Deterministic Finite Automata

Name: Anonymous 2010-02-04 12:57

Write a program that accepts a description with lines of the form:  state symbol next_state, which defines the DFA's transition rules, and an input string. 

The first word in the description shall correspond to the starting state.  All transition states shall start with a lowercase letter and all accepting states shall start with an uppercase letter.  The program will print `1' if the input string ends on an accepting state and print `0' if otherwise.  If a symbol in the input string is not included in the description (i.e. not in it's ``alphabet''), then the program will print `0'.

Begin!


import sys

class DFA:
        def __init__(self, file):
                description = self.__listify__(file)

                self.sigma = set([j for (i,j,k) in description])
                self.alpha = [((i,j),k) for (i,j,k) in description]
                self.final = set([i for (i,j,k) in description if i[0].isupper()])
                self.state = description[0][0]

                self.accept = 1

        def __listify__(self, file):
                return [tuple(line.strip('\n').split()) for line in file]

        def __transition__(self, symbol):
                for (oldstate,newstate) in self.alpha:
                        if (self.state,symbol) == oldstate:
                                self.state = newstate
                                break

        def tapewalk(self, tape):
                for symbol in tape:
                        if not (symbol in self.sigma):
                                self.accept = 0
                                break
                        self.__transition__(symbol)

                self.accept = 1 if self.accept and self.state in self.final else 0
                print self.accept

def main():

        if len(sys.argv) != 3:
                sys.stderr.write('usage: DFA_sim DFA_desc_file string')
                sys.exit(0)

        descfile   = open(sys.argv[1])
        input      = sys.argv[2]
        automation = DFA(descfile)

        automation.tapewalk(input)

if __name__ == "__main__":
        main()

Name: Anonymous 2010-02-04 17:00

>>1
Dude, __foo__ is only for magic methods, your private methods are supposed to be __foo

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List