python 中的流程图逻辑

Flowchart logic in python

我有一个流程图,其中包含状态机等组件。我无法解码如何在 python 中开始编写此内容。 TMS 是一个输入列表 [1,1,1,1,1,0,1,1,0]

我开始编写一些代码,但陷入了进一步开发的困境。

TMS = [1,1,1,1,1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0]

next_step = False
def test_logic_reset():
  if tms == 1:
    print("reset")
  elif tms == 0:
    run_test_idle()

for i in TMS:
  tms = i
  print(tms)
  test_logic_reset()

任何人都可以帮助理解我应该使用的范例吗?

这似乎有利于状态机的实现。您可以从头开始实施,也可以使用 Python 库,例如 pytransitions。这个库有很多特性,比如在转换之前或之后调用方法、仅在满足条件时执行转换、处理无效 states/transitions 的错误等。基本解决方案如下所示:

from transitions import Machine

class StateMachine:

    states = ['test_logic_reset', 'run_test_idle', 'another_state']

    def __init__(self):
        self.machine = Machine(model=self, states=StateMachine.states, initial='test_logic_reset')

        # you can also use named arguments: trigger, source, dest
        self.machine.add_transition('input_0', 'test_logic_reset', 'run_test_idle')
        self.machine.add_transition('input_1', 'test_logic_reset', '=')
        self.machine.add_transition('input_0', 'run_test_idle', '=')
        self.machine.add_transition('input_1', 'run_test_idle', 'another_state')

    def trigger(self, value):
        if value == 0:
            self.input_0()
        elif value == 1:
            self.input_1()
        else:
            raise NotImplementedError

然后你可以这样称呼它:

TMS = [1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0]
sm = StateMachine()
for i in TMS:
    start_state = sm.state
    sm.trigger(i)
    end_state = sm.state
    print(f'Input: {i}, Transition: {start_state} -> {end_state}')

这可能会帮助您走上正确的道路。根据图中可见的部分,最好用 class 对有限状态机建模,其中机器到达下一个状态所需的密钥由当前状态决定。

class FSM:
    TEST_LOGIC_REST = 'TEST_LOGIC_REST'
    RUN_TEST_IDLE = 'RUN_TEST_IDLE'
    FINAL_STATE = 'FINAL_STATE'

    states = {
        TEST_LOGIC_REST: (0, RUN_TEST_IDLE),
        RUN_TEST_IDLE: (1, FINAL_STATE),
        FINAL_STATE: (None, None)
    }

    def __init__(self):
        self.state = FSM.TEST_LOGIC_REST
     

    def input(self, n):
        keyValue, nextState = FSM.states[self.state]
        if keyValue == n:
            self.state = nextState


    def __str__(self):
        return f'FSM(state={self.state})'


if __name__ == '__main__':
    TMS = [1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0]
    fsm = FSM()

    for i in TMS:
        fsm.input(i)
        print(f'input: {i},', fsm)