Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 迭代到递归_Python 3.x - Fatal编程技术网

Python 3.x 迭代到递归

Python 3.x 迭代到递归,python-3.x,Python 3.x,因此MyListTopyListList:获取一个MyList对象lst,并返回一个包含相同数据的Python列表 def myListToPyList(lst): return myListToPyListRec(lst.head) 以下是我的助手函数: def myListToPyListRec(node): if node == None: return else: st1 = [] st1.append(node

因此MyListTopyListList:获取一个MyList对象lst,并返回一个包含相同数据的Python列表

def myListToPyList(lst):
    return myListToPyListRec(lst.head)
以下是我的助手函数:

def myListToPyListRec(node):
    if node == None:
        return 
    else:
        st1 = []
        st1.append(node.data)
        myListToPyListRec(node.next)
    return st1
它不能正常工作

现在,我的迭代解决方案可以正常工作:

    def myListToPyList(lst):
    """
    Takes a list and returns a python list containing
    the same data
    param; lst
    return; list
    """

    st1 = []
    curr = lst.head
    while curr != None:
        st1.append(curr.data)
        curr = curr.next
    return st1 

while循环相当于尾部递归,反之亦然。Python没有自动尾部调用消除的一个原因是“反之亦然”部分相当简单。尾部递归要求您添加一个累加器参数,以便在基本情况下返回。虽然我没有测试的链接列表,但我相信下面的方法应该有效。如果不是,这就很接近了。Python的默认参数使助手变得更容易或不必要

def myListToPyListRec(node, py_list=[]):
    if node
        py_list.append(node.data)
        return myListToPyListRec(node.next, py_list)
    else:
        return py_list

当前的递归代码不起作用,因为每次调用它时,它都会创建一个新的空列表,向列表中添加一个值,然后在不传递列表的情况下进行递归。这意味着当处理链接列表中的最后一项时,调用堆栈将有N个单元素Python列表,其中N是列表节点的数量

相反,您应该在非递归包装函数中只创建一次列表。然后通过所有递归传递它:

def myListToPyList(lst):
    result_list = []                          # create just one Python list object
    myListToPyListRec(lst.head, result_list)  # pass it to the recursive function
    return result_list                        # return it after it has been filled

def myListToPyListRec(node, lst):
    if node is not None              # the base case is to do nothing (tested in reverse)
        lst.append(node.data)                 # if node exists, append its data to lst
        myListToPyListRec(node.next, lst)     # then recurse on the next node
因为Python列表是可变的,我们不需要在递归调用中返回任何内容,默认情况下不会返回任何内容,但我们忽略了这一点。myListToPyList中的result_list引用的列表与在对myListToPyList的每个递归调用中lst引用的对象相同。只要递归函数在适当的位置改变对象,例如使用append而不是重新绑定它,它们都会看到相同的结果

请注意,在Python中递归的效率将低于迭代,因为函数调用的开销比只更新两个变量要大