بتل کد Battle Codeدارد باز می‌شود…

جواب «Track C: A Prediction Line with a Warning» چالش 6 از جلسه‌ی 78

سؤال

مسیر پ. تابع fit(xs, ys) را بنویس که (a, b) خط کمترین مربعات را با فرمول مستقیم برگرداند. بعد predict(hours): اگر hours بیرون از کمترین و بیشترین ساعت داده است، <hours> h: outside the data (<min>-<max> h), not trusted، وگرنه <hours> h: about <mark> (یک رقم اعشار). خروجی:
mark = 1.97 * hours + 9.95
2.5 h: about 14.9
4 h: about 17.8
10 h: outside the data (1-5 h), not trusted
Remember: correlation is not cause.

راهنما

mx = sum(xs) / len(xs) و همین برای my؛ a = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs)؛ b = my - a * mx. در predict: if hours < min(STUDY) or hours > max(STUDY):.

یک جواب درست

STUDY = [2, 4, 1, 3, 5, 2, 3, 1]
MARK = [15, 18, 11, 17, 19, 13, 16, 12]


def fit(xs, ys):
    mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
    a = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs)
    b = my - a * mx
    return a, b


a, b = fit(STUDY, MARK)
print(f"mark = {a:.2f} * hours + {b:.2f}")


def predict(hours):
    low, high = min(STUDY), max(STUDY)
    if hours < low or hours > high:
        return f"{hours} h: outside the data ({low}-{high} h), not trusted"
    return f"{hours} h: about {a * hours + b:.1f}"


for h in [2.5, 4, 10]:
    print(predict(h))
print("Remember: correlation is not cause.")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن