当前位置:首页 >> 编程语言 >> 【Python CheckiO 题解】Median,东芝G900

【Python CheckiO 题解】Median,东芝G900

0evadmin 编程语言 1
文件名:【Python CheckiO 题解】Median,东芝G900 【Python CheckiO 题解】Median

CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,本博客主要记录自己用 Python 在闯关时的做题思路和实现代码,同时也学习学习其他大神写的代码。

CheckiO 官网:https://checkio.org/

我的 CheckiO 主页:https://py.checkio.org/user/TRHX/

CheckiO 题解系列专栏:https://itrhx.blog.csdn.net/category_9536424.html

CheckiO 所有题解源代码:https://github.com/TRHX/Python-CheckiO-Exercise


题目描述

【Median】:给定一个数组,查找其中位数,如果数组的元素个数是偶数,则返回中间两个元素的平均值。

【链接】:https://py.checkio.org/mission/median/

【输入】:由整数组成的数组(list)

【输出】:数组的中位数(int or float)

【前提】:1 < len(data) ≤ 1000;all(0 ≤ x < 10 ** 6 for x in data)

【范例】:

checkio([1, 2, 3, 4, 5]) == 3checkio([3, 1, 2, 5, 3]) == 3checkio([1, 300, 2, 200, 1]) == 2checkio([3, 6, 20, 99, 10, 15]) == 12.5 解题思路

先用 sort() 方法将数组元素按照从小到大排序,利用数组的长度除以 2 来判断其元素个数是奇数还是偶数。

代码实现 from typing import Listdef checkio(data: List[int]) -> [int, float]:data.sort()if len(data) % 2 == 0:return (data[int(len(data)/2) - 1] + data[int(len(data)/2)])/2else:return data[int(len(data)/2)]# These "asserts" using only for self-checking and not necessary for auto-testingif __name__ == '__main__':print("Example:")print(checkio([1, 2, 3, 4, 5]))assert checkio([1, 2, 3, 4, 5]) == 3, "Sorted list"assert checkio([3, 1, 2, 5, 3]) == 3, "Not sorted list"assert checkio([1, 300, 2, 200, 1]) == 2, "It's not an average"assert checkio([3, 6, 20, 99, 10, 15]) == 12.5, "Even length"print("Start the long test")assert checkio(list(range(1000000))) == 499999.5, "Long."print("Coding complete? Click 'Check' to earn cool rewards!") 大神解答 大神解答 NO.1 from typing import Listfrom statistics import mediandef checkio(data: List[int]) -> [int, float]:return median(data)

statistics 模块的 median 方法可以直接求中位数!

大神解答 NO.2 from typing import Listdef checkio(data: List[int]) -> [int, float]:data = sorted(data)l = len(data) return [(data[l//2]+data[l//2-1])/2, data[l//2]][l%2] 大神解答 NO.3 from typing import Listdef checkio(data):data.sort()half = len(data) // 2return (data[half] + data[~half]) / 2
协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接