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

PythonPython

מבחן 5: קבצים, נתונים ובדיקותExam 5: Files, data and tests

JSON, CSV, חריגות, pathlib ו-pytest

JSON, CSV, exceptions, pathlib and pytest

75 דקותminutes4 שאלות בחירהmultiple choice3 שאלות קודcoding questions100 נקודותpoints
75: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. למה עדיף with open(...) as f?Why prefer with open(...) as f? 5
2. מה יקרה?What happens? 5
python
try:
    n = int("x")
except ValueError:
    print("bad")
3. מה מחזיר json.loads('[1, 2]')?What does json.loads('[1, 2]') return? 5
4. איך pytest מוצא בדיקות?How does pytest find tests? 5

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

שאלהQuestion 5

יומן אימוניםA training log

כתבו add_run(path, km) שמוסיפה ריצה לקובץ JSON (רשימת מספרים; קובץ חסר = רשימה ריקה) ומחזירה את הסכום הכולל. ו-best(path) שמחזירה את הריצה הארוכה ביותר או 0.

Write add_run(path, km) appending a run to a JSON file (a list of numbers; a missing file = an empty list) and returning the total. And best(path) returning the longest run or 0.

איך הפלט אמור להיראות?What should the output look like?
0 5 13.5 8.5
main.py
רמזHint 1: Path(path).exists().Path(path).exists().
רמזHint 2: json.loads(p.read_text()).json.loads(p.read_text()).
הפתרון שלנוOur solution
main.py
import json
from pathlib import Path

def _load(path):
    p = Path(path)
    return json.loads(p.read_text()) if p.exists() else []

def add_run(path, km):
    runs = _load(path) + [km]
    Path(path).write_text(json.dumps(runs))
    return sum(runs)

def best(path):
    return max(_load(path), default=0)

print(best("runs.json"), add_run("runs.json", 5), add_run("runs.json", 8.5), best("runs.json"))
פלטOutput
0 5 13.5 8.5

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.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

ניקוי נתוניםCleaning data

כתבו clean(rows) שמקבלת רשימת מילונים עם name ו-age (מחרוזות). החזירו (good, errors): good רשימת מילונים עם name נקי (strip, title) ו-age כ-int בין 0 ל-120; errors רשימת אינדקסים של שורות פסולות.

Write clean(rows) taking a list of dicts with name and age (strings). Return (good, errors): good is a list of dicts with a clean name (strip, title) and age as an int between 0 and 120; errors is a list of indexes of rejected rows.

איך הפלט אמור להיראות?What should the output look like?
([{'name': 'Noa Levi', 'age': 31}, {'name': 'Lia', 'age': 0}], [1, 2, 3])
main.py
רמזHint 1: try: int(...) בתוך הלולאה.try: int(...) inside the loop.
רמזHint 2: שם ריק אחרי strip הוא שגיאה.A name empty after strip is an error.
הפתרון שלנוOur solution
main.py
def clean(rows):
    good, errors = [], []
    for i, row in enumerate(rows):
        name = row.get("name", "").strip().title()
        try:
            age = int(row.get("age", ""))
        except ValueError:
            age = -1
        if not name or not 0 <= age <= 120:
            errors.append(i)
        else:
            good.append({"name": name, "age": age})
    return good, errors

rows = [{"name": " noa levi ", "age": "31"}, {"name": "", "age": "20"}, {"name": "dan", "age": "abc"}, {"name": "ari", "age": "130"}, {"name": "lia", "age": "0"}]
print(clean(rows))
פלטOutput
([{'name': 'Noa Levi', 'age': 31}, {'name': 'Lia', 'age': 0}], [1, 2, 3])

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.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

כתבו בדיקותWrite tests

נתונה slugify(title): אותיות קטנות, רווחים הופכים ל--, ושאר התווים שאינם אותיות או ספרות נמחקים. כתבו את הפונקציה ואחריה לפחות 4 פונקציות test_... שבודקות אותה עם assert (כולל מקרה קצה של מחרוזת ריקה). בסוף הריצו את כל הבדיקות בעצמכם והדפיסו N tests passed.

Given slugify(title): lowercase, spaces become -, and other characters that aren't letters or digits are removed. Write the function followed by at least 4 test_... functions checking it with assert (including the empty-string edge case). At the end run all the tests yourself and print N tests passed.

איך הפלט אמור להיראות?What should the output look like?
4 tests passed
main.py
רמזHint 1: ch.isalnum().ch.isalnum().
רמזHint 2: [f for n, f in globals().items() if n.startswith("test_")].[f for n, f in globals().items() if n.startswith("test_")].
הפתרון שלנוOur solution
main.py
def slugify(title):
    out = []
    for ch in title.lower().strip():
        if ch.isalnum():
            out.append(ch)
        elif ch == " ":
            out.append("-")
    return "".join(out)

def test_basic():
    assert slugify("Hello World") == "hello-world"

def test_symbols():
    assert slugify("Python 3.12!") == "python-312"

def test_empty():
    assert slugify("") == ""

def test_edges():
    assert slugify("  Hi  ") == "hi"

tests = [f for n, f in list(globals().items()) if n.startswith("test_")]
for t in tests:
    t()
print(len(tests), "tests passed")
פלטOutput
4 tests passed

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.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