DFA 基本上由transition table 定义。此转换表将当前状态和当前输入的每个(有效)组合映射到相应的后继状态。这样的表可以建模为字典的字典。例如:外部字典包含状态作为键和字典作为值,这些字典依次将有效输入作为键和后继状态作为值。
编辑:
您选择的示例并不理想,因为它具有至少[a-zA-Z0-9] 的相当大的字母表(即所有可能的输入字符),链接的答案仅限于[01] 是有原因的;-)
无论如何,我将如何开始:
{
# in state '' we have not yet processed/consumed any input
# it is the start state
# the only valid input is a 'w'
'': {'w': 'w'},
# in state 'w' we a have already consumed a 'w'
# the only valid input is another 'w'
'w': {'w': 'ww'},
# in state 'ww' we have previously consumed 'ww'
# the only valid input is still only a 'w'
'ww': {'w': 'www'},
# now the only valid input is a '.'
'www': {'.': 'www.'},
# this is where your example becomes unpractical:
# we have to add a transition for every valid input
# (you could get around this by using a defaultdict and some kind of special signal value, but im not quite sure you are up to that)
'www.': {'a': 'www.*', 'b': 'www.*', ...},
# I used the star in this state name to symbolize multiple (at least one) valid character
# we only leave this state if we encounter a '.'
'www.*': {'.': 'www.*.', 'a': 'www.*', 'b': 'www.*', ...},
# it should be obvious how to continue from here
'www.*.': ...
}
EDIT2:聊天后的实施。
from collections import defaultdict
dfa = {
'initial': defaultdict(lambda: 'invalid', w='w'),
'w': defaultdict(lambda: 'invalid', w='ww'),
'ww': defaultdict(lambda: 'invalid', w='www'),
'www': defaultdict(lambda: 'invalid', [('.','www.')]),
'www.': defaultdict(lambda: 'www.*', [('.','invalid')]),
'www.*': defaultdict(lambda: 'www.*', [('.','www.*.')]),
'www.*.': defaultdict(lambda: 'www.*', [('c','www.*.c')]),
'www.*.c': defaultdict(lambda: 'www.*', [('o','www.*.co')]),
'www.*.co': defaultdict(lambda: 'www.*', [('m','www.*.com'), ('.','www.*.')]),
'www.*.com': defaultdict(lambda: 'www.*', [('.','www.*.')]),
'invalid': defaultdict(lambda: 'invalid')
}
def accepts(transitions,initial,accepting,s):
state = initial
for c in s:
state = transitions[state][c]
print(c, '->', state)
return state in accepting
print(accepts(dfa,'initial',{'www.*.com', 'www.*.co'},"www.hi.com"))