Python中基于lambda判定毕达哥拉斯三元组及num_list索引遍历输出实现
实现步骤
- 保留已编写的
is_pythagorean_triplelambda函数,判断逻辑无需修改 - 遍历列表时严格采用索引访问的方式,匹配提示中
num_list[0][0]的操作规则:先获取列表长度,生成从0到列表末尾的索引值序列,循环中通过索引取出每一个三元组的三个元素 - 根据判断函数的返回结果,拼接对应格式的字符串打印即可
完整可运行代码
num_list = [(20, 99, 101), (60, 91, 109), (16, 112, 113), (44, 117, 125)] is_pythagorean_triple = lambda a, b, c : a **2 + b**2 == c**2 # 索引遍历方式,i依次取0、1、2、3,对应列表的4个元素 for i in range(len(num_list)): # 按索引规则取出三个数值,和提示的访问方式完全一致 a = num_list[i][0] b = num_list[i][1] c = num_list[i][2] result = is_pythagorean_triple(a, b, c) status = "a" if result else "not a" print(f"{num_list[i]} is {status} triple Pythagoras.")
运行后输出效果
(20, 99, 101) is a triple Pythagoras. (60, 91, 109) is a triple Pythagoras. (16, 112, 113) is not a triple Pythagoras. (44, 117, 125) is a triple Pythagoras.
注:上述代码没有直接迭代列表的元组元素,所有三个数值的读取都遵循
num_list[元素位置][元组内位置]的索引规则,完全匹配题目给出的操作提示。
内容的提问来源于stack exchange,提问作者ssssmaner
相关产品推荐
相关产品推荐

