python - 不同版本的帕斯卡三角、列表、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
*
有人可以帮我解决这个错误吗?或者你会如何尝试解决这个问题?也许我的整个思考过程是错误的......
解决方案
也许这样的事情会帮助你:
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]]
推荐阅读
- flutter - WidgetsBinding.instance.addPostFrameCallback 不再起作用
- regex - 查找以特定单词开头的最长行
- javascript - 如何在 DevExtreme 图表中的 SubvalueIndicator 上放置标签?
- testing - 我们如何使用 UiPath 在 Tricentis Tosca 中管理测试事件?
- android - 如何在 RecyclerView 中突出显示并自动单击最近添加的项目
- javascript - 为什么我在 bouncycastle 中生成的 SHA512-ECDSA 密钥在 jsrsasign 中不匹配?
- css - 使用 mat-form-field 更改特定字段中的背景颜色
- python - Podio - 504 服务器错误:网址的网关超时
- reactjs - 在 Reactjs 和 Tailwind CSS 中创建默认缩略图
- java - 我使用 itextpdf 在 pdf 中生成了一些注释,但是当 acrobat reader 打开 pdf 时无法搜索到注释