【问题标题】:Python - Making a function to check whether a given query string, is accepted by the given FSMPython - 制作一个函数来检查给定的查询字符串是否被给定的 FSM 接受
【发布时间】: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

【问题讨论】:

    标签: python fsm


    【解决方案1】:

    编写有限状态机非常简单:

    它需要三个组件。

    1. 一组状态(整数列表)
    2. 一组最终状态(整数列表)
    3. 转换矩阵(3d 布尔数组(state_old, state_new, char))。 (一个 epsilon 边仅仅意味着所有的转换都是有效的)

    然后创建一个递归调用自身的函数。此函数将字符串作为输入、当前状态以及两组状态和转换表。如果字符串为空,如果 state 是最终状态,则返回 true;如果 state 不是最终状态,则返回 false。如果字符串不为空,它会检查转换表中的条目是否已通过状态和string[0],并使用string[1:] 和新状态调用自身。

    差不多就是这样。我没有故意在这里放任何代码,因为你自己做这个是一个很好的练习。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-25
      • 2011-07-05
      • 2019-12-17
      • 1970-01-01
      • 2014-12-29
      • 2012-07-21
      • 2016-04-25
      • 2022-12-09
      相关资源
      最近更新 更多