נבנה על ידיBuilt by Ariel Yohimovich

PythonPython

מבחן 8: מבחן מסכםExam 8: Final exam

כל הקורס: פרויקט קטן מקצה לקצה

The whole course: a small end-to-end project

120 דקותminutes4 שאלות בחירהmultiple choice3 שאלות קודcoding questions100 נקודותpoints
120:00השעון רק עוזר להתאמן. אפשר גם בלי.The timer is just for practice. You can skip it.

חלק א: שאלות בחירה (5 נקודות לשאלה)Part A: multiple choice (5 points each)

התשובות מתגלות רק כשמסיימים את המבחן.Answers are revealed only when you finish the exam.

1. מה יודפס?What is printed? 5
python
def add(x, bag=[]):
    bag.append(x)
    return bag

a = add(1)
add(2)
b = add(3)
print(a, b)
2. איזה מבנה הכי מתאים לבדוק מהר אם משתמש כבר נרשם?Which structure best checks quickly whether a user already registered? 5
3. מה עושה if __name__ == "__main__":?What does if __name__ == "__main__": do? 5
4. מה הפקודה ששומרת את השינויים ב-Git עם הודעה?Which command records changes in Git with a message? 5

חלק ב: שאלות קודPart B: coding questions

שאלהQuestion 5

ספריית שירים: מודלA song library: the model

כתבו @dataclass Song(title, artist, seconds) עם property length שמחזירה "M:SS", ומחלקה Library עם add(song) (כפילות של אותו title ואותו artist זורקת ValueError("duplicate")), total() בשניות, ו-by_artist(name) שמחזירה רשימת כותרות ממוינת (בלי תלות באותיות גדולות בשם האמן).

Write @dataclass Song(title, artist, seconds) with a length property returning "M:SS", and a Library class with add(song) (a duplicate of the same title and artist raises ValueError("duplicate")), total() in seconds, and by_artist(name) returning a sorted list of titles (case-insensitive on the artist's name).

איך הפלט אמור להיראות?What should the output look like?
duplicate
446 ['Dawn', 'Rain'] 1:01
main.py
רמזHint 1: שמרו set של (title.lower(), artist.lower()).Keep a set of (title.lower(), artist.lower()).
הפתרון שלנוOur solution
main.py
from dataclasses import dataclass

@dataclass
class Song:
    title: str
    artist: str
    seconds: int

    @property
    def length(self):
        return f"{self.seconds // 60}:{self.seconds % 60:02d}"

class Library:
    def __init__(self):
        self.songs, self._keys = [], set()

    def add(self, song):
        key = (song.title.lower(), song.artist.lower())
        if key in self._keys:
            raise ValueError("duplicate")
        self._keys.add(key)
        self.songs.append(song)

    def total(self):
        return sum(s.seconds for s in self.songs)

    def by_artist(self, name):
        return sorted(s.title for s in self.songs if s.artist.lower() == name.lower())

lib = Library()
for s in [Song("Rain", "Mira", 185), Song("Dawn", "Mira", 200), Song("Echo", "Tal", 61)]:
    lib.add(s)
try:
    lib.add(Song("rain", "MIRA", 1))
except ValueError as e:
    print(e)
print(lib.total(), lib.by_artist("mira"), Song("x", "y", 61).length)
פלטOutput
duplicate
446 ['Dawn', 'Rain'] 1:01

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (25 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

שאלהQuestion 6

ספריית שירים: שמירהA song library: saving

כתבו save_songs(songs, path) ששומרת רשימת מילונים {title, artist, seconds} ל-JSON, ו-load_songs(path) שמחזירה את הרשימה, או רשימה ריקה אם הקובץ חסר או פגום. וגם stats(songs) שמחזירה מילון {"count": n, "longest": title או None, "avg": ממוצע שניות מעוגל לשלם}.

Write save_songs(songs, path) saving a list of {title, artist, seconds} dicts to JSON, and load_songs(path) returning the list, or an empty list if the file is missing or broken. And stats(songs) returning a dict {"count": n, "longest": a title or None, "avg": average seconds rounded to an int}.

איך הפלט אמור להיראות?What should the output look like?
{'count': 2, 'longest': 'Rain', 'avg': 123} []
main.py
רמזHint 1: except (FileNotFoundError, json.JSONDecodeError).except (FileNotFoundError, json.JSONDecodeError).
רמזHint 2: ממוצע של רשימה ריקה הוא 0.The average of an empty list is 0.
הפתרון שלנוOur solution
main.py
import json
from pathlib import Path

def save_songs(songs, path):
    Path(path).write_text(json.dumps(songs, ensure_ascii=False), encoding="utf-8")

def load_songs(path):
    try:
        return json.loads(Path(path).read_text(encoding="utf-8"))
    except (FileNotFoundError, json.JSONDecodeError):
        return []

def stats(songs):
    if not songs:
        return {"count": 0, "longest": None, "avg": 0}
    longest = max(songs, key=lambda s: s["seconds"])
    return {"count": len(songs), "longest": longest["title"], "avg": round(sum(s["seconds"] for s in songs) / len(songs))}

songs = [{"title": "Rain", "artist": "Mira", "seconds": 185}, {"title": "Echo", "artist": "Tal", "seconds": 61}]
save_songs(songs, "songs.json")
print(stats(load_songs("songs.json")), load_songs("nothing.json"))
פלטOutput
{'count': 2, 'longest': 'Rain', 'avg': 123} []

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (25 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

שאלהQuestion 7

ספריית שירים: פלייליסטA song library: a playlist

כתבו playlist(songs, limit) שבוחרת שירים (רשימת מילונים) כך שסך השניות הכי קרוב ל-limit בלי לעבור אותו, ומחזירה (total, titles) כש-titles לפי הסדר המקורי. בתיקו, הבחירה שמגיעה ראשונה בסריקה (תכנות דינמי על הסכומים: לכל סכום שומרים את הבחירה הראשונה שהגיעה אליו).

Write playlist(songs, limit) choosing songs (a list of dicts) so the total seconds is as close to limit as possible without going over, and return (total, titles) with titles in their original order. On a tie, the choice reached first in the scan (dynamic programming over sums: for each sum keep the first choice that reached it).

איך הפלט אמור להיראות?What should the output look like?
(576, ['Rain', 'Dawn', 'Echo', 'Tide'])
(0, [])
main.py
רמזHint 1: best = {0: []} ולכל שיר מעדכנים עותק של המילון.best = {0: []} and for each song update a copy of the dict.
רמזHint 2: עוברים על list(best.items()) כדי לא לשנות בזמן לולאה.Loop over list(best.items()) to avoid changing it while looping.
הפתרון שלנוOur solution
main.py
def playlist(songs, limit):
    best = {0: []}
    for i, song in enumerate(songs):
        for total, picked in list(best.items()):
            new = total + song["seconds"]
            if new <= limit and new not in best:
                best[new] = picked + [i]
    total = max(best)
    return total, [songs[i]["title"] for i in best[total]]

songs = [{"title": t, "seconds": s} for t, s in [("Rain", 185), ("Dawn", 200), ("Echo", 61), ("Glow", 240), ("Tide", 130)]]
print(playlist(songs, 600))
print(playlist(songs, 60))
פלטOutput
(576, ['Rain', 'Dawn', 'Echo', 'Tide'])
(0, [])

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (30 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

נבנה על ידיBuilt by Ariel Yohimovich