جواب «Account Closures» چالش 11 از جلسهی 15
سؤال
تابع open_account(balance) را بنویس که دو تابع deposit(amount) و withdraw(amount) را برگرداند که موجودی مشترکی دارند و هر دو موجودی جدید را برمیگردانند. اگر برداشت بیش از موجودی بود، withdraw موجودی را تغییر ندهد و None برگرداند. ورودی: موجودی اولیه، تعداد دستورها، سپس دستورهایی مثل d 50 یا w 30. برای هر دستور موجودی جدید یا insufficient funds را چاپ کن.
راهنما
دو تابع درونی در یک closure مشترکاند؛ هر دو به nonlocal balance نیاز دارند.
یک جواب درست
def open_account(balance):
def deposit(amount):
nonlocal balance
balance += amount
return balance
def withdraw(amount):
nonlocal balance
if amount > balance:
return None
balance -= amount
return balance
return deposit, withdraw
deposit, withdraw = open_account(int(input()))
for _ in range(int(input())):
action, amount = input().split()
if action == "d":
result = deposit(int(amount))
else:
result = withdraw(int(amount))
print("insufficient funds" if result is None else result)
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن