Dunder methodsDunder methods
__str__, __repr__, __eq__, __lt__, __len__ ומה הם נותנים.
__str__, __repr__, __eq__, __lt__, __len__ and what they give you.
נקודה מודפסתA printable point
תזכורת: מה ביקשוReminder: the task
כתבו 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)].
הפתרון המלא והפלט שלוFull solution and its output
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
p = Point(1, 2)
print(p)
print([p])(1, 2) [Point(x=1, y=2)]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
כסף שווהEqual money
תזכורת: מה ביקשוReminder: the task
כתבו Money(amount, currency) עם __eq__ (שווה אם הסכום והמטבע זהים; לסוג אחר NotImplemented) ו-__add__ שמחברת רק אותו מטבע (אחרת ValueError).
Write Money(amount, currency) with __eq__ (equal when amount and currency match; NotImplemented for other types) and __add__ that adds only the same currency (otherwise ValueError).
הפתרון המלא והפלט שלוFull solution and its output
class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return (self.amount, self.currency) == (other.amount, other.currency)
def __add__(self, other):
if self.currency != other.currency:
raise ValueError("different currencies")
return Money(self.amount + other.amount, self.currency)
print(Money(5, "ILS") + Money(7, "ILS") == Money(12, "ILS"))True
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שחקנים ממויניםSorted players
תזכורת: מה ביקשוReminder: the task
כתבו Player(name, score) עם __lt__ לפי ניקוד ו-__repr__ שמחזירה name:score. הדפיסו את הרשימה ממוינת מהגבוה לנמוך (sorted(..., reverse=True)).
Write Player(name, score) with __lt__ by score and __repr__ returning name:score. Print the list sorted high to low (sorted(..., reverse=True)).
הפתרון המלא והפלט שלוFull solution and its output
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def __lt__(self, other):
return self.score < other.score
def __repr__(self):
return f"{self.name}:{self.score}"
players = [Player("Noa", 70), Player("Avi", 95), Player("Dana", 82)]
print(sorted(players, reverse=True))[Avi:95, Dana:82, Noa:70]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
פלייליסטA playlist
תזכורת: מה ביקשוReminder: the task
כתבו Playlist עם add(song), __len__, __contains__ (בלי רגישות לאותיות גדולות), __iter__ ו-__getitem__(i) שמחזירה את השיר במקום i (כך p[0] עובד).
Write Playlist with add(song), __len__, __contains__ (case-insensitive), __iter__ and __getitem__(i) returning the song at index i (so p[0] works).
הפתרון המלא והפלט שלוFull solution and its output
class Playlist:
def __init__(self):
self.songs = []
def add(self, song):
self.songs.append(song)
def __len__(self):
return len(self.songs)
def __contains__(self, song):
return song.lower() in [s.lower() for s in self.songs]
def __iter__(self):
return iter(self.songs)
def __getitem__(self, i):
return self.songs[i]
p = Playlist()
for s in ["Yellow", "Hello", "Dynamite"]:
p.add(s)
print(len(p), "hello" in p, p[0], p[-1], list(p))3 True Yellow Dynamite ['Yellow', 'Hello', 'Dynamite']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 17: ספרים מתנהגים יפהShelf, step 17: well-behaved books
תזכורת: מה ביקשוReminder: the task
הוסיפו ל-Book(title, author, pages): __str__ ("Dune by Frank Herbert"), __repr__ ("Book('Dune', 412)"), __eq__ (כותרת וסופר, בלי רגישות לאותיות גדולות) ו-__lt__ (לפי כותרת). ל-Library הוסיפו __len__, __iter__ ו-__contains__ (מקבלת Book). הדפיסו את הספרייה ממוינת.
Add to Book(title, author, pages): __str__ ("Dune by Frank Herbert"), __repr__ ("Book('Dune', 412)"), __eq__ (title and author, case-insensitive) and __lt__ (by title). Add __len__, __iter__ and __contains__ (takes a Book) to Library. Print the library sorted.
הפתרון המלא והפלט שלוFull solution and its output
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f"{self.title} by {self.author}"
def __repr__(self):
return f"Book({self.title!r}, {self.pages})"
def __eq__(self, other):
if not isinstance(other, Book):
return NotImplemented
return (self.title.lower(), self.author.lower()) == (other.title.lower(), other.author.lower())
def __lt__(self, other):
return self.title < other.title
class Library:
def __init__(self):
self.books = []
def add(self, book):
self.books.append(book)
def __len__(self):
return len(self.books)
def __iter__(self):
return iter(self.books)
def __contains__(self, book):
return book in self.books
lib = Library()
lib.add(Book("Matilda", "Roald Dahl", 240))
lib.add(Book("Dune", "Frank Herbert", 412))
print(len(lib), Book("dune", "FRANK HERBERT", 0) in lib)
print(sorted(lib))
for b in sorted(lib):
print(b)2 True
[Book('Dune', 412), Book('Matilda', 240)]
Dune by Frank Herbert
Matilda by Roald Dahlיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
וקטורA vector
תזכורת: מה ביקשוReminder: the task
כתבו Vector(x, y) עם __add__, __sub__, __mul__ (כפל בסקלר: v * 3), __rmul__ (כדי ש-3 * v יעבוד), __eq__, __abs__ (אורך, מעוגל ל-2) ו-__repr__ (Vector(1, 2)).
Write Vector(x, y) with __add__, __sub__, __mul__ (scalar: v * 3), __rmul__ (so 3 * v works), __eq__, __abs__ (length, rounded to 2) and __repr__ (Vector(1, 2)).
הפתרון המלא והפלט שלוFull solution and its output
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, o):
return Vector(self.x + o.x, self.y + o.y)
def __sub__(self, o):
return Vector(self.x - o.x, self.y - o.y)
def __mul__(self, k):
return Vector(self.x * k, self.y * k)
def __rmul__(self, k):
return self * k
def __eq__(self, o):
if not isinstance(o, Vector):
return NotImplemented
return (self.x, self.y) == (o.x, o.y)
def __abs__(self):
return round((self.x ** 2 + self.y ** 2) ** 0.5, 2)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v = Vector(3, 4)
print(v + Vector(1, 1), v - Vector(1, 1), 2 * v, abs(v))Vector(4, 5) Vector(2, 3) Vector(6, 8) 5.0
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
טווח תאריכיםA date range
תזכורת: מה ביקשוReminder: the task
כתבו DayRange(start, end) (מספרי ימים, כולל שניהם) שמתנהגת כמו range: len, in (מספר בטווח), לולאת for, ו-__getitem__ שתומכת באינדקס שלילי ומעלה IndexError מחוץ לטווח. DayRange(3, 7) מכיל 5 ימים.
Write DayRange(start, end) (day numbers, both inclusive) that behaves like range: len, in (a number in range), a for loop, and __getitem__ supporting negative indexes and raising IndexError outside the range. DayRange(3, 7) has 5 days.
הפתרון המלא והפלט שלוFull solution and its output
class DayRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __len__(self):
return max(self.end - self.start + 1, 0)
def __contains__(self, day):
return self.start <= day <= self.end
def __iter__(self):
return iter(range(self.start, self.end + 1))
def __getitem__(self, i):
if i < 0:
i += len(self)
if not 0 <= i < len(self):
raise IndexError("day index out of range")
return self.start + i
r = DayRange(3, 7)
print(len(r), 5 in r, 9 in r, list(r), r[0], r[-1])5 True False [3, 4, 5, 6, 7] 3 7
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.