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

PythonPython

המסע: קו הלילהThe quest: the night line

הרכבת האחרונה של הלילה עוברת בשש תחנות. בכל תחנה שלוש משימות ושומר. כל משימה נבדקת בדפדפן, ובכל אחת יש רמזים ופתרון מוסתר.

The last train of the night passes six stops. Each stop has three tasks and a keeper. Every task is checked in your browser, and each has hints and a hidden solution.

  1. תחנה 1: רציף המשתניםStop 1: Variables Platform
  2. תחנה 2: צומת הלולאותStop 2: Loop Junction
  3. תחנה 3: מחסן הנתוניםStop 3: The Data Depot
  4. תחנה 4: מבצר האובייקטיםStop 4: Object Fortress
  5. תחנה 5: נמל הקבציםStop 5: File Harbour
  6. תחנה 6: מגדל האלגוריתמיםStop 6: Algorithm Tower

תחנה 1: רציף המשתניםStop 1: Variables Platform

הרכבת האחרונה של הלילה עוצרת ברציף שבו כל השלטים התבלבלו. הכרטיסן מבקש עזרה: לחשב, לעגל ולסדר טקסט לפני שהרכבת יוצאת.

The last train of the night stops at a platform where every sign got scrambled. The conductor asks for help: calculate, round and tidy some text before the train leaves.

משימהTask 1

מחיר כרטיסTicket price

כתבו fare(stops, student): כל תחנה עולה 2.5 ₪, ותלמיד מקבל 50% הנחה. החזירו מספר מעוגל לשתי ספרות (round).

Write fare(stops, student): each stop costs 2.5, and students get 50% off. Return the amount rounded to two decimals (round).

איך הפלט אמור להיראות?What should the output look like?
10.0 3.75
main.py
רמזHint 1: price = stops * 2.5price = stops * 2.5
רמזHint 2: אם student, חלקו ב-2.If student, halve it.
הפתרון שלנוOur solution
main.py
def fare(stops, student):
    price = stops * 2.5
    if student:
        price = price / 2
    return round(price, 2)

print(fare(4, False), fare(3, True))
פלטOutput
10.0 3.75

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

משימהTask 2

שלט מתוקןA fixed sign

השלטים כתובים בבלגן: " tEL aVIV ". כתבו fix(sign) שמחזירה את הטקסט בלי רווחים בקצוות, וכל מילה מתחילה באות גדולה.

The signs are a mess: " tEL aVIV ". Write fix(sign) returning the text with no spaces at the ends and every word capitalised.

איך הפלט אמור להיראות?What should the output look like?
Tel Aviv
main.py
רמזHint 1: strip() ו-title().strip() and title().
הפתרון שלנוOur solution
main.py
def fix(sign):
    return sign.strip().title()

print(fix("  tEL aVIV  "))
פלטOutput
Tel Aviv

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

משימהTask 3

זמן נסיעהTravel time

כתבו duration(minutes) שמחזירה מחרוזת בפורמט "H:MM", למשל 135 → "2:15" ו-5 → "0:05".

Write duration(minutes) returning a string in the format "H:MM", for example 135 → "2:15" and 5 → "0:05".

איך הפלט אמור להיראות?What should the output look like?
2:15 0:05
main.py
רמזHint 1: // ו-%.// and %.
רמזHint 2: f"{m:02d}" מוסיף אפס מוביל.f"{m:02d}" adds a leading zero.
הפתרון שלנוOur solution
main.py
def duration(minutes):
    return f"{minutes // 60}:{minutes % 60:02d}"

print(duration(135), duration(5))
פלטOutput
2:15 0:05

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

שומר התחנהStation keeper

שומר הרציף: הכרטיסןPlatform keeper: the Conductor

הכרטיסן בודק כרטיס בפורמט "NAME-STOPS-TYPE", למשל "noa-4-student". כתבו ticket(code) שמחזירה "Noa: 4 stops, 5.0" (שם עם אות גדולה, מספר תחנות, מחיר לפי fare מהמשימה הראשונה, TYPE הוא student או adult). אם הקוד לא תקין (לא שלושה חלקים, או STOPS לא מספר), החזירו "Invalid ticket".

The conductor checks a ticket in the format "NAME-STOPS-TYPE", for example "noa-4-student". Write ticket(code) returning "Noa: 4 stops, 5.0" (a capitalised name, the number of stops, the price by the first task's fare, TYPE being student or adult). If the code is invalid (not three parts, or STOPS isn't a number), return "Invalid ticket".

איך הפלט אמור להיראות?What should the output look like?
Noa: 4 stops, 5.0
Invalid ticket
main.py
רמזHint 1: code.split("-").code.split("-").
רמזHint 2: stops.isdigit().stops.isdigit().
הפתרון שלנוOur solution
main.py
def fare(stops, student):
    price = stops * 2.5
    if student:
        price = price / 2
    return round(price, 2)

def ticket(code):
    parts = code.split("-")
    if len(parts) != 3 or not parts[1].isdigit():
        return "Invalid ticket"
    name, stops, kind = parts
    price = fare(int(stops), kind == "student")
    return f"{name.title()}: {stops} stops, {price}"

print(ticket("noa-4-student"))
print(ticket("dan-x-adult"))
פלטOutput
Noa: 4 stops, 5.0
Invalid ticket

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

תחנה 2: צומת הלולאותStop 2: Loop Junction

בצומת עוברות עשרות רכבות, וכל אחת צריכה החלטה: לעצור, להמתין או לעבור. כאן לומדים לחזור על פעולות ולהחליט מהר.

Dozens of trains pass the junction, and each needs a decision: stop, wait or pass. Here you repeat actions and decide fast.

משימהTask 1

ספירת רכבותCounting trains

כתבו late_count(delays) שמקבלת רשימת עיכובים בדקות ומחזירה כמה רכבות איחרו ביותר מ-5 דקות.

Write late_count(delays) taking a list of delays in minutes and returning how many trains were more than 5 minutes late.

איך הפלט אמור להיראות?What should the output look like?
2
main.py
רמזHint 1: לולאה ומונה.A loop and a counter.
הפתרון שלנוOur solution
main.py
def late_count(delays):
    count = 0
    for d in delays:
        if d > 5:
            count += 1
    return count

print(late_count([0, 6, 5, 12, 3]))
פלטOutput
2

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

משימהTask 2

רמזורThe signal

כתבו signal(speed, distance): אם המרחק קטן מ-100 החזירו "STOP"; אחרת אם המהירות מעל 80 החזירו "SLOW"; אחרת "GO".

Write signal(speed, distance): if the distance is under 100 return "STOP"; else if the speed is over 80 return "SLOW"; else "GO".

איך הפלט אמור להיראות?What should the output look like?
STOP SLOW GO
main.py
רמזHint 1: סדר התנאים חשוב.The order of the conditions matters.
הפתרון שלנוOur solution
main.py
def signal(speed, distance):
    if distance < 100:
        return "STOP"
    if speed > 80:
        return "SLOW"
    return "GO"

print(signal(90, 50), signal(90, 500), signal(60, 500))
פלטOutput
STOP SLOW GO

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

משימהTask 3

לוח זמניםA timetable

כתבו timetable(start, every, count) שמחזירה רשימת שעות יציאה כמחרוזות "HH:MM", מתחילה ב-start (בדקות מחצות), כל every דקות, count פעמים. אחרי 23:59 חוזרים ל-00:00.

Write timetable(start, every, count) returning a list of departure times as "HH:MM" strings, starting at start (minutes after midnight), every every minutes, count times. After 23:59 wrap to 00:00.

איך הפלט אמור להיראות?What should the output look like?
['23:30', '23:50', '00:10']
main.py
רמזHint 1: t % (24 * 60).t % (24 * 60).
רמזHint 2: f"{h:02d}:{m:02d}".f"{h:02d}:{m:02d}".
הפתרון שלנוOur solution
main.py
def timetable(start, every, count):
    times = []
    for i in range(count):
        t = (start + i * every) % (24 * 60)
        times.append(f"{t // 60:02d}:{t % 60:02d}")
    return times

print(timetable(23 * 60 + 30, 20, 3))
פלטOutput
['23:30', '23:50', '00:10']

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

