【问题标题】:Python recursive function not descendingPython递归函数不降序
【发布时间】: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
  • 不,那不可能是您的代码。复制并粘贴它并尝试运行它,您会发现它甚至无法解析。我可以立即发现一个问题——末尾的returndef 的级别相同。但我不知道这是否是您的帖子与您的真实代码不同的唯一地方。您可以发布一些我们可以阅读、运行和调试的内容,而不是让我们尝试猜测您的真实代码是什么样的。

标签: python recursion python-2.x


【解决方案1】:

为了实现递归,您的流程函数需要调用自身。通常带有初始函数参数的子集。

在您的代码中,您从 for 循环中调用 Process 函数。所以这不会是递归的。

这个线程有一个递归函数的例子,以及为什么在后续调用中参数减少的例子:

How can I build a recursive function in python?

【讨论】:

  • 所以我需要从任何循环之外调用它?
  • 从循环中调用它是无关紧要的。如果该循环在函数体内,则它是递归的。如果它在函数体之外,则不是。
  • @mr.plow:我是说关于“在任何循环之外”的整个事情都是一个红鲱鱼。如果你从函数体内调用函数,它是递归的。如果你不这样做,它就不是递归的。而且,正如我上面解释的,如果你不修复缩进,我们实际上无法判断你的函数是否是递归的。
  • 致那些投反对票的人——我的回答在缩进被纠正之前是有效的。
猜你喜欢
  • 2014-04-08
  • 2017-06-14
  • 1970-01-01
  • 2016-06-30
  • 2015-03-01
  • 1970-01-01
  • 2015-11-09
相关资源
最近更新 更多