初心者向けのPythonのプログラミング問題です。入門編としてチャレンジしてください。Pythonの正答例は以下になります。
問題751
def quantile(lst, p):
if not lst or not (0 le; p le; 1):
return None
s = sorted(lst)
idx = int(p * (len(s) – 1))
return s[idx]
# 呼び出し例
print(quantile([1,3,5,7,9], 0.25)) # 出力: 3
問題752
def variance_population(lst):
if not lst:
return None
mu = sum(lst) / len(lst)
return sum((x – mu) ** 2 for x in lst) / len(lst)
# 呼び出し例
print(round(variance_population([2,4,4,4,5,5,7,9]), 2)) # 出力: 4.0
問題753
from collections import Counter
def sort_by_freq_then_alpha(words):
c = Counter(words)
return sorted(words, key=lambda w: (-c[w], w))
# 呼び出し例
print(sort_by_freq_then_alpha([“apple”,”banana”,”apple”,”avocado”]))
# 出力例: [‘apple’,’apple’,’avocado’,’banana’]


コメント