尝试使用递归将Pascal的三角形生成为元组 [英] Attempting to generate Pascal's Triangle as a tuple using recursion

查看:80
本文介绍了尝试使用递归将Pascal的三角形生成为元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个函数以使用递归将Pascal的三角形生成为元组.

I need to write a function to generate Pascal's Triangle as a tuple using recursion.

e.g pascal(5)   
((1,), (1, 1), (1, 2, 1), (1, 3, 3, 1), (1, 4, 6, 4, 1))

我可以使用以下功能将其生成为列表:

I can generate it as a list with the following function:

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

我尝试将其更改为元组:

And I've tried changing this to a tuple:

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

但是它不起作用,并且出现错误len(last_row)-1 type int has no len.

but it doesn't work and I get the error len(last_row)-1 type int has no len.

我不确定如何解决此代码,将不胜感激.

I'm not sure how to fix this code and would appreciate any help.

推荐答案

我认为问题出在result = result + new_row行.

如果要查看原因,请将鼠标悬停在下面...

If you want to see why, mouseover below...

result是一个元组的元组,new_row是一个数字元组.如果将数字元组添加到元组的元组中,则会以元组的元组结尾!例如((1,), 1),这不是您想要的. 通过result = result + (new_row,)

result is a tuple of tuples, new_row is a tuple of numbers. If you add a tuple of numbers to a tuple of tuples, you end with a tuple of tuples and numbers! Such as ((1,), 1) which is not what you want. fix it by doing result = result + (new_row,)

这篇关于尝试使用递归将Pascal的三角形生成为元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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