שומר התחנהStation keeper

שומר הצומת: המסדרןJunction keeper: the Dispatcher

המסדרן רוצה דוח: כתבו report(delays) שמחזירה מחרוזת עם שלוש שורות: "trains: N", "on time: K" (עיכוב 0 או פחות), ו-"worst: W" (העיכוב הגדול ביותר, או 0 אם הרשימה ריקה). השתמשו בפונקציות ולולאות, בלי max מובנה.

The dispatcher wants a report: write report(delays) returning a string of three lines: "trains: N", "on time: K" (a delay of 0 or less), and "worst: W" (the largest delay, or 0 if the list is empty). Use functions and loops, without the built-in max.

איך הפלט אמור להיראות?What should the output look like?
trains: 5
on time: 3
worst: 12
main.py
רמזHint 1: אתחלו worst = 0 ועדכנו בלולאה.Start with worst = 0 and update it in the loop.
רמזHint 2: "\n".join(...)."\n".join(...).
הפתרון שלנוOur solution
main.py
def report(delays):
    on_time, worst = 0, 0
    for d in delays:
        if d <= 0:
            on_time += 1
        if d > worst:
            worst = d
    return "\n".join([f"trains: {len(delays)}", f"on time: {on_time}", f"worst: {worst}"])

print(report([0, 4, -1, 12, 0]))
פלטOutput
trains: 5
on time: 3
worst: 12

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

תחנה 3: מחסן הנתוניםStop 3: The Data Depot

במחסן שוכבים ארגזים של נוסעים, מטענים ותחנות בלי סדר. רשימות, מילונים וקבוצות יהפכו את הבלגן לתמונה ברורה.

In the depot lie crates of passengers, luggage and stations in no order. Lists, dicts and sets will turn the mess into a clear picture.

משימהTask 1

נוסעים ייחודייםUnique passengers

כתבו unique_sorted(names) שמחזירה רשימה ממוינת של שמות בלי כפילויות, כשהשוואה לא תלויה באותיות גדולות (כל שם יוחזר באותיות קטנות).

Write unique_sorted(names) returning a sorted list of names without duplicates, comparing case-insensitively (return every name in lowercase).

איך הפלט אמור להיראות?What should the output look like?
['ari', 'dan', 'noa']
main.py
רמזHint 1: {n.lower() for n in names}.{n.lower() for n in names}.
הפתרון שלנוOur solution
main.py
def unique_sorted(names):
    return sorted({n.lower() for n in names})

print(unique_sorted(["Noa", "dan", "noa", "Ari", "DAN"]))
פלטOutput
['ari', 'dan', 'noa']

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

משימהTask 2

ספירת מטעניםCounting luggage

כתבו count_by_station(items) כש-items רשימת טאפלים (station, kg). החזירו מילון {station: total_kg}.

Write count_by_station(items) where items is a list of (station, kg) tuples. Return a dict {station: total_kg}.

איך הפלט אמור להיראות?What should the output look like?
{'Haifa': 15, 'Eilat': 5}
main.py
רמזHint 1: totals.get(station, 0) + kg.totals.get(station, 0) + kg.
הפתרון שלנוOur solution
main.py
def count_by_station(items):
    totals = {}
    for station, kg in items:
        totals[station] = totals.get(station, 0) + kg
    return totals

print(count_by_station([("Haifa", 12), ("Eilat", 5), ("Haifa", 3)]))
פלטOutput
{'Haifa': 15, 'Eilat': 5}

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

משימהTask 3

החלפת קוויםChanging lines

שני קווים: red ו-green הן רשימות תחנות. כתבו transfers(red, green) שמחזירה רשימה ממוינת של תחנות משותפות (תחנות החלפה), ו-only_red(red, green) שמחזירה ממוינת את מה שרק בקו האדום.

Two lines: red and green are lists of stations. Write transfers(red, green) returning a sorted list of shared stations (interchanges), and only_red(red, green) returning, sorted, what's only on the red line.

איך הפלט אמור להיראות?What should the output look like?
['Center', 'Museum'] ['Park', 'Port']
main.py
רמזHint 1: set(red) & set(green).set(red) & set(green).
רמזHint 2: set(red) - set(green).set(red) - set(green).
הפתרון שלנוOur solution
main.py
def transfers(red, green):
    return sorted(set(red) & set(green))

def only_red(red, green):
    return sorted(set(red) - set(green))

red = ["Center", "Park", "Museum", "Port"]
green = ["Museum", "Campus", "Center"]
print(transfers(red, green), only_red(red, green))
פלטOutput
['Center', 'Museum'] ['Park', 'Port']

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

שומר התחנהStation keeper

שומר המחסן: המלאיDepot keeper: the Ledger

כתבו busiest(trips) כש-trips רשימת מילונים {"from": ..., "to": ...}. ספרו לכל תחנה כמה פעמים הופיעה (כמוצא או כיעד), והחזירו רשימה של 3 התחנות העמוסות ביותר כטאפלים (station, count), מהעמוסה לפחות עמוסה; בתיקו, לפי שם בסדר אלפביתי.

Write busiest(trips) where trips is a list of dicts {"from": ..., "to": ...}. Count for each station how many times it appears (as origin or destination), and return a list of the 3 busiest stations as (station, count) tuples, busiest first; on a tie, alphabetically.

איך הפלט אמור להיראות?What should the output look like?
[('Port', 3), ('Center', 2), ('Park', 2)]
main.py
רמזHint 1: מילון ספירה.A counting dict.
רמזHint 2: sorted(counts.items(), key=lambda p: (-p[1], p[0]))[:3].sorted(counts.items(), key=lambda p: (-p[1], p[0]))[:3].
הפתרון שלנוOur solution
main.py
def busiest(trips):
    counts = {}
    for trip in trips:
        for station in (trip["from"], trip["to"]):
            counts[station] = counts.get(station, 0) + 1
    return sorted(counts.items(), key=lambda p: (-p[1], p[0]))[:3]

trips = [{"from": "Park", "to": "Port"}, {"from": "Port", "to": "Center"}, {"from": "Center", "to": "Port"}, {"from": "Museum", "to": "Park"}]
print(busiest(trips))
פלטOutput
[('Port', 3), ('Center', 2), ('Park', 2)]

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

תחנה 4: מבצר האובייקטיםStop 4: Object Fortress

במבצר כל דבר הוא אובייקט: קרונות, קטרים, נוסעים. כדי לעבור צריך לבנות מחלקות שיודעות לשמור על עצמן.

In the fortress everything is an object: carriages, engines, passengers. To get through you build classes that look after themselves.

משימהTask 1

קרוןA carriage

כתבו מחלקה Carriage(seats) עם board(n) שמוסיפה נוסעים ומחזירה True, או מחזירה False (ולא מוסיפה) אם אין מספיק מקום. free() מחזירה כמה מקומות פנויים.

Write a Carriage(seats) class with board(n) adding passengers and returning True, or returning False (adding none) if there isn't room. free() returns how many seats are free.

איך הפלט אמור להיראות?What should the output look like?
True False 4
main.py
רמזHint 1: שמרו self.seats ו-self.people = 0.Keep self.seats and self.people = 0.
הפתרון שלנוOur solution
main.py
class Carriage:
    def __init__(self, seats):
        self.seats, self.people = seats, 0

    def free(self):
        return self.seats - self.people

    def board(self, n):
        if n > self.free():
            return False
        self.people += n
        return True

c = Carriage(10)
print(c.board(6), c.board(5), c.free())
פלטOutput
True False 4

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

משימהTask 2

רכבת שלמהA whole train

כתבו מחלקה Train(name) עם רשימת קרונות cars, add(carriage) שמחזירה את הרכבת עצמה (כדי לשרשר), __len__ (מספר קרונות) ו-__str__ שמחזירה "NAME [3 cars, 7/30 seats taken]". השתמשו במחלקה Carriage מהמשימה הקודמת.

Write a Train(name) class with a cars list, add(carriage) returning the train itself (for chaining), __len__ (number of cars) and __str__ returning "NAME [3 cars, 7/30 seats taken]". Use the Carriage class from the previous task.

