بتل کد Battle Codeدارد باز می‌شود…

جواب «Adding Money» چالش 6 از جلسه‌ی 28

سؤال

کلاس Money(amount, currency) با __add__ و __str__ بنویسید. __add__ اگر ارزها یکسان نباشند ValueError("currency mismatch") بالا می‌آورد، وگرنه یک Money جدید برمی‌گرداند. __str__ خروجی <amount با ۲ رقم> <currency> می‌دهد. ورودی خط‌به‌خط <amount> <currency> است تا end (حداقل یک خط). همه را با + جمع کنید و نتیجه را چاپ کنید؛ اگر خطا رخ داد Error: currency mismatch چاپ کنید.

راهنما

با شیء اول شروع کنید و بقیه را در حلقه با total = total + m اضافه کنید.

یک جواب درست

class Money:
    def __init__(self, amount, currency):
        self.amount = amount
        self.currency = currency

    def __add__(self, other):
        if self.currency != other.currency:
            raise ValueError("currency mismatch")
        return Money(self.amount + other.amount, self.currency)

    def __str__(self):
        return f"{self.amount:.2f} {self.currency}"


items = []
while True:
    line = input()
    if line == "end":
        break
    amount, currency = line.split()
    items.append(Money(float(amount), currency))
try:
    total = items[0]
    for m in items[1:]:
        total = total + m
    print(total)
except ValueError as e:
    print(f"Error: {e}")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن