You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python for循环练习:实现数字三角形最后一行求和及get_row函数

数字三角形功能实现

1. 辅助函数get_row实现

功能说明:传入行高row_height,返回对应行的带空格分隔的数字字符串。

def get_row(row_height):
    # 生成1到row_height的升序数字序列
    ascending_nums = list(range(1, row_height + 1))
    # 生成row_height-1到1的降序数字序列
    descending_nums = list(range(row_height - 1, 0, -1))
    # 合并序列后转为空格拼接的字符串
    return ' '.join(map(str, ascending_nums + descending_nums))

测试用例输出验证:

  • get_row(1) 返回 "1"
  • get_row(2) 返回 "1 2 1"
  • get_row(5) 返回 "1 2 3 4 5 4 3 2 1"

2. 最后行总和计算功能实现

功能说明:传入数字三角形总高度height,返回最后一行所有整数的总和。

def calc_last_row_sum(height):
    # 调用get_row获取最后一行字符串
    last_row = get_row(height)
    # 拆分字符串为数字列表并求和
    num_list = list(map(int, last_row.split()))
    return sum(num_list)

测试用例输出验证:

  • calc_last_row_sum(2) 返回 4
  • calc_last_row_sum(4) 返回 16
  • calc_last_row_sum(7) 返回 49

内容的提问来源于stack exchange,提问作者Gizem Tepecik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 15:54:05