איך הפלט אמור להיראות?What should the output look like?
Night Owl [2 cars, 7/30 seats taken]
main.py
רמזHint 1: return self מאפשר t.add(a).add(b).return self allows t.add(a).add(b).
רמזHint 2: sum(c.people for c in self.cars).sum(c.people for c in self.cars).
הפתרון שלנוOur solution
main.py
class Carriage:
    def __init__(self, seats):
        self.seats, self.people = seats, 0

    def board(self, n):
        if n > self.seats - self.people:
            return False
        self.people += n
        return True

class Train:
    def __init__(self, name):
        self.name, self.cars = name, []

    def add(self, carriage):
        self.cars.append(carriage)
        return self

    def __len__(self):
        return len(self.cars)

    def __str__(self):
        taken = sum(c.people for c in self.cars)
        seats = sum(c.seats for c in self.cars)
        return f"{self.name} [{len(self)} cars, {taken}/{seats} seats taken]"

a, b = Carriage(10), Carriage(20)
a.board(7)
print(Train("Night Owl").add(a).add(b))
פלטOutput
Night Owl [2 cars, 7/30 seats taken]

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

משימהTask 3

קטר חשמליAn electric engine

כתבו מחלקה Engine(power) עם speed() שמחזירה power // 10, ומחלקה יורשת ElectricEngine(power, battery) שבה speed() מחזירה את המהירות של ההורה כפול 2 אם battery מעל 20, אחרת רק חצי (// 2). השתמשו ב-super().

Write an Engine(power) class with speed() returning power // 10, and a subclass ElectricEngine(power, battery) whose speed() returns the parent's speed times 2 if battery is above 20, otherwise only half (// 2). Use super().

איך הפלט אמור להיראות?What should the output look like?
50 100 25
main.py
רמזHint 1: super().__init__(power).super().__init__(power).
רמזHint 2: base = super().speed().base = super().speed().
הפתרון שלנוOur solution
main.py
class Engine:
    def __init__(self, power):
        self.power = power

    def speed(self):
        return self.power // 10

class ElectricEngine(Engine):
    def __init__(self, power, battery):
        super().__init__(power)
        self.battery = battery

    def speed(self):
        base = super().speed()
        return base * 2 if self.battery > 20 else base // 2

print(Engine(500).speed(), ElectricEngine(500, 80).speed(), ElectricEngine(500, 10).speed())
פלטOutput
50 100 25

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

שומר התחנהStation keeper

שומר המבצר: הכספתFortress keeper: the Vault

כתבו מחלקה Pass(owner, rides) לכרטיסייה: rides הוא property לקריאה בלבד; use() מורידה נסיעה ומחזירה את מה שנשאר, וזורקת ValueError("no rides left") אם אין. __add__ בין שתי כרטיסיות של אותו בעלים מחזיר כרטיסייה חדשה עם סכום הנסיעות, ובעלים שונים זורקים ValueError("different owners"). __eq__ משווה בעלים ונסיעות.

Write a Pass(owner, rides) class for a punch card: rides is a read-only property; use() takes one ride and returns what's left, raising ValueError("no rides left") if there are none. __add__ between two passes of the same owner returns a new pass with the rides summed, and different owners raise ValueError("different owners"). __eq__ compares owner and rides.

איך הפלט אמור להיראות?What should the output look like?
3 2 True
different owners
main.py
רמזHint 1: שמרו self._rides והחזירו אותו מ-@property.Keep self._rides and return it from an @property.
רמזHint 2: ב-__eq__ בדקו isinstance(other, Pass).In __eq__ check isinstance(other, Pass).
הפתרון שלנוOur solution
main.py
class Pass:
    def __init__(self, owner, rides):
        self.owner, self._rides = owner, rides

    @property
    def rides(self):
        return self._rides

    def use(self):
        if self._rides == 0:
            raise ValueError("no rides left")
        self._rides -= 1
        return self._rides

    def __add__(self, other):
        if self.owner != other.owner:
            raise ValueError("different owners")
        return Pass(self.owner, self._rides + other._rides)

    def __eq__(self, other):
        return isinstance(other, Pass) and (self.owner, self._rides) == (other.owner, other._rides)

p = Pass("Noa", 2) + Pass("Noa", 1)
print(p.rides, p.use(), p == Pass("Noa", 2))
try:
    Pass("Noa", 1) + Pass("Dan", 1)
except ValueError as e:
    print(e)
פלטOutput
3 2 True
different owners

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

תחנה 5: נמל הקבציםStop 5: File Harbour

בנמל מגיעות הודעות מכל העולם: קבצי CSV, JSON ודוחות. צריך לקרוא, לנקות ולבדוק אותם לפני שהן נכנסות למערכת.

Messages arrive at the harbour from all over: CSV files, JSON and reports. They need reading, cleaning and checking before entering the system.

משימהTask 1

קריאת CSVReading a CSV

כתבו load_rides(text) שמקבלת תוכן CSV עם כותרת name,km ומחזירה מילון {name: km} כש-km הוא float. שורות ריקות מדלגים.

Write load_rides(text) taking CSV content with a name,km header and returning a dict {name: km} with km as a float. Skip empty lines.

איך הפלט אמור להיראות?What should the output look like?
{'Noa': 12.5, 'Dan': 3.0}
main.py
רמזHint 1: csv.DictReader(io.StringIO(text)).csv.DictReader(io.StringIO(text)).
הפתרון שלנוOur solution
main.py
import csv
import io

def load_rides(text):
    rides = {}
    for row in csv.DictReader(io.StringIO(text)):
        if row["name"]:
            rides[row["name"]] = float(row["km"])
    return rides

print(load_rides("name,km\nNoa,12.5\n\nDan,3\n"))
פלטOutput
{'Noa': 12.5, 'Dan': 3.0}

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

משימהTask 2

JSON בטוחSafe JSON

כתבו parse_config(text) שמחזירה מילון מתוך JSON, עם ברירות מחדל {"speed": 60, "night": False} לכל מפתח שחסר. אם ה-JSON שבור, החזירו את ברירות המחדל בלבד.

Write parse_config(text) returning a dict from JSON, with defaults {"speed": 60, "night": False} for any missing key. If the JSON is broken, return the defaults only.

איך הפלט אמור להיראות?What should the output look like?
{'speed': 90, 'night': False} {'speed': 60, 'night': False}
main.py
רמזHint 1: try / except json.JSONDecodeError.try / except json.JSONDecodeError.
רמזHint 2: {**DEFAULTS, **data}.{**DEFAULTS, **data}.
הפתרון שלנוOur solution
main.py
import json

DEFAULTS = {"speed": 60, "night": False}

def parse_config(text):
    try:
        data = json.loads(text)
    except json.JSONDecodeError:
        return dict(DEFAULTS)
    return {**DEFAULTS, **data}

print(parse_config('{"speed": 90}'), parse_config("{oops"))
פלטOutput
{'speed': 90, 'night': False} {'speed': 60, 'night': False}

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

משימהTask 3

שגיאות ברורותClear errors

כתבו average_speed(km, minutes) שמחזירה קמ"ש מעוגל לספרה אחת. אם minutes הוא 0 או שלילי, זרקו ValueError("minutes must be positive"). אם אחד מהם אינו מספר, זרקו TypeError("numbers only").

Write average_speed(km, minutes) returning km/h rounded to one decimal. If minutes is 0 or negative, raise ValueError("minutes must be positive"). If either isn't a number, raise TypeError("numbers only").

איך הפלט אמור להיראות?What should the output look like?
90.0
ValueError minutes must be positive
TypeError numbers only
main.py
רמזHint 1: isinstance(x, (int, float)).isinstance(x, (int, float)).
הפתרון שלנוOur solution
main.py
def average_speed(km, minutes):
    if not isinstance(km, (int, float)) or not isinstance(minutes, (int, float)):
        raise TypeError("numbers only")
    if minutes <= 0:
        raise ValueError("minutes must be positive")
    return round(km / minutes * 60, 1)

print(average_speed(30, 20))
for bad in [(10, 0), ("10", 5)]:
    try:
        average_speed(*bad)
    except (ValueError, TypeError) as e:
        print(type(e).__name__, e)
פלטOutput
90.0
ValueError minutes must be positive
TypeError numbers only

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

שומר התחנהStation keeper

