python递归帕斯卡三角形 [英] python recursive pascal triangle

查看:90
本文介绍了python递归帕斯卡三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在完成使用迭代函数创建帕斯卡三角形的任务后,我尝试使用递归函数重新创建它.我已经到了可以让它生成与作为参数传入的数字相对应的单个行的地步.但是几次尝试让它产生直到并包括该行的整个三角形都失败了.我什至尝试编写一个单独的函数,该函数在输入数字的范围内进行迭代,并使用迭代的数字调用递归函数,同时在返回该列表之前将各个行附加到列表中.所需的输出应该是一个列表列表,其中每个内部列表包含三角形的一行.像这样:

After completing an assignment to create pascal's triangle using an iterative function, I have attempted to recreate it using a recursive function. I have gotten to the point where I can get it to produce the individual row corresponding to the number passed in as an argument. But several attempts to have it produce the entire triangle up to and including that row have failed. I even tried writing a separate function which iterates over the range of the input number and calls the recursive function with the iterated digit while appending the individual lines to list before returning that list. The desired output should be a list of lists where each internal list contains one row of the triangle. Like so:

[[1], [1, 1], [1, 2, 1]...]

相反,它返回一个完全由 1 填充的嵌套列表的混乱.

Instead it returns a jumbled mess of a nested list completely filled with 1's.

这是有问题的递归函数,没有第二个函数来追加行(无论如何我真的想要1个全包函数):

Here is the recursive function in question, without the second function to append the rows (I really wanted 1 all inclusive function anyway):

def triangle(n):
    if n == 0:
        return []
    elif n == 1:
        return [1]
    else:
        new_row = [1]
        last_row = triangle(n-1)
        for i in range(len(last_row)-1):
            new_row.append(last_row[i] + last_row[i+1])
        new_row += [1]
    return new_row

说清楚,我已经完成了分配的任务,这只是为了更深入地理解递归......

To be clear, I have already completed the assigned task, this is just to provide a deeper understanding of recursion...

迭代解决方案:

def triangle(n):
    result = []
    for row in range(n):
        newrow = [1]
        for col in range(1, row+1):
            newcell = newrow[col-1] * float(row+1-col)/col
            newrow.append(int(newcell))
        result.append(newrow)
    return result

推荐答案

你只需要通过递归传递一个列表列表,挑出列表的最后一个元素(即三角形的最后一行)来构建你的新行.像这样:

You just need to pass a list of lists through the recursion, and pick off the last element of the list (i.e. the last row of the triangle) to build your new row. Like so:

def triangle(n):
    if n == 0:
        return []
    elif n == 1:
        return [[1]]
    else:
        new_row = [1]
        result = triangle(n-1)
        last_row = result[-1]
        for i in range(len(last_row)-1):
            new_row.append(last_row[i] + last_row[i+1])
        new_row += [1]
        result.append(new_row)
    return result

这篇关于python递归帕斯卡三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