Python 为FSM将函数循环在一起
正如你们中的许多人可能已经看到和/或编码过的,我正在尝试创建一个有限状态机;5个状态和9个转换,以确定某人是否在笑。我不一定要完整的答案,因为我想自己尽可能多地找出答案。然而,教授和助教在回答问题时并不总是很快或很有帮助,而且这个地方更有用 我只想能够输入“ha”或“ho”,直到输入一个“!”并说“你笑了”。任何其他字符都会结束它。有3个功能要实现;get_ch()、find_state()和main(),它们驱动其他两个。以下是我所拥有的:Python 为FSM将函数循环在一起,python,function,fsm,Python,Function,Fsm,正如你们中的许多人可能已经看到和/或编码过的,我正在尝试创建一个有限状态机;5个状态和9个转换,以确定某人是否在笑。我不一定要完整的答案,因为我想自己尽可能多地找出答案。然而,教授和助教在回答问题时并不总是很快或很有帮助,而且这个地方更有用 我只想能够输入“ha”或“ho”,直到输入一个“!”并说“你笑了”。任何其他字符都会结束它。有3个功能要实现;get_ch()、find_state()和main(),它们驱动其他两个。以下是我所拥有的: def get_ch(): # prompt fo
def get_ch(): # prompt for the input in a loop
ch = input("Enter a character or press the Return key to finish: ")
if len(ch) > 1:
print("Invalid input, please try again.")
else:
return ch
def find_state(state, ch):
if state==1:
if ch=="h" or ch=="H":
state=2
return state
else:
state=5
return state
if state==2:
if ch=="a" or ch=="A" or ch=="o" or ch=="O":
state=3
return state
else:
state=5
return state
if state==3:
if ch=="!":
state=4
return state
if ch=="h" or ch=="H":
state=2
return state
else:
state=5
return state
def main():
print("I can recognize if you are laughing or not.")
print("Please enter one character at a time.")
# initialize the variables, for example:
ch=get_ch()
string=""
state=1
#call the functions in a loop
while get_ch():
if len(ch)<1:
print("\nYou entered", string)
print("You are laughing.")
print("You are not laughing.")
else:
if state<4:
find_state(state,ch)
string+=ch
continue
if state==4:
print("\nYou entered", string)
print("You are laughing.")
else:
print("\nYou entered", string)
print("You are not laughing.")
main()
def get_ch():#在循环中提示输入
ch=输入(“输入字符或按回车键完成:”)
如果len(ch)>1:
打印(“输入无效,请重试”)
其他:
返回ch
def find_状态(状态,ch):
如果state==1:
如果ch==“h”或ch==“h”:
状态=2
返回状态
其他:
状态=5
返回状态
如果状态==2:
如果ch==“a”或ch==“a”或ch==“o”或ch==“o”:
州=3
返回状态
其他:
状态=5
返回状态
如果状态==3:
如果ch==“!”:
状态=4
返回状态
如果ch==“h”或ch==“h”:
状态=2
返回状态
其他:
状态=5
返回状态
def main():
打印(“我能认出你是否在笑。”)
打印(“请一次输入一个字符。”)
#初始化变量,例如:
ch=获取
string=“”
状态=1
#在循环中调用函数
而get_ch():
如果len(ch)看起来像是在粘贴代码时缩进被弄乱了。看起来有点像是您想使用协同程序-即“在两个函数之间来回跳跃而不返回返回”。这是可行的,但比“介绍级”Python要复杂一些。检查一下,现在应该好些了。我从Spyder复制时总是这样做。。。后来总是忘了再检查一遍。谢谢你的提醒!不幸的是,我们不能使用集体游或蹦床;我们只需要在主函数中循环这两个函数。当您在get_ch()时编写:
,您将丢弃返回值。它不会因为在函数中调用了ch
而神奇地出现在ch
变量中,或者因为您之前将此函数的第一次调用的结果分配给了ch
。看起来在粘贴代码时缩进有点混乱。看起来有点像您想使用协同程序-即“在两个函数之间来回跳跃,而不返回return
”。这是可行的,但比“介绍级”Python要复杂一些。检查一下,现在应该好些了。我从Spyder复制时总是这样做。。。后来总是忘了再检查一遍。谢谢你的提醒!不幸的是,我们不能使用集体游或蹦床;我们只需要在主函数中循环这两个函数。当您在get_ch()时编写:
,您将丢弃返回值。它不会仅仅因为在函数内部调用了ch
,或者之前将此函数第一次调用的结果赋给了ch
,就神奇地在ch
变量中结束。