שומר הנמל: המכסHarbour keeper: Customs

כתבו customs(text) שמקבלת CSV עם כותרת id,kg,from ומחזירה מילון: "ok" (רשימת id תקינים), "bad" (רשימת טאפלים (line_number, reason) כשמספר השורה מתחיל ב-2 אחרי הכותרת), ו-"total_kg" (סכום התקינים). סיבות: "missing field" אם שדה ריק, "bad weight" אם kg אינו מספר או שלילי.

Write customs(text) taking a CSV with an id,kg,from header and returning a dict: "ok" (a list of valid ids), "bad" (a list of (line_number, reason) tuples, line numbers starting at 2 after the header), and "total_kg" (the sum of the valid ones). Reasons: "missing field" if a field is empty, "bad weight" if kg isn't a number or is negative.

איך הפלט אמור להיראות?What should the output look like?
{'ok': ['A1', 'A4'], 'bad': [(3, 'missing field'), (4, 'bad weight'), (6, 'bad weight')], 'total_kg': 15.5}
main.py
רמזHint 1: enumerate(reader, start=2).enumerate(reader, start=2).
רמזHint 2: try: float(...).try: float(...).
הפתרון שלנוOur solution
main.py
import csv
import io

def customs(text):
    result = {"ok": [], "bad": [], "total_kg": 0.0}
    for line, row in enumerate(csv.DictReader(io.StringIO(text)), start=2):
        if not all((row.get(k) or "").strip() for k in ("id", "kg", "from")):
            result["bad"].append((line, "missing field"))
            continue
        try:
            kg = float(row["kg"])
        except ValueError:
            kg = -1
        if kg < 0:
            result["bad"].append((line, "bad weight"))
            continue
        result["ok"].append(row["id"])
        result["total_kg"] += kg
    return result

data = "id,kg,from\nA1,12,Cyprus\nA2,,Rhodes\nA3,heavy,Crete\nA4,3.5,Malta\nA5,-2,Sicily\n"
print(customs(data))
פלטOutput
{'ok': ['A1', 'A4'], 'bad': [(3, 'missing field'), (4, 'bad weight'), (6, 'bad weight')], 'total_kg': 15.5}

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

תחנה 6: מגדל האלגוריתמיםStop 6: Algorithm Tower

התחנה האחרונה היא מגדל עם מאות קומות של נתונים. רק מי שיודע לחפש, למיין ולמצוא מסלול קצר יגיע לראש וידליק את פנס הקו.

The last stop is a tower with hundreds of floors of data. Only someone who can search, sort and find a short route reaches the top and lights the line's lamp.

משימהTask 1

חיפוש בינאריBinary search

כתבו find(sorted_list, target) שמחזירה את האינדקס של target ברשימה ממוינת, או -1, בעזרת חיפוש בינארי (בלי index ובלי in). החזירו גם כמה השוואות נדרשו: (index, steps).

Write find(sorted_list, target) returning target's index in a sorted list, or -1, using binary search (no index, no in). Also return how many comparisons it took: (index, steps).

איך הפלט אמור להיראות?What should the output look like?
(333, 9) (-1, 8)
main.py
רמזHint 1: lo, hi = 0, len(a) - 1.lo, hi = 0, len(a) - 1.
רמזHint 2: mid = (lo + hi) // 2.mid = (lo + hi) // 2.
הפתרון שלנוOur solution
main.py
def find(a, target):
    lo, hi, steps = 0, len(a) - 1, 0
    while lo <= hi:
        mid = (lo + hi) // 2
        steps += 1
        if a[mid] == target:
            return mid, steps
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1, steps

floors = list(range(0, 1000, 3))
print(find(floors, 999), find(floors, 4))
פלטOutput
(333, 9) (-1, 8)

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

משימהTask 2

מיון יציבA stable sort

כתבו by_floor(people) שממיינת רשימת טאפלים (name, floor) לפי קומה מהנמוכה לגבוהה, ובאותה קומה שומרת את הסדר המקורי. מימשו מיון הכנסה (insertion sort) בעצמכם, בלי sort או sorted.

Write by_floor(people) sorting a list of (name, floor) tuples by floor, lowest first, keeping the original order within a floor. Implement insertion sort yourself, without sort or sorted.

