pythontip 第n小的数
编写一个Python程序,找出列表中第n小的整数。
定义函数find_nth_smallest(),该函数接受整数列表numbers_list和整数n作为参数。
在函数内部,返回列表中第n小的整数。
如果n大于列表的长度,则返回None。
- 这道题关键在输入的数据为无序,若判断大小则可以使用排序函数sorted()
![image]()
- 以上的内容不能通过,因为还未判断n的越界,len()判断n的越界
点击查看代码
def find_nth_smallest(numbers_list, n):
if n>len(numbers_list):
return None
else:
sorted_list=sorted(numbers_list)
return sorted_list[n-1]
# 将输入的整数转换为列表
numbers_list = list(map(int, input().split()))
# 获取n的输入
n = int(input())
# 调用函数
print(find_nth_smallest(numbers_list, n))

浙公网安备 33010602011771号