【发布时间】:2018-04-10 18:42:01
【问题描述】:
我必须实现一个函数来检查查询字符串是否被下面的 FSM(有限状态自动机)接受
我已经做了一个小设计,基本上可以检索所有需要处理的数据。我仍然需要实现代码来检查 query_string 中的每个字符是否在某个箭头(转换)中可用。
所以我们有例如查询字符串'aab' 代码必须运行的方式是它检查查询中的第一个字符是否在从q0 到q1 的转换中可用。在这种情况下确实如此,因此代码需要检查查询中的第二个字符是否存在于从 q1 到 q2 的转换中。这又是真的。但是没有任何转换,所以查询中的第三个字符不存在于任何转换中,它需要返回 false。如果接受查询字符串,则代码必须返回 True 我对此很陌生,所以我希望你能理解下面的代码
代码:
def accept(fsm, query_string):
query_list = list(query_string)
# this is the list of the query string
print(query_list)
start = fsm1.get_initial_state()
betweenstates = fsm1.get_transitions()
endstates = fsm1.get_end_states()
# this function iterates through a dictionary and gives the available transtions per state
for i,j in betweenstates.items():
print("The transition to the next state" + str(i) + " : ")
for k in tuple(j):
print(k)
return False
print('This is the first query_string')
# This is the function that is ran
print(accept(fsm1, "b")) # should be True
print('\n')
print('This is the second query_string')
print(accept(fsm1, "aab")) # should be False
这是输出:
This is the first query_string
['b']
First entries for Q0 :
('a', 'Q1')
('b', 'Q1')
First entries for Q1 :
('a', 'Q2')
('', 'Q2')
('b', 'Q2')
False
This is the second query_string
['a', 'a', 'b']
First entries for Q0 :
('a', 'Q1')
('b', 'Q1')
First entries for Q1 :
('a', 'Q2')
('', 'Q2')
('b', 'Q2')
False
【问题讨论】: