【发布时间】:2013-10-18 09:46:20
【问题描述】:
我在尝试编写递归函数时遇到问题。看起来函数只是没有下降。我没有收到任何错误或任何东西,所以我真的不明白发生了什么。我得到的唯一输出是一些空列表。本质上,我试图跟踪我的程序通过某些给定输入可以采用的所有路径,并返回一个包含所有这些路径的列表。我对 python 非常非常非常陌生,所以有很多我不知道的。我对stackoverflow也很陌生,所以请原谅格式错误。提前致谢!
def Process ( fst, input, start_state, current_path=[], input_index=0 ):
current_line = input.replace('"', '')
current_state = start_state
probability = 1
result = []
state_paths = []
this_path = current_path
paths_found = []
epsilon_paths_found = []
temp_list = []
index = input_index
if not index < len( current_line ):
return this_path
item = current_line[index]
if not item.isspace():
for edge in fst.transitions[current_state]:
next_state = current_state
if item == edge.input:
paths_found.append( edge )
index += 1
for x in paths_found:
temp_list = this_path
temp_list.append( x )
temp_entry = Process( fst, input, x.target_state, temp_list, index )
state_paths.append( temp_entry )
#epsilon returns a list
epsilon = EpsilonStates( fst.transitions[current_state] )
if epsilon:
index -= 1
for i in epsilon:
epsilon_paths_found.append( i )
for y in epsilon_paths_found:
temp_list = this_path
temp_list.append( y )
state_paths.append( Process( fst, input, y.target_state, temp_list, index ) )
return state_paths
【问题讨论】:
-
你能修复缩进吗?这里不清楚
Process的定义在哪里结束,顶级模块代码从哪里开始——这对于回答您的问题至关重要。 -
这取决于。那是你的实际代码吗?因为当我尝试它时,我得到了一个
IndentationError,然后它甚至可以运行任何东西...... -
是的,那是我的代码。我再次尝试编辑它。只要没有错误,它就对我有用。
-
打印语句是找出代码执行时发生了什么的好方法——但它们有时难以解释递归过程。也许只是从
print locals()作为 Process 的第一行开始。我看到您使用可变数据类型(列表)作为默认参数 - 这肯定会导致问题。尝试谷歌搜索“python 可变默认参数”。 http://effbot.org/zone/default-values.htm -
不,那不可能是您的代码。复制并粘贴它并尝试运行它,您会发现它甚至无法解析。我可以立即发现一个问题——末尾的
return与def的级别相同。但我不知道这是否是您的帖子与您的真实代码不同的唯一地方。您可以发布一些我们可以阅读、运行和调试的内容,而不是让我们尝试猜测您的真实代码是什么样的。
标签: python recursion python-2.x