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.
חלק ב: שאלות קוד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):returnf"{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):returnsum(s.seconds for s in self.songs)
def by_artist(self, name):returnsorted(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?
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.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 inenumerate(songs):for total, picked inlist(best.items()):
new = total + song["seconds"]
if new <= limit and new notin 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.