איך הפלט אמור להיראות?What should the output look like?
[('Dan', 1), ('Lia', 1), ('Noa', 3), ('Ari', 3)]
main.py
רמזHint 1: עברו על הרשימה והכניסו כל איבר למקומו בתוצאה.Go through the list and insert each item into its place in the result.
רמזHint 2: השוו רק לפי [1], ועצרו כשהקומה קטנה או שווה.Compare only by [1], and stop when the floor is smaller or equal.
הפתרון שלנוOur solution
main.py
def by_floor(people):
    result = []
    for person in people:
        i = len(result)
        while i > 0 and result[i - 1][1] > person[1]:
            i -= 1
        result.insert(i, person)
    return result

print(by_floor([("Noa", 3), ("Dan", 1), ("Ari", 3), ("Lia", 1)]))
פלטOutput
[('Dan', 1), ('Lia', 1), ('Noa', 3), ('Ari', 3)]

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

משימהTask 3

מעליותElevators

כתבו fib_stairs(n) שמחזירה בכמה דרכים אפשר לעלות n מדרגות כשכל צעד הוא 1 או 2 מדרגות. השתמשו ב-memoization (functools.cache או מילון), כך ש-fib_stairs(80) יחזיר מיד.

Write fib_stairs(n) returning how many ways there are to climb n stairs when each step is 1 or 2 stairs. Use memoization (functools.cache or a dict), so fib_stairs(80) returns instantly.

איך הפלט אמור להיראות?What should the output look like?
5 37889062373143906
main.py
רמזHint 1: ways(n) = ways(n-1) + ways(n-2).ways(n) = ways(n-1) + ways(n-2).
רמזHint 2: ways(0) = ways(1) = 1.ways(0) = ways(1) = 1.
הפתרון שלנוOur solution
main.py
from functools import cache

@cache
def fib_stairs(n):
    if n <= 1:
        return 1
    return fib_stairs(n - 1) + fib_stairs(n - 2)

print(fib_stairs(4), fib_stairs(80))
פלטOutput
5 37889062373143906

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

שומר התחנהStation keeper

שומר המגדל: מפת הקוויםTower keeper: the Line Map

כתבו route(lines, start, goal) כש-lines מילון {line_name: [stations...]} (קו נוסע בין תחנות סמוכות ברשימה בשני הכיוונים). החזירו את רשימת התחנות במסלול עם הכי מעט עצירות מ-start ל-goal (BFS), או None אם אין. בתיקו, BFS עם סדר הקווים והתחנות כפי שהם במילון.

Write route(lines, start, goal) where lines is a dict {line_name: [stations...]} (a line runs between neighbouring stations in its list, both ways). Return the list of stations on the route with the fewest stops from start to goal (BFS), or None if there's none. On ties, BFS in the order lines and stations appear in the dict.

איך הפלט אמור להיראות?What should the output look like?
['Campus', 'Park', 'Center', 'Port']
None
main.py
רמזHint 1: בנו מילון שכנים מכל הקווים.Build a neighbours dict from all the lines.
רמזHint 2: came = {start: None} ושחזור בסוף.came = {start: None} and rebuild at the end.
הפתרון שלנוOur solution
main.py
from collections import deque

def route(lines, start, goal):
    near = {}
    for stations in lines.values():
        for a, b in zip(stations, stations[1:]):
            near.setdefault(a, []).append(b)
            near.setdefault(b, []).append(a)
    came, queue = {start: None}, deque([start])
    while queue:
        here = queue.popleft()
        if here == goal:
            path = []
            while here is not None:
                path.append(here)
                here = came[here]
            return path[::-1]
        for nxt in near.get(here, []):
            if nxt not in came:
                came[nxt] = here
                queue.append(nxt)
    return None

LINES = {"red": ["Port", "Center", "Park", "Museum"], "green": ["Campus", "Park", "Zoo"], "blue": ["Port", "Beach", "Zoo"]}
print(route(LINES, "Campus", "Port"))
print(route(LINES, "Museum", "Moon"))
פלטOutput
['Campus', 'Park', 'Center', 'Port']
None

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

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