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

PythonPython

מבחן 3: אוספיםExam 3: Collections

רשימות, מילונים, קבוצות, טאפלים ו-comprehensions

Lists, dicts, sets, tuples and comprehensions

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. מה יודפס?What is printed? 5
python
a = [1, 2, 3]
b = a
b.append(4)
print(a)
2. מה התוצאה של {1, 2, 2, 3} | {3, 4}?What's {1, 2, 2, 3} | {3, 4}? 5
3. מה יודפס?What is printed? 5
python
print([n * n for n in range(5) if n % 2 == 0])
4. מה מחזיר d.get("z", 0) כש-z לא במילון?What does d.get("z", 0) return when z isn't in the dict? 5

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

שאלהQuestion 5

תדירות מיליםWord frequency

כתבו top_words(text, n) שמחזירה רשימת n המילים הנפוצות כטאפלים (word, count), מהנפוצה ביותר; בתיקו, לפי סדר אלפביתי. התעלמו מאותיות גדולות ומהסימנים .,!?.

Write top_words(text, n) returning the n most common words as (word, count) tuples, most common first; on a tie, alphabetically. Ignore case and the marks .,!?.

איך הפלט אמור להיראות?What should the output look like?
[('the', 3), ('cat', 2), ('a', 1)]
main.py
רמזHint 1: text.lower() ואז strip(".,!?") לכל מילה.text.lower() then strip(".,!?") for each word.
רמזHint 2: מיון לפי (-count, word).Sort by (-count, word).
הפתרון שלנוOur solution
main.py
def top_words(text, n):
    counts = {}
    for word in text.lower().split():
        word = word.strip(".,!?")
        if word:
            counts[word] = counts.get(word, 0) + 1
    return sorted(counts.items(), key=lambda p: (-p[1], p[0]))[:n]

print(top_words("The cat. The dog! A cat, the end?", 3))
פלטOutput
[('the', 3), ('cat', 2), ('a', 1)]

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

היפוך מילוןInverting a dict

כתבו invert(d) שמקבלת מילון {name: group} ומחזירה {group: [names...]} כשהשמות בכל קבוצה ממוינים, והקבוצות לפי סדר הופעתן הראשון.

Write invert(d) taking a dict {name: group} and returning {group: [names...]} with names in each group sorted, and groups in order of first appearance.

איך הפלט אמור להיראות?What should the output look like?
{'red': ['ari', 'noa'], 'blue': ['dan']}
main.py
רמזHint 1: setdefault(group, []).append(name).setdefault(group, []).append(name).
הפתרון שלנוOur solution
main.py
def invert(d):
    out = {}
    for name, group in d.items():
        out.setdefault(group, []).append(name)
    return {g: sorted(names) for g, names in out.items()}

print(invert({"noa": "red", "dan": "blue", "ari": "red"}))
פלטOutput
{'red': ['ari', 'noa'], 'blue': ['dan']}

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

כתבו transpose(grid) שמחזירה את הטרנספוזה של רשימת רשימות (שורות הופכות לעמודות), ו-spiral(grid) שמחזירה את כל האיברים בסדר ספירלי עם כיוון השעון מהפינה השמאלית העליונה.

Write transpose(grid) returning the transpose of a list of lists (rows become columns), and spiral(grid) returning all items in clockwise spiral order from the top-left corner.

איך הפלט אמור להיראות?What should the output look like?
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
[1, 2, 3, 6, 9, 8, 7, 4, 5] [1, 2, 3]
main.py
רמזHint 1: [list(col) for col in zip(*grid)].[list(col) for col in zip(*grid)].
רמזHint 2: ספירלה: לוקחים את השורה הראשונה, ומסובבים את השאר נגד כיוון השעון.Spiral: take the first row, then rotate the rest counter-clockwise.
הפתרון שלנוOur solution
main.py
def transpose(grid):
    return [list(col) for col in zip(*grid)]

def spiral(grid):
    grid = [row[:] for row in grid]
    out = []
    while grid:
        out += grid.pop(0)
        grid = transpose(grid)[::-1]
    return out

g = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(transpose(g))
print(spiral(g), g[0])
פלטOutput
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
[1, 2, 3, 6, 9, 8, 7, 4, 5] [1, 2, 3]

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