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

جواب «Recommend» چالش 5 از جلسه‌ی 37

سؤال

تابع recommend(user) بنویس: شبیه‌ترین کاربر را پیدا کن و بازی‌هایی را برگردان که او امتیاز ۴ یا بیشتر داده ولی user هنوز امتیاز نداده. خروجی برای nika و arad: [] و ['puzzle']. (برای نیکا، سارا به فوتبال ۱ داده، پس پیشنهادی نیست.)

راهنما

friend = most_similar(user)؛ for game, score in ratings[friend].items(): if game not in ratings[user] and score >= 4: result.append(game).

یک جواب درست

ratings = {
    "sara": {"chess": 5, "racing": 2, "puzzle": 4, "football": 1},
    "omid": {"chess": 1, "racing": 5, "puzzle": 2, "football": 5},
    "nika": {"chess": 4, "racing": 1, "puzzle": 5},
    "arad": {"chess": 2, "racing": 4, "football": 4},
}


def similarity(a, b):
    shared = [game for game in a if game in b]
    if not shared:
        return 0
    return 1 / (1 + sum(abs(a[g] - b[g]) for g in shared))


def most_similar(user):
    others = [o for o in ratings if o != user]
    return max(others, key=lambda o: similarity(ratings[user], ratings[o]))


def recommend(user):
    friend = most_similar(user)
    result = []
    for game, score in ratings[friend].items():
        if game not in ratings[user] and score >= 4:
            result.append(game)
    return result


print(recommend("nika"))
print(recommend("arad"))

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