初心者向けのPythonのプログラミング問題です。入門編としてチャレンジしてください。Pythonの正答例は以下になります。
問題748
def mean_value(lst):
if not lst:
return None
return sum(lst) / len(lst)
# 呼び出し例
print(mean_value([2, 4, 6])) # 出力: 4.0
問題749
def median_value(lst):
if not lst:
return None
s = sorted(lst)
n = len(s)
return s[n//2] if n % 2 else (s[n//2-1] + s[n//2]) / 2
# 呼び出し例
print(median_value([1, 3, 2, 4])) # 出力: 2.5
問題750
from collections import Counter
def mode_value(lst):
if not lst:
return None
c = Counter(lst)
max_freq = max(c.values())
candidates = [x for x,v in c.items() if v == max_freq]
return min(candidates)
# 呼び出し例
print(mode_value([1,2,2,3,3])) # 出力: 2



コメント