有限自动机是如何在代码中实现的?

2024-09-27 00:17:12 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python代码中,如何实现这方面的dfanfa

在python中有哪些好的方法可以做到这一点? 它们是否曾用于现实世界的项目?


Tags: 项目方法代码世界现实dfanfa
3条回答

在这里,我给出了NFA的递归解决方案。

考虑以下nfa:

enter image description here

可以使用列表列表来表示转换,如下所示:

转换=[[[0,1],[0]], [[4],[2]], [[4],[3]], [[4],[4]],[[4],[4]]]

注意:状态4是一个假设状态。一旦你去了那个州,你就不能再往前走了。当您无法从当前状态读取输入时,它会很有帮助。直接进入状态4,并说当前进度不接受输入(通过返回检查其他可能性)。e、 g,如果您在q1,并且当前的输入符号是'a',则转到状态4并进一步停止计算。

下面是Python代码:

#nfa simulation for (a|b)*abb
#state 4 is a trap state


import sys

def main():
    transition = [[[0,1],[0]], [[4],[2]], [[4],[3]], [[4],[4]]]
    input = raw_input("enter the string: ")
    input = list(input) #copy the input in list because python strings are immutable and thus can't be changed directly
    for index in range(len(input)): #parse the string of a,b in 0,1 for simplicity
        if input[index]=='a':
            input[index]='0' 
        else:
            input[index]='1'

    final = "3" #set of final states = {3}
    start = 0
    i=0  #counter to remember the number of symbols read

    trans(transition, input, final, start, i)
    print "rejected"



def trans(transition, input, final, state, i):
    for j in range (len(input)):
        for each in transition[state][int(input[j])]: #check for each possibility
            if each < 4:                              #move further only if you are at non-hypothetical state
                state = each
                if j == len(input)-1 and (str(state) in final): #last symbol is read and current state lies in the set of final states
                    print "accepted"
                    sys.exit()
                trans(transition, input[i+1:], final, state, i) #input string for next transition is input[i+1:]
        i = i+1 #increment the counter


main()

样本输出:(接受以abb结尾的字符串)

enter the string: abb
accepted

enter the string: aaaabbbb
rejected

。。。。。。

这是我的dfa实现版本,如果您正在寻找一个更面向对象的实现。然而,约翰·科尔曼的回答给了我一点启发。

class Node:
    def __init__(self, val):
        self.val = val
        self.links = []
    def add_link(self, link):
        self.links.append(link)
    def __str__(self):
        node = "(%s):\n" % self.val
        for link in self.links:
            node += "\t" + link + "\n"
        return node
    def __add__(self, other):
        return str(self) + other
    def __radd__(self, other):
        return other + str(self)
    def equals(self, node):
        ok = (self.val == node.val)
        if len(self.links) == len(node.links):
            for i in range(len(self.links)):
                ok = ok and (self.links[i] == node.links[i])
            return ok
        else:
            return False

class Link:
    def __init__(self, from_node, etiquette, to_node):
        self.from_node = from_node
        self.etiquette = etiquette
        self.to_node = to_node
    def __str__(self):
        return "(%s --%s--> %s)" % (self.from_node.val, self.etiquette, self.to_node.val)
    def __add__(self, other):
        return str(self) + other
    def __radd__(self, other):
        return other + str(self)
    def equals(self, link):
        return (self.from_node == link.from_node) and (self.etiquette == link.etiquette) and (self.to_node == link.to_node)

class Automata:
    def __init__(self, initial_node, nodes, terminal_node):
        self.initial_node = initial_node
        self.nodes = nodes
        self.terminal_node = terminal_node
    def get_next_node(self, current_node, etiquette):
        for link in current_node.links:
            if link.etiquette == etiquette:
                return link.to_node
        return None
    def accepts(self, string):
        node = self.initial_node
        for character in string:
            node = self.get_next_node(node, character)
        return self.terminal_node.equals(node)
    def __str__(self):
        automata = "Initial node: %s\nTerminal node: %s\n" % (self.initial_node.val, self.terminal_node.val)
        for node in self.nodes:
            automata += node
        return automata
    def __add__(self, other):
        return str(self) + other
    def __radd__(self, other):
        return other + str(self)




if __name__ == '__main__':
    pass

    s0 = Node("s0")
    s1 = Node("s1")
    s2 = Node("s2")

    s0_0_s0 = Link(s0, '0', s0)
    s0_1_s1 = Link(s0, '1', s1)
    s1_0_s2 = Link(s1, '0', s2)
    s1_1_s0 = Link(s1, '1', s0)
    s2_0_s1 = Link(s2, '0', s1)
    s2_1_s2 = Link(s2, '1', s2)

    s0.add_link(s0_0_s0)
    s0.add_link(s0_1_s1)
    s1.add_link(s1_0_s2)
    s1.add_link(s1_1_s0)
    s2.add_link(s2_0_s1)
    s2.add_link(s2_1_s2)

    a = Automata(s0, [s0, s1, s2], s0)

    print(a)
    print(a.accepts('1011101')) #True
    print(a.accepts('10111011')) #False

表示DFA的一种简单方法是使用字典。为每个州创建一个由字母表的字母键控的字典,然后创建一个由州键控的全局字典。例如,来自Wikipedia article on DFAs的以下DFA

enter image description here

可以用这样的字典来表示:

dfa = {0:{'0':0, '1':1},
       1:{'0':2, '1':0},
       2:{'0':1, '1':2}}

对从所讨论的字母表中提取的输入字符串“运行”dfa(在指定初始状态和接受值集之后)很简单:

def accepts(transitions,initial,accepting,s):
    state = initial
    for c in s:
        state = transitions[state][c]
    return state in accepting

您从初始状态开始,一个字符一个字符地遍历字符串,在每个步骤中只需查找下一个状态。单步执行完字符串后,只需检查最终状态是否在接受状态集中。

例如

>>> accepts(dfa,0,{0},'1011101')
True
>>> accepts(dfa,0,{0},'10111011')
False

对于NFAs,您可以在转换字典中存储可能的状态集,而不是单个状态,并使用random模块从可能的状态集中选择下一个状态。

相关问题 更多 >

    热门问题