【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]) == 3 checkio([3, 1, 2, 5, 3]) == 3 checkio([1, 300, 2, 200, 1]) == 2 checkio([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-testing if __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 List from 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總結
以上是生活随笔為你收集整理的【Python CheckiO 题解】Median的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浦发万用随借金怎么查 浦发万用随借金账单
- 下一篇: Python 数据分析三剑客之 Pand