首页 > 解决方案 > 不同版本的帕斯卡三角、列表、python

问题描述

我是 python 的初学者,我必须做一个特殊版本的帕斯卡三角形......特别的方式是元素不会相加但它们会相乘。

这是示例:因此该函数定义为multiplicative_pascal(start: int, height: int) -> List[List[int]]

forstart = 2并且height = 5函数应该返回

[[2 ], [2, 2], [2, 4, 2], [2, 8, 8, 2], [2, 16, 64, 16, 2]]

我的思考过程和代码

首先,我尝试制作正常的帕斯卡三角形,然后我想我只需将 + 替换为 * 并将 1(帕斯卡三角形的正常起点)替换为变量 start

def multiplicative_pascal(start: int, height: int) -> List[List[int]]:
    Pascal_list =[[start]]   #FIrst entry Defined to start 
    for i in range(start, height+1): 
        temp_list =[]
        for j in range(i+1):  #+1 As we are considering last element
            if(j==0):#First Element = start
                temp_list.append(start)
                continue
            elif(j == i):#Last Element = start
                temp_list.append(start)
                continue
            else:
                temp_list.append(Pascal_list[i-1][j]+Pascal_list[i-1][j-1]) # Addition of Upper Two Elements
        Pascal_list.append(temp_list)
    return Pascal_list 
print(multiplicative_pascal(1, 5))

对于这个函数,它打印了它应该在这里的结果

[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]

但是当我尝试从print(multiplicative_pascal(1, 5))更改为print(multiplicative_pascal(2, 5))时,它给了我这个错误, 如果你不想去外部,我不确定为什么会出错关联 :

*回溯(最近一次通话最后):文件“C:\Users\ASUS\Documents\Dalšie štúdium!!\MUNI\Informatika\ucenie na semestralny test.py”,第 108 行,打印中(multiplicative_pascal(2, 5))文件“C:\Users\ASUS\Documents\Dalšie štúdium!!\MUNI\Informatika\ucenie na semestralny test.py”,第 105 行,在 multiplicative_pascal temp_list.append(Pascal_list[i-1][j]+Pascal_list[i -1][j-1]) # Addition of Upper Two Elements IndexError: list index out of range

*

有人可以帮我解决这个错误吗?或者你会如何尝试解决这个问题?也许我的整个思考过程是错误的......

标签: pythonlistpascals-triangle

解决方案


也许这样的事情会帮助你:

def multiplicative_pascal(start: int, height: int) -> List[List[int]]:
    if height < 1:
        return []
    result = row = [start]
    for _ in range(height - 1):
        row = [start] + [(a * b) for a, b in zip(row, row[1:])] + [start]
        result.append(row)
    return result

>>> multiplicative_pascal(1, 5)
[[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]  # 1 * 1 is always 1...

>>> multiplicative_pascal(2, 5)
[[2], [2, 2], [2, 4, 2], [2, 8, 8, 2], [2, 16, 64, 16, 2]]

推荐阅读