编译原理课程作业2

NFA匹配字符串,突然意识到可以用多层的list,然后整个作业就没有难度了,递归部分一直错我都怀疑人生了,结果发现是类里的递归声明要加类名。。

# -*- coding: utf-8 -*-
import sys
class io():
    """read the NFA from file"""
    def __init__(self,strlist):
        self.strlist = strlist
    def i(self):
        if(len(sys.argv)!=3):
            print "there are some errors"
            exit(0)
        file_name = sys.argv[1]
        self.strlist = list(sys.argv[2])
        file = open(file_name)
        """ M = (K ,E ,f ,S0 ,Z  ) """
        self.K = file.readline().strip().split(' ')
        self.E = file.readline().strip().split(' ')
        self.f = []
        for i in range(len(self.K)):
            listks = file.readline().strip().split(' ')
            listks2 = []
            for listk in listks:
                listks2.append(listk.strip().split(','))
            self.f.append(listks2)
        self.S0 = file.readline().strip().split(' ')
        self.Z = file.readline().strip().split(' ')
        #print self.K ,self.E ,self.f ,self.S0 ,self.Z,self.strlist
        if (not(set(self.strlist)<=set(self.E))):
            print "no"
            sys.exit()

    def nfa2str(self,numstr = 0,state = 's0'):
        if(numstr==len(self.strlist) and (state in self.Z)):
            print "yes"
            sys.exit()
        elif(numstr<len(self.strlist)):
            statex = self.K.index(state)
            statey = self.E.index(self.strlist[numstr])
            statesNow = self.f[statex][statey]
            if(statesNow!=['N/A']):
                for stateNow in statesNow:
                    x = io.nfa2str(self,numstr+1,stateNow)

str = []
m = io(str)
m.i()
m.nfa2str()
print "no"

读入的文件nfa.txt

s0 s1
a b
s0,s1 s1
N/A s0,s1
s0
s1

 

posted @ 2016-04-04 21:25  Dystopia  阅读(259)  评论(0编辑  收藏  举报