כל יום תרגיל אחר מתוך הקורס, אותו תרגיל לכל מי שנכנס היום. פתרתם? קיבלתם 30 XP בונוס והרצף נשמר.
Every day a different exercise from the course, the same one for everyone who visits today. Solved it? You get a 30 XP bonus and keep your streak.
אתגר חדש בחצות.A new challenge at midnight.
התרגיל של היוםToday's exercise
מפגש 1Session 1
שלום, עולם (בגרסה שלכם)Hello, world (your version)
כתבו תוכנית שמדפיסה שתי שורות: ברכה עם השם שלכם, ומשפט על משהו שאתם אוהבים.
Write a program that prints two lines: a greeting with your name, and a sentence about something you love.
איך הפלט אמור להיראות?What should the output look like?
שלום, אני נועה!
אני אוהבת פיצה וטיולים
Hi, I am Noa!
I love pizza and hiking
main.py
רמזHint 1:כל שורת פלט היא print נפרדת.Each output line is a separate print.
רמזHint 2:טקסט תמיד בתוך מירכאות: print("...").Text always goes inside quotes: print("...").
הפתרון שלנוOur solution
main.py
print("שלום, אני נועה!")
print("אני אוהבת פיצה וטיולים")
print("Hi, I am Noa!")
print("I love pizza and hiking")
פלטOutput
שלום, אני נועה!
אני אוהבת פיצה וטיולים
Hi, I am Noa!
I love pizza and hiking
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 1Session 1
צייד באגיםBug hunter
בקוד הזה יש 3 באגים. הריצו, קראו כל הודעת שגיאה, תקנו אחד-אחד עד שהתוכנית מדפיסה 3 שורות.
This code has 3 bugs. Run it, read each error, fix them one by one until the program prints 3 lines.
איך הפלט אמור להיראות?What should the output look like?
מתחילים!
2 * 21 = 42
סוף
Let's go!
2 * 21 = 42
The end
main.py
רמזHint 1:Python מראה שגיאה אחת בכל פעם. מתקנים, מריצים שוב, ורואים את הבאה.Python shows one error at a time. Fix, run again, see the next.
רמזHint 2:שגיאות תחביר (מירכאות, רווחים) Python מוצאת עוד לפני שהיא מתחילה להריץ.Syntax errors (quotes, spaces) are found before Python even starts running.
רמזHint 3:חפשו: אות גדולה, רווחים בהתחלה, ומירכאות חסרות.Look for: a capital letter, leading spaces, and a missing quote.
a = (1, 2)
b = (4, 6)
x1, y1 = a
x2, y2 = b
print(((x2 - x1) **2+ (y2 - y1) **2) **0.5)
פלטOutput
5.0
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 9Session 9
בודק סיסמהPassword checker
כתבו is_strong(pw) שמחזירה True אם הסיסמה באורך 8 לפחות ויש בה גם ספרה (any(c.isdigit() for c in pw)). הדפיסו את התוצאה עבור "python" ועבור "python2026".
Write is_strong(pw) returning True if the password is at least 8 long and contains a digit (any(c.isdigit() for c in pw)). Print the result for "python" and "python2026".
איך הפלט אמור להיראות?What should the output look like?
False
True
main.py
רמזHint 1:len(pw) >= 8 and ...len(pw) >= 8 and ...
רמזHint 2:מחזירים את הביטוי עצמו.Return the expression itself.
הפתרון שלנוOur solution
main.py
def is_strong(pw):returnlen(pw) >=8andany(c.isdigit() for c in pw)
print(is_strong("python"))
print(is_strong("python2026"))
פלטOutput
False
True
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 10Session 10
עצרת ברקורסיהRecursive factorial
כתבו factorial(n) רקורסיבית: factorial(0) היא 1, ו-factorial(n) היא n * factorial(n - 1). הדפיסו את factorial(6).
Write a recursive factorial(n): factorial(0) is 1, and factorial(n) is n * factorial(n - 1). Print factorial(6).
איך הפלט אמור להיראות?What should the output look like?
720
main.py
רמזHint 1:תנאי עצירה: if n == 0: return 1.Stop condition: if n == 0: return 1.
הפתרון שלנוOur solution
main.py
def factorial(n):if n ==0:return1return n * factorial(n -1)
print(factorial(6))
פלטOutput
720
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 12Session 12
שמירת רשימהSave a list
כתבו את שלושת הספרים ברשימה books לקובץ books.txt, ספר בשורה. אחר כך קראו את הקובץ והדפיסו כמה שורות יש בו.
Write the three books in books to books.txt, one per line. Then read the file back and print how many lines it has.
איך הפלט אמור להיראות?What should the output look like?
3
main.py
רמזHint 1:לולאה עם f.write(b + "\n").A loop with f.write(b + "\n").
רמזHint 2:len(f.readlines()) או לולאה.len(f.readlines()) or a loop.
הפתרון שלנוOur solution
main.py
books = ["Dune", "Emma", "Matilda"]
withopen("books.txt", "w", encoding="utf-8") as f:for b in books:
f.write(b +"\n")
withopen("books.txt", encoding="utf-8") as f:print(len(f.readlines()))
פלטOutput
3
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 13Session 13
מגריל ספריםBook picker
השתמשו ב-random עם seed(1) כדי לבחור ספר אקראי מהרשימה ולהדפיס אותו, ואז הדפיסו את הרשימה מעורבבת (shuffle).
Use random with seed(1) to pick a random book from the list and print it, then print the list shuffled (shuffle).
איך הפלט אמור להיראות?What should the output look like?
class Dog:def __init__(self, name, sound="Woof"):
self.name = name
self.sound = sound
def speak(self):returnf"{self.name} says {self.sound}"print(Dog("Rex").speak())
פלטOutput
Rex says Woof
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 16Session 16
חיות מדברותTalking animals
כתבו Animal עם name ומתודה speak() שמחזירה "...". צרו Dog ו-Cat שיורשות ודורסות את speak ("Woof", "Meow"). הדפיסו name: sound לכל חיה ברשימה.
Write Animal with name and a speak() method returning "...". Create Dog and Cat that inherit and override speak ("Woof", "Meow"). Print name: sound for each animal in a list.
איך הפלט אמור להיראות?What should the output look like?
Rex: Woof
Tom: Meow
Fish: ...
main.py
רמזHint 1:class Dog(Animal): ובתוכה רק speak.class Dog(Animal): with only speak inside.
class Animal:def __init__(self, name):
self.name = name
def speak(self):return"..."class Dog(Animal):def speak(self):return"Woof"class Cat(Animal):def speak(self):return"Meow"for a in [Dog("Rex"), Cat("Tom"), Animal("Fish")]:print(f"{a.name}: {a.speak()}")
פלטOutput
Rex: Woof
Tom: Meow
Fish: ...
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 17Session 17
נקודה מודפסתA printable point
כתבו Point(x, y) עם __str__ שמחזירה (x, y) ו-__repr__ שמחזירה Point(x=1, y=2). הדפיסו נקודה ואת הרשימה [Point(1, 2)].
Write Point(x, y) with __str__ returning (x, y) and __repr__ returning Point(x=1, y=2). Print a point and the list [Point(1, 2)].
איך הפלט אמור להיראות?What should the output look like?
רמזHint 2:רשימה מדפיסה repr של כל פריט.A list prints each item's repr.
הפתרון שלנוOur solution
main.py
class Point:def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):returnf"({self.x}, {self.y})"def __repr__(self):returnf"Point(x={self.x}, y={self.y})"
p = Point(1, 2)
print(p)
print([p])
פלטOutput
(1, 2)
[Point(x=1, y=2)]
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 18Session 18
להוסיף רמזיםAdd hints
הוסיפו רמזי טיפוס לכל הפרמטרים ולערכי ההחזרה: average(nums) מקבלת רשימת float ומחזירה float, ו-greet(name, times) מקבלת str ו-int ומחזירה str.
Add type hints to every parameter and return value: average(nums) takes a list of float and returns float, and greet(name, times) takes str and int and returns str.
איך הפלט אמור להיראות?What should the output look like?
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 20Session 20
מה ייכנס ל-Git?What goes into Git?
כתבו ignored(path, patterns) שמחזירה True אם הנתיב תואם לאחת התבניות. תבנית שמסתיימת ב-/ היא תיקייה (מתאימה אם הנתיב מתחיל בה או מכיל אותה), ושאר התבניות נבדקות מול שם הקובץ עם fnmatch. ואז to_commit(paths, patterns) מחזירה את מה שלא מתעלמים ממנו.
Write ignored(path, patterns) returning True if the path matches a pattern. A pattern ending in / is a folder (matches if the path starts with it or contains it); others are checked against the file name with fnmatch. Then to_commit(paths, patterns) returns the paths not ignored.
איך הפלט אמור להיראות?What should the output look like?
['shelf.py', 'README.md']
main.py
רמזHint 1:from fnmatch import fnmatch ו-path.split("/")[-1] לשם הקובץ.from fnmatch import fnmatch and path.split("/")[-1] for the name.
רמזHint 2:תיקייה: path.startswith(p) or "/" + p in "/" + path.Folder: path.startswith(p) or "/" + p in "/" + path.
הפתרון שלנוOur solution
main.py
from fnmatch import fnmatch
def ignored(path, patterns):
name = path.split("/")[-1]
for p in patterns:if p.endswith("/"):if path.startswith(p) or"/"+ p in"/"+ path:returnTrueelif fnmatch(name, p):returnTruereturnFalsedef to_commit(paths, patterns):return [p for p in paths ifnot ignored(p, patterns)]
patterns = [".venv/", "__pycache__/", "*.pyc", ".env"]
files = ["shelf.py", ".env", ".venv/bin/python", "src/__pycache__/a.pyc", "README.md", "old.pyc"]
print(to_commit(files, patterns))
פלטOutput
['shelf.py', 'README.md']
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 21Session 21
ציונים מ-CSVGrades from CSV
הקוד יוצר grades.csv. קראו אותו עם DictReader והדפיסו את הממוצע (מעוגל ל-1) ואת שם התלמיד עם הציון הגבוה ביותר.
The code creates grades.csv. Read it with DictReader and print the average (rounded to 1) and the name of the student with the highest grade.
איך הפלט אמור להיראות?What should the output look like?
87.3
Avi
main.py
רמזHint 1:int(r["grade"]) לכל שורה.int(r["grade"]) for each row.
def explain(code):
kinds = {2:"ok", 3:"redirect", 4:"client error", 5:"server error"}
return kinds.get(code //100, "unknown")
for c in [200, 404, 503, 301, 99]:print(c, explain(c))
פלטOutput
200 ok
404 client error
503 server error
301 redirect
99 unknown
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 23Session 23
חיפוש בטוחA safe search
בעזרת הטבלה הנתונה, כתבו by_author(con, name) שמחזירה רשימת כותרות של הסופר (חיפוש חלקי, LIKE עם %), ממוינת לפי שנה. השתמשו ב-? בלבד.
Using the given table, write by_author(con, name) returning the author's titles (partial match, LIKE with %), sorted by year. Use ? only.
איך הפלט אמור להיראות?What should the output look like?
['The BFG', 'Matilda']
[]
main.py
רמזHint 1:הערך עצמו מכיל את ה-%: ("%" + name + "%",)The value itself carries the %: ("%" + name + "%",)
רמזHint 2:[r[0] for r in ...][r[0] for r in ...]
הפתרון שלנוOur solution
main.py
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT, pages INTEGER, year INTEGER)")
con.executemany("INSERT INTO books (title, author, pages, year) VALUES (?, ?, ?, ?)", [
("Dune", "Frank Herbert", 412, 1965), ("Emma", "Jane Austen", 474, 1815),
("Matilda", "Roald Dahl", 240, 1988), ("The BFG", "Roald Dahl", 208, 1982),
])
def by_author(con, name):
rows = con.execute("SELECT title FROM books WHERE author LIKE ? ORDER BY year", ("%"+ name +"%",))
return [r[0] for r in rows]
print(by_author(con, "dahl"))
print(by_author(con, "x' OR '1'='1"))
פלטOutput
['The BFG', 'Matilda']
[]
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 24Session 24
סינוןFiltering
החזירו מ-picks(df) רשימת כותרות של ספרים עם דירוג 4 ומעלה ופחות מ-300 עמודים, ממוינות לפי מספר עמודים מהקצר לארוך.
Return from picks(df) the titles of books rated 4+ with fewer than 300 pages, sorted by pages shortest first.
איך הפלט אמור להיראות?What should the output look like?
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 27Session 27
דגליםFlags
הוסיפו לפרסר של מחשבון טיפ: amount (float), --percent (int, ברירת מחדל 12) ודגל --round. tip(argv) מחזירה את הטיפ (amount × percent / 100), ואם יש --round מעגלת למספר שלם, אחרת ל-2 ספרות.
Build a tip calculator parser: amount (float), --percent (int, default 12) and a --round flag. tip(argv) returns the tip (amount × percent / 100), rounded to a whole number with --round, otherwise to 2 places.
איך הפלט אמור להיראות?What should the output look like?
רמזHint 2:args.round הוא True או False.args.round is True or False.
הפתרון שלנוOur solution
main.py
import argparse
def tip(argv):
p = argparse.ArgumentParser(prog="tip")
p.add_argument("amount", type=float)
p.add_argument("--percent", type=int, default=12)
p.add_argument("--round", action="store_true")
a = p.parse_args(argv)
value = a.amount * a.percent /100returnround(value) if a.roundelseround(value, 2)
print(tip(["187.5"]), tip(["187.5", "--percent", "15", "--round"]))
פלטOutput
22.5 28
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 28Session 28
סידור עם dry runTidying with a dry run
כתבו plan(folder, rules) שמחזירה רשימת זוגות (שם קובץ, תיקיית יעד) בלי להזיז כלום, ו-apply(folder, rules) שמבצעת את התוכנית ומחזירה כמה קבצים הוזזו. rules הוא מילון סיומת → תיקייה, וכל השאר הולך ל-other.
Write plan(folder, rules) returning pairs (file name, target folder) without moving anything, and apply(folder, rules) carrying out the plan and returning how many files moved. rules is a dict extension → folder, and anything else goes to other.
איך הפלט אמור להיראות?What should the output look like?
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 29Session 29
לוגיקה בלי שרתLogic without a server
כתבו את הלוגיקה של נתיב חיפוש כפונקציה רגילה search(books, q=None, min_pages=0) שמחזירה ספרים שהכותרת או הסופר שלהם מכילים q (בלי רגישות לאותיות; q ריק = כולם) ושיש להם לפחות min_pages עמודים, ממוינים לפי כותרת. כך קל לבדוק אותה, ובשרת מחברים אותה לנתיב.
Write the logic of a search route as a plain function search(books, q=None, min_pages=0) returning books whose title or author contains q (case-insensitive; empty q = all) with at least min_pages pages, sorted by title. That makes it easy to test, and the server just connects it to a route.
איך הפלט אמור להיראות?What should the output look like?
['Matilda', 'The BFG']
['Dune', 'Matilda']
main.py
רמזHint 1:if q and q.lower() not in (b["title"] + " " + b["author"]).lower(): continueif q and q.lower() not in (b["title"] + " " + b["author"]).lower(): continue
def search(books, q=None, min_pages=0):
out = []
for b in books:if q and q.lower() notin (b["title"] +" "+ b["author"]).lower():continueif b["pages"] < min_pages:continue
out.append(b)
returnsorted(out, key=lambda b: b["title"])
BOOKS = [{"title":"Matilda", "author":"Roald Dahl", "pages":240}, {"title":"Dune", "author":"Frank Herbert", "pages":412}, {"title":"The BFG", "author":"Roald Dahl", "pages":208}]
print([b["title"] for b in search(BOOKS, q="DAHL")])
print([b["title"] for b in search(BOOKS, min_pages=230)])
פלטOutput
['Matilda', 'The BFG']
['Dune', 'Matilda']
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 30Session 30
gathergather
כתבו async def fetch_all(titles) שמריצה במקביל fake_fetch(t) לכל כותרת (נתונה: מחכה 0.1 שנייה ומחזירה אורך הכותרת) ומחזירה מילון כותרת → תוצאה. 10 כותרות צריכות לקחת פחות מ-0.5 שנייה.
Write async def fetch_all(titles) running fake_fetch(t) for every title concurrently (given: waits 0.1 seconds and returns the title's length) and returning a dict title → result. 10 titles should take under 0.5 seconds.
איך הפלט אמור להיראות?What should the output look like?
{'Dune': 4, 'Emma': 4, 'The Hobbit': 10}
main.py
רמזHint 1:results = await asyncio.gather(*(fake_fetch(t) for t in titles))results = await asyncio.gather(*(fake_fetch(t) for t in titles))
import asyncio
asyncdef fake_fetch(title):await asyncio.sleep(0.1)
returnlen(title)
asyncdef fetch_all(titles):
results =await asyncio.gather(*(fake_fetch(t) for t in titles))
returndict(zip(titles, results))
print(asyncio.run(fetch_all(["Dune", "Emma", "The Hobbit"])))
פלטOutput
{'Dune': 4, 'Emma': 4, 'The Hobbit': 10}
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 31Session 31
האחסוןThe storage
כתבו load(path) ו-save(path, books) לרשימת Book (המודל נתון): save כותבת דרך קובץ זמני, load מחזירה [] לקובץ חסר, וגם לקובץ פגום (ומדפיסה warning: broken file).
Write load(path) and save(path, books) for a list of Book (the model is given): save writes via a temp file, load returns [] for a missing file, and also for a broken one (printing warning: broken file).
איך הפלט אמור להיראות?What should the output look like?
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 32Session 32
בונה בקשותA prompt builder
כתבו build_prompt(task, examples, rules) שמחזירה מחרוזת: שורה Task: ..., אחריה Examples: ושורה לכל דוגמה - <input> => <output> (עם repr), ואחריה Rules: ושורה לכל כלל - <rule>. בלי כללים: בלי שורת Rules: בכלל.
Write build_prompt(task, examples, rules) returning a string: a Task: ... line, then Examples: and a line per example - <input> => <output> (with repr), then Rules: and a line per rule - <rule>. With no rules: no Rules: line at all.
איך הפלט אמור להיראות?What should the output look like?
Task: Slugify a title
Examples:
- 'Hello World' => 'hello-world'
Rules:
- lowercase
- no punctuation
main.py
רמזHint 1:בונים רשימת שורות ומחברים עם "\n".join.Build a list of lines and join with "\n".join.
def build_prompt(task, examples, rules):
lines = [f"Task: {task}", "Examples:"]
lines += [f"- {inp!r} => {out!r}"for inp, out in examples]
if rules:
lines += ["Rules:"] + [f"- {r}"for r in rules]
return"\n".join(lines)
print(build_prompt("Slugify a title", [("Hello World", "hello-world")], ["lowercase", "no punctuation"]))
פלטOutput
Task: Slugify a title
Examples:
- 'Hello World' => 'hello-world'
Rules:
- lowercase
- no punctuation
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 33Session 33
לחלץ טקסט מתשובהExtracting text from a reply
כתבו reply_text(reply) שמקבלת תשובת API (מילון) ומחזירה את כל קטעי הטקסט מ-content מחוברים (רק פריטים עם type == "text"), ו-token_cost(reply, price_in, price_out) שמחזירה עלות לפי usage (מחיר למיליון טוקנים), מעוגלת ל-6.
Write reply_text(reply) taking an API reply (a dict) and returning all text pieces from content joined (only items with type == "text"), and token_cost(reply, price_in, price_out) returning the cost from usage (price per million tokens), rounded to 6.
איך הפלט אמור להיראות?What should the output look like?
Try Emma. 0.006
main.py
רמזHint 1:"".join(c["text"] for c in reply["content"] if c.get("type") == "text")"".join(c["text"] for c in reply["content"] if c.get("type") == "text")
רמזHint 2:u = reply["usage"]u = reply["usage"]
הפתרון שלנוOur solution
main.py
def reply_text(reply):return"".join(c["text"] for c in reply.get("content", []) if c.get("type") =="text")
def token_cost(reply, price_in, price_out):
u = reply["usage"]
returnround(u["input_tokens"] /1e6* price_in + u["output_tokens"] /1e6* price_out, 6)
reply = {"content": [{"type":"text", "text":"Try "}, {"type":"text", "text":"Emma."}], "usage": {"input_tokens":1000, "output_tokens":200}}
print(reply_text(reply), token_cost(reply, 3, 15))
פלטOutput
Try Emma. 0.006
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 34Session 34
מ-O(n²) ל-O(n)From O(n²) to O(n)
common_slow(a, b) מחזירה את הפריטים של a שמופיעים גם ב-b (בסדר של a, בלי כפילויות), אבל היא O(n²). כתבו common_fast(a, b) שמחזירה אותה תוצאה ב-O(n) בעזרת set.
common_slow(a, b) returns a's items that also appear in b (in a's order, no duplicates), but it's O(n²). Write common_fast(a, b) returning the same result in O(n) using a set.
איך הפלט אמור להיראות?What should the output look like?
['Dune', 'Matilda'] True
main.py
רמזHint 1:in_b = set(b) פעם אחת לפני הלולאה.in_b = set(b) once before the loop.
רמזHint 2:set נוסף seen כדי לא להוסיף פעמיים.Another set seen to avoid adding twice.
הפתרון שלנוOur solution
main.py
def common_slow(a, b):
out = []
for x in a:if x in b and x notin out:
out.append(x)
return out
def common_fast(a, b):
in_b, seen, out =set(b), set(), []
for x in a:if x in in_b and x notin seen:
out.append(x)
seen.add(x)
return out
a = ["Dune", "Emma", "Dune", "Matilda"]
b = ["Matilda", "Dune", "Ulysses"]
print(common_fast(a, b), common_fast(a, b) == common_slow(a, b))
פלטOutput
['Dune', 'Matilda'] True
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 35Session 35
אנגרמות בקבוצותGrouping anagrams
כתבו group_anagrams(words) שמחזירה רשימת קבוצות של מילים שהן אנגרמות זו של זו (בלי רגישות לאותיות). כל קבוצה בסדר ההופעה, והקבוצות לפי הופעת המילה הראשונה שלהן.
Write group_anagrams(words) returning groups of words that are anagrams of each other (case-insensitive). Each group in order of appearance, and groups ordered by their first word's appearance.
איך הפלט אמור להיראות?What should the output look like?
רמזHint 2:dict שומר סדר הכנסה, אז list(groups.values()).A dict keeps insertion order, so list(groups.values()).
הפתרון שלנוOur solution
main.py
def group_anagrams(words):
groups = {}
for w in words:
groups.setdefault("".join(sorted(w.lower())), []).append(w)
returnlist(groups.values())
print(group_anagrams(["listen", "Dune", "silent", "Mame", "enlist", "Emma"]))
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 36Session 36
קריאת pyprojectReading pyproject
כתבו summary(text) שמקבלת תוכן של pyproject.toml ומחזירה מחרוזת name version (python REQ): N deps, commands: a, b, בעזרת tomllib. אם אין scripts, commands: none.
Write summary(text) taking a pyproject.toml's content and returning name version (python REQ): N deps, commands: a, b, using tomllib. With no scripts, commands: none.
איך הפלט אמור להיראות?What should the output look like?
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 37Session 37
הקפצהBouncing
כתבו bounce(pos, vel, r, size) שמזיזה בציר אחד ומחזירה (pos, vel) חדשים: אם הקצה עבר את 0 או את size, הבועה מוחזרת לגבול והמהירות מתהפכת.
Write bounce(pos, vel, r, size) that moves along one axis and returns the new (pos, vel): if the edge passed 0 or size, the bubble is put back on the boundary and the velocity flips.
איך הפלט אמור להיראות?What should the output look like?
(460, -15) (20, 10) (204, 4)
main.py
רמזHint 1:קודם pos += vel.First pos += vel.
רמזHint 2:if pos - r < 0: pos, vel = r, -velif pos - r < 0: pos, vel = r, -vel
הפתרון שלנוOur solution
main.py
def bounce(pos, vel, r, size):
pos += vel
if pos - r <0:
pos, vel = r, -vel
elif pos + r > size:
pos, vel = size - r, -vel
return pos, vel
print(bounce(470, 15, 20, 480), bounce(25, -10, 20, 480), bounce(200, 4, 20, 480))
פלטOutput
(460, -15) (20, 10) (204, 4)
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 38Session 38
חפיפת מלבניםRectangle overlap
בלי pygame: כתבו overlap(a, b) לשני מלבנים כטאפלים (x, y, w, h) שמחזירה True אם הם חופפים (נגיעה בקצה בלבד אינה חפיפה, בדיוק כמו ב-pygame).
Without pygame: write overlap(a, b) for two rects as tuples (x, y, w, h) returning True if they overlap (merely touching edges isn't overlap, exactly as in pygame).
איך הפלט אמור להיראות?What should the output look like?
רמזHint 2:ax < bx + bw and bx < ax + aw and ...ax < bx + bw and bx < ax + aw and ...
הפתרון שלנוOur solution
main.py
def overlap(a, b):
ax, ay, aw, ah = a
bx, by, bw, bh = b
return ax < bx + bw and bx < ax + aw and ay < by + bh and by < ay + ah
print(overlap((0, 0, 10, 10), (5, 5, 10, 10)), overlap((0, 0, 10, 10), (10, 0, 5, 5)), overlap((0, 0, 10, 10), (2, 2, 3, 3)))
פלטOutput
True False True
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 39Session 39
יריב הוגןA fair opponent
כתבו ai_move(paddle_y, ball_y, speed, dead=4) שמחזירה את מיקום המחבט החדש: מתקרב לכדור לכל היותר speed פיקסלים, לא עובר אותו, ולא זז אם ההפרש קטן או שווה ל-dead.
Write ai_move(paddle_y, ball_y, speed, dead=4) returning the paddle's new position: moves toward the ball by at most speed pixels, never past it, and doesn't move if the gap is at most dead.
איך הפלט אמור להיראות?What should the output look like?
רמזHint 2:paddle_y + max(-speed, min(speed, gap)) כשהפער גדול מ-dead.paddle_y + max(-speed, min(speed, gap)) when the gap exceeds dead.
הפתרון שלנוOur solution
main.py
def ai_move(paddle_y, ball_y, speed, dead=4):
gap = ball_y - paddle_y
ifabs(gap) <= dead:return paddle_y
return paddle_y +max(-speed, min(speed, gap))
print([ai_move(160, b, 6) for b in (162, 200, 100, 165)])
פלטOutput
[160, 166, 154, 165]
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 40Session 40
צעד של נחשA snake step
כתבו step(snake, direction, food, cols, rows) שמחזירה (new_snake, ate, alive): ראש חדש עם מעבר מקצה לקצה; אם הראש על האוכל, הנחש גדל (ate=True); אחרת הזנב נמחק. אם הראש פוגע בגוף (בלי הזנב, אלא אם גדלים), alive=False והנחש לא משתנה.
Write step(snake, direction, food, cols, rows) returning (new_snake, ate, alive): a new head with wrap-around; if the head is on the food, the snake grows (ate=True); otherwise the tail is removed. If the head hits the body (excluding the tail, unless growing), alive=False and the snake is unchanged.
איך הפלט אמור להיראות?What should the output look like?
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 41Session 41
פגיעה לפי צדA hit by side
בלי pygame: כתבו move(ball, vx, vy, bricks) כשהכדור והלבנים הם רשימות [x, y, w, h]. מזיזים ב-x, אם יש חפיפה עם לבנה מוחקים אותה והופכים vx (ומחזירים את x אחורה); ואז אותו דבר ב-y. מחזירה (vx, vy, removed) כש-removed הוא מספר הלבנים שנמחקו.
Without pygame: write move(ball, vx, vy, bricks) where the ball and bricks are [x, y, w, h] lists. Move along x; if it overlaps a brick, remove it and flip vx (and move x back); then the same on y. Return (vx, vy, removed) where removed is the number of bricks removed.
איך הפלט אמור להיראות?What should the output look like?
(0, 4, 1) []
main.py
רמזHint 1:פונקציית עזר first_hit(ball, bricks) שמחזירה אינדקס או -1.A helper first_hit(ball, bricks) returning an index or -1.
רמזHint 2:אחרי היפוך: ball[0] += vx מחזיר את הכדור החוצה.After flipping: ball[0] += vx moves the ball back out.
הפתרון שלנוOur solution
main.py
def overlap(a, b):return a[0] < b[0] + b[2] and b[0] < a[0] + a[2] and a[1] < b[1] + b[3] and b[1] < a[1] + a[3]
def first_hit(ball, bricks):return next((i for i, b inenumerate(bricks) if overlap(ball, b)), -1)
def move(ball, vx, vy, bricks):
removed =0
ball[0] += vx
i = first_hit(ball, bricks)
if i >=0:
bricks.pop(i)
vx, removed =-vx, removed +1
ball[0] += vx
ball[1] += vy
i = first_hit(ball, bricks)
if i >=0:
bricks.pop(i)
vy, removed =-vy, removed +1
ball[1] += vy
return vx, vy, removed
bricks = [[100, 50, 40, 14]]
print(move([110, 66, 10, 10], 0, -4, bricks), bricks)
פלטOutput
(0, 4, 1) []
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 42Session 42
מלבני צינורPipe rectangles
בלי pygame: כתבו pipe_rects(x, gap_y, gap, height, width=40) שמחזירה שני טאפלים (x, y, w, h): העליון מ-0 עד תחילת הרווח, והתחתון מסוף הרווח עד height. ו-random_gap(rng, gap, height, margin=20) שמחזירה מרכז רווח כך שכל הרווח בתוך המסך עם שוליים.
Without pygame: write pipe_rects(x, gap_y, gap, height, width=40) returning two tuples (x, y, w, h): the top one from 0 to the gap's start, and the bottom one from the gap's end to height. And random_gap(rng, gap, height, margin=20) returning a gap centre so the whole gap is on screen with margins.
איך הפלט אמור להיראות?What should the output look like?
((300, 0, 40, 105), (300, 215, 40, 105))
75 245
main.py
רמזHint 1:top_h = gap_y - gap // 2top_h = gap_y - gap // 2
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 43Session 43
מי פגע במיWho hit whom
בלי pygame: כתבו group_hits(enemies, bullets) כששני המילונים ממפים שם → מלבן (x, y, w, h). מחזירה מילון אויב → רשימה ממוינת של היריות שפגעו בו, ומוחקת מהמילונים את האויבים שנפגעו ואת היריות שפגעו (כמו groupcollide(..., True, True)).
Without pygame: write group_hits(enemies, bullets) where both dicts map name → rect (x, y, w, h). Return a dict enemy → sorted list of the bullets that hit it, and remove the hit enemies and the hitting bullets from the dicts (like groupcollide(..., True, True)).
איך הפלט אמור להיראות?What should the output look like?
{'e1': ['b1', 'b2']} ['e2'] ['b3']
main.py
רמזHint 1:לולאה כפולה, ואז מחיקה אחרי הלולאה.A double loop, then delete after the loop.
רמזHint 2:ירייה שפגעה בשניים נמחקת פעם אחת: bullets.pop(b, None).A bullet hitting two is removed once: bullets.pop(b, None).
הפתרון שלנוOur solution
main.py
def overlap(a, b):return a[0] < b[0] + b[2] and b[0] < a[0] + a[2] and a[1] < b[1] + b[3] and b[1] < a[1] + a[3]
def group_hits(enemies, bullets):
hits = {}
for e, er in enemies.items():
who =sorted(b for b, br in bullets.items() if overlap(er, br))
if who:
hits[e] = who
for e, who in hits.items():
enemies.pop(e)
for b in who:
bullets.pop(b, None)
return hits
enemies = {"e1": (0, 0, 20, 20), "e2": (50, 0, 20, 20)}
bullets = {"b1": (5, 10, 4, 10), "b2": (8, 12, 4, 10), "b3": (200, 0, 4, 10)}
print(group_hits(enemies, bullets), list(enemies), list(bullets))
פלטOutput
{'e1': ['b1', 'b2']} ['e2'] ['b3']
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 44Session 44
נפילה חופשיתFree fall
כתבו fall_time(height, dt, g=9.8) שמסמלצת נפילה מגובה height (מהירות התחלתית 0, אוילר חצי-מרומז) ומחזירה את הזמן (בשניות, מעוגל ל-3) עד שהגובה ≤ 0. השוו לנוסחה המדויקת sqrt(2h / g): ככל ש-dt קטן, הם קרובים יותר.
Write fall_time(height, dt, g=9.8) simulating a fall from height (initial velocity 0, semi-implicit Euler) and returning the time (seconds, rounded to 3) until the height ≤ 0. Compare to the exact formula sqrt(2h / g): the smaller dt, the closer.
איך הפלט אמור להיראות?What should the output look like?
0.1 2.0 0.02
0.01 2.02 0.0
0.001 2.02 0.0
main.py
רמזHint 1:v += g * dt; y -= v * dt; t += dtv += g * dt; y -= v * dt; t += dt
רמזHint 2:לולאת while עד y <= 0.A while loop until y <= 0.
הפתרון שלנוOur solution
main.py
import math
def fall_time(height, dt, g=9.8):
y, v, t =float(height), 0.0, 0.0while y >0:
v += g * dt
y -= v * dt
t += dt
returnround(t, 3)
exact = math.sqrt(2*20/9.8)
for dt in (0.1, 0.01, 0.001):print(dt, fall_time(20, dt), round(abs(fall_time(20, dt) - exact), 3))
פלטOutput
0.1 2.0 0.02
0.01 2.02 0.0
0.001 2.02 0.0
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 45Session 45
תנועה עם התנגשותMoving with collision
בלי pygame: כתבו move(p, dx, vy, solids) כש-p הוא רשימה [x, y, w, h] ו-solids רשימת טאפלים. מזיזים ב-x (נעצרים בקיר), ואז ב-y (נוחתים או נתקלים בתקרה). מחזירה (vy, on_ground).
Without pygame: write move(p, dx, vy, solids) where p is a list [x, y, w, h] and solids a list of tuples. Move on x (stopping at walls), then on y (landing or bumping the ceiling). Return (vy, on_ground).
איך הפלט אמור להיראות?What should the output look like?