你的答案似乎是正确的。我没有仔细证明,但逻辑相当清楚。此外,我编写了一个 Python 程序来测试它:
def accepts(transitions,initial,accepting,s):
state = initial
for c in s:
state = transitions[state][c]
return state in accepting
dfa = {1:{'a':4, 'b':2},
2:{'a':10, 'b':3},
3:{'a':4, 'b':3},
4:{'a':7, 'b':5},
5:{'a':10, 'b':6},
6:{'a':7, 'b':6},
7:{'a':1, 'b':8},
8:{'a':10, 'b':9},
9:{'a':1, 'b':9},
10:{'a':10, 'b':10}}
def dfaTest(s):
return accepts(dfa,3,{1,2,3},s)
def valid(s):
return s.count('a') % 3 == 0 and not 'aba' in s
import random
tests = [''.join(random.choice(['a','b']) for j in range(100)) for i in range(1,1001)]
print(all(valid(s) == dfaTest(s) for s in tests))
此答案accepts
中解释了该功能的操作。我对其进行了定制以匹配您的图表。为了对其进行压力测试,我生成了 100,000 个长度范围从 1 到 1000 的随机输入,然后将 DFA 的输出与条件的直接验证进行了比较。每次我运行这段代码时,输出都是令人满意的.True
要测试单个字符串:
>>> dfaTest('ababba')
False
>>> dfaTest('abbabba')
True