جواب «Track C: Group Averages and Correlation» چالش 3 از جلسهی 78
سؤال
مسیر پ. جدول ناشناس را بخوان. ۱) میانگین نمرهی گروه low (ساعت مطالعه ۲ یا کمتر) و گروه high (۳ یا بیشتر). ۲) تابع pearson(xs, ys) را بنویس: Σ(x−x̄)(y−ȳ) / √(Σ(x−x̄)² × Σ(y−ȳ)²). همبستگی مطالعه با نمره و خواب با نمره را با دو رقم اعشار چاپ کن. خروجی:low study: average mark 12.75high study: average mark 17.50study vs mark: r = 0.96sleep vs mark: r = -0.06
راهنما
mx, my = sum(xs) / len(xs), sum(ys) / len(ys)؛ top = sum((x - mx) * (y - my) for x, y in zip(xs, ys))؛ پایین: math.sqrt(sum((x - mx) ** 2 for x in xs) * sum((y - my) ** 2 for y in ys)).
یک جواب درست
import csv
import io
import math
DATA = '''id,study_hours,sleep_hours,mark
S1,2,8,15
S2,4,7,18
S3,1,6,11
S4,3,9,17
S5,5,6,19
S6,2,7,13
S7,3,8,16
S8,1,9,12'''
rows = list(csv.DictReader(io.StringIO(DATA)))
study = [float(r["study_hours"]) for r in rows]
sleep = [float(r["sleep_hours"]) for r in rows]
mark = [float(r["mark"]) for r in rows]
def pearson(xs, ys):
mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
top = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
bottom = math.sqrt(sum((x - mx) ** 2 for x in xs) * sum((y - my) ** 2 for y in ys))
return top / bottom
low = [m for s, m in zip(study, mark) if s <= 2]
high = [m for s, m in zip(study, mark) if s >= 3]
print(f"low study: average mark {sum(low) / len(low):.2f}")
print(f"high study: average mark {sum(high) / len(high):.2f}")
print(f"study vs mark: r = {pearson(study, mark):.2f}")
print(f"sleep vs mark: r = {pearson(sleep, mark):.2f}")
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن