הרכבת האחרונה של הלילה עוברת בשש תחנות. בכל תחנה שלוש משימות ושומר. כל משימה נבדקת בדפדפן, ובכל אחת יש רמזים ופתרון מוסתר.
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.
הרכבת האחרונה של הלילה עוצרת ברציף שבו כל השלטים התבלבלו. הכרטיסן מבקש עזרה: לחשב, לעגל ולסדר טקסט לפני שהרכבת יוצאת.
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.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנה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?
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.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 inrange(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.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנה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, 0for d in delays:if d <=0:
on_time +=1if 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
תחנה 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):returnsorted({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.
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?
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנה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?
def busiest(trips):
counts = {}
for trip in trips:for station in (trip["from"], trip["to"]):
counts[station] = counts.get(station, 0) +1returnsorted(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
תחנה 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?
class Carriage:def __init__(self, seats):
self.seats, self.people = seats, 0def free(self):return self.seats - self.people
def board(self, n):if n > self.free():returnFalse
self.people += n
returnTrue
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, 0def board(self, n):if n > self.seats - self.people:returnFalse
self.people += n
returnTrueclass Train:def __init__(self, name):
self.name, self.cars = name, []
def add(self, carriage):
self.cars.append(carriage)
return self
def __len__(self):returnlen(self.cars)
def __str__(self):
taken =sum(c.people for c in self.cars)
seats =sum(c.seats for c in self.cars)
returnf"{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?
class Engine:def __init__(self, power):
self.power = power
def speed(self):return self.power //10class ElectricEngine(Engine):def __init__(self, power, battery):super().__init__(power)
self.battery = battery
def speed(self):
base =super().speed()
return base *2if self.battery >20else base //2print(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.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנה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.
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?
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.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
def average_speed(km, minutes):ifnotisinstance(km, (int, float)) ornotisinstance(minutes, (int, float)):raise TypeError("numbers only")
if minutes <=0:raise ValueError("minutes must be positive")
returnround(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.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנה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?
import csv
import io
def customs(text):
result = {"ok": [], "bad": [], "total_kg":0.0}
for line, row inenumerate(csv.DictReader(io.StringIO(text)), start=2):ifnotall((row.get(k) or"").strip() for k in ("id", "kg", "from")):
result["bad"].append((line, "missing field"))
continuetry:
kg =float(row["kg"])
except ValueError:
kg =-1if 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))
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
6
תחנה 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, 0while lo <= hi:
mid = (lo + hi) //2
steps +=1if a[mid] == target:return mid, steps
if a[mid] < target:
lo = mid +1else:
hi = mid -1return-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 >0and 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?
from functools import cache
@cache
def fib_stairs(n):if n <=1:return1return 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.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנה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 inzip(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 isnotNone:
path.append(here)
here = came[here]
return path[::-1]
for nxt in near.get(here, []):if nxt notin came:
came[nxt] = here
queue.append(nxt)
returnNone
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.