python - 创建列表的三角形结构,其中包含左下角的数字
问题描述
我正在尝试创建一个看起来像这样的结构,它可以容纳的项目数为 n:
7
4 8
2 5 9
1 3 6 10
并将其转换为如下列表:
[[1, 3, 6, 10],[2, 5, 9],[4, 8],[7]]
我无法理解它,我认为每个项目都会增加1
,然后2
等等3
,但我希望它们存储的方式是我无法弄清楚的。
fn(6)
[[1 3 6],[2 5],[4]]
解决方案
我一定是有史以来最善良的人,但测试起来确实很有趣。这是一个有效的功能:
def fn(input):
output = []
# First row:
row = [1]
incrementor = 2
while row[-1]+incrementor <= input:
row.append(row[-1]+incrementor)
incrementor += 1
output.append(row)
# Rest of rows:
for i in range(len(output[0])-1):
output.append([e-1 for e in output[-1][1:]])
print(fn(10))
>> [[1, 3, 6, 10], [2, 5, 9], [4, 8], [7]]
推荐阅读
- azure-devops - AzureDevOps:授予对组织中所有存储库的只读访问权限
- asp.net-core - .net 4.6 web api2 401 未经授权使用身份服务器 4
- ios - 在 Realm Swift 中使用时间戳值(Double 数据类型)作为主键
- python - 创建 Tensorflow 模型,该模型接受张量图像作为模型的输入
- php - 如何对具有对象外键值的数组进行排序必须是第一个(Laravel)
- javascript - 如何在动态创建的单选按钮上触发功能
- pandas - 跨两个轴的小计和总计
- r - R DataTable 选择行
- git - 如何在不使用交互式 git rebase 的情况下将两个 git 提交合并为一个提交?
- linux - tar(子):test.zip:无法打开:压缩 node_modules 时是一个目录