简体   繁体   English

如何在python的递归函数中增长和返回列表

[英]How to grow and return a list from inside a recursive function in python

I have a recursive solution to Pascal's triangle, but it returns the row of the triangle requested, and not all of the rows preceding it. 我对Pascal的三角形有一个递归的解决方案,但是它返回所请求的三角形的行,而不是它前面的所有行。 I would like to know if there is a way to scoop up all the rows as they are computed from the base case and down the call stack, and return that as a list. 我想知道是否有一种方法可以检索所有行,因为它们是从基本情况下计算出来的,并向下调用堆栈,然后将其作为列表返回。

Writing the recursion for computing/returning any given row wasn't difficult but I thought I could just append each return to a list variable. 编写用于计算/返回任何给定行的递归并不困难,但我认为我可以将每个返回值附加到列表变量中。 The issue I'm having is anything I do to return the whole list messes with the return statement and breaks the computation of the row. 我遇到的问题是我要做的所有事情来返回整个列表,使之与return语句混乱,并破坏行的计算。

def pascal(n, tri):
    if n == 0:
        return tri
    else:
        r = pascal(n - 1, tri)
        row = [1] + [(r[i] + r[i + 1]) for i in range(len(r) - 1)] + [1]
        tri.append(row)
        print('tri =', tri)
    return tri[-1]

print(pascal(5, [[1]]))

The print statement inside the function shows that the rows get appended to the list. 函数内部的print语句显示行被追加到列表中。 I just can't think of how to return the list outside the function. 我只是想不出如何在函数外返回列表。 I need the last list element of 'tri' to generate the next layer, but at the same time I want to return all of 'tri' as my final return. 我需要'tri'的最后一个列表元素来生成下一层,但是同时我想返回所有'tri'作为我的最终返回值。

This is my first SO question so apologies if I'm just not seeing something blindingly obvious here. 这是我的第一个SO问题,如果我在这里看不到任何令人眼花obvious乱的东西,那么我深表歉意。 Thank you! 谢谢!

构建row您应该返回整个tri并仅使用r的最后一个元素:

row = [1] + [(r[-1][i] + r[-1][i + 1]) for i in range(len(r[-1]) - 1)] + [1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM