如何为Python勾股三元组输出添加英文序数词序号?
给勾股三元组输出添加动态英文序数词序号
问题背景
现有一段生成指定范围内勾股三元组的Python代码,输出仅打印三元组列表,需要修改代码,让每个输出的三元组前自动添加对应的英文序数词(如First、Second),并保持指定的格式对齐。
原代码
def Pythagorean_Triplets(N) : c = 4 m = 2 while c < N : for n in range(1, m) : a = m * m - n * n b = 2 * m * n c = m * m + n * n if c > N : break print([a, b, c]) m = m + 1 N = int(input("\nEnter the value of N uptil which you want to get the Pythagorean Triplets: ")) print(f"\nPythagorean Triplets uptil {N} are: ") Pythagorean_Triplets(N)
原输出示例
Enter the value of N uptil which you want to get the Pythagorean Triplets: 20 Pythagorean Triplets uptil 20 are: [3, 4, 5] [8, 6, 10] [5, 12, 13] [15, 8, 17] [12, 16, 20]
期望输出格式
Enter the value of N uptil which you want to get the Pythagorean Triplets: 20 Pythagorean Triplets uptil 20 are: First list : [3, 4, 5] Second list : [8, 6, 10] Third list : [5, 12, 13] Fourth list : [15, 8, 17] Fifth list : [12, 16, 20]
修改后的代码
def get_ordinal(n): # 基础序数词映射,覆盖常用场景,如需更多可扩展 ordinals = { 1: "First", 2: "Second", 3: "Third", 4: "Fourth", 5: "Fifth", 6: "Sixth", 7: "Seventh", 8: "Eighth", 9: "Ninth", 10: "Tenth", 11: "Eleventh", 12: "Twelfth", 13: "Thirteenth", 14: "Fourteenth", 15: "Fifteenth", 16: "Sixteenth", 17: "Seventeenth", 18: "Eighteenth", 19: "Nineteenth", 20: "Twentieth" } if n in ordinals: return ordinals[n] # 处理大于20的情况,按规则生成序数词 suffix = "th" if n % 10 == 1 and n % 100 != 11: suffix = "st" elif n % 10 == 2 and n % 100 != 12: suffix = "nd" elif n % 10 == 3 and n % 100 != 13: suffix = "rd" return f"{n}{suffix}".capitalize() def Pythagorean_Triplets(N) : c = 4 m = 2 count = 1 # 计数器,记录三元组序号 while c < N : for n in range(1, m) : a = m * m - n * n b = 2 * m * n c = m * m + n * n if c > N : break # 获取序数词并格式化输出 ordinal = get_ordinal(count) print(f"{ordinal} list : {[a, b, c]}") count += 1 m = m + 1 N = int(input("\nEnter the value of N uptil which you want to get the Pythagorean Triplets: ")) print(f"\nPythagorean Triplets uptil {N} are: ") Pythagorean_Triplets(N)
修改说明
- 新增序数词生成函数
get_ordinal:- 内置1-20的标准序数词映射,保证输出格式符合要求;
- 对大于20的数字,通过规则自动生成对应的序数词(如21st、22nd等),适配更多场景。
- 添加序号计数器
count:- 在函数内部初始化计数器,每生成一个有效三元组就递增;
- 打印时调用
get_ordinal获取对应序数词,配合格式化字符串实现对齐输出。
内容的提问来源于stack exchange,提问作者Jerin Joy
相关产品推荐
相关产品推荐

