无需使用starmap、函数及lambda实现原Python代码相同输出
无函数/lambda、无starmap实现原代码输出
需要实现以下原代码的完全相同输出,但禁止使用starmap、任何自定义函数及lambda表达式。
原代码
from itertools import starmap #the max p you can have for your square pair. max_P = number square_pairs = sorted( ((x_square-y_square) // 2, P, x_square, y_square) for parity in (1, 2) for x in range(parity, int((2*max_P)**.5)+1, 2) for y in range(parity, x, 2) if (P := ((x_square:=x**2)+(y_square:=y**2)) // 2) <= max_P ) print( 'N\tP\tN+P\tP-N\n---------------------------', '\n'.join(starmap('{}\t{}\t{}\t{}'.format, square_pairs)), sep='\n' )
修改后的代码
#the max p you can have for your square pair. max_P = number square_pairs = sorted( ((x_square-y_square) // 2, P, x_square, y_square) for parity in (1, 2) for x in range(parity, int((2*max_P)**.5)+1, 2) for y in range(parity, x, 2) if (P := ((x_square:=x**2)+(y_square:=y**2)) // 2) <= max_P ) # 替换starmap和format函数,直接用生成器+F-string格式化 output_lines = '\n'.join(f"{n}\t{p}\t{n_plus_p}\t{p_minus_n}" for n, p, n_plus_p, p_minus_n in square_pairs) print( 'N\tP\tN+P\tP-N\n---------------------------', output_lines, sep='\n' )
修改说明
原代码通过starmap配合str.format函数,将每个元组的元素传入格式化字符串生成输出行。现在直接用生成器遍历square_pairs中的每个元组,借助F-string语法直接拼接出符合格式的字符串,完全避开了starmap和函数调用,同时保证输出结果和原代码完全一致。
内容的提问来源于stack exchange,提问作者Landon Courtney
相关产品推荐
相关产品推荐

