Senior
```python BILLS = (5000, 1000, 500, 100, 50) class SDK(ABC): @abstractmethod def count_banknotes(self, banknote: int) -> int: pass @abstractmethod def move_banknote_to_dispenser(self, banknote: int, count: int) -> None: pass @abstractmethod def open_dispenser(self) -> None: pass class ATM(): def __init__(self, atm_api: SDK): self.atm_api: SDK = atm_api def withdraw(self, amount: int) -> bool: bills_plan: dict[int: int] = {} for bill in BILLS: available = self.count_bills(bill) self.atm_api.open_dispenser() for bill, count in bills_plan.items(): self.atm_api.move_banknote_to_dispenser(bill, count) return True ``` Complete the implementation of the `withdraw` method in the `ATM` class to correctly dispense the requested amount using the available banknotes.
sobes.tech AI
Answer from AI
python BILLS = (5000, 1000, 500, 100, 50)
class SDK(ABC): @abstractmethod def count_banknotes(self, banknote: int) -> int: pass
@abstractmethod
def move_banknote_to_dispenser(self, banknote: int, count: int) -> None:
pass
@abstractmethod
def open_dispenser(self) -> None:
pass
class ATM(): def init(self, atm_api: SDK): self.atm_api: SDK = atm_api
def withdraw(self, amount: int) -> bool:
bills_plan: dict[int, int] = {}
remaining = amount
for bill in BILLS:
available = self.atm_api.count_banknotes(bill)
needed = remaining // bill
count = min(needed, available)
if count > 0:
bills_plan[bill] = count
remaining -= bill * count
if remaining != 0:
# Невозможно выдать точную сумму
return False
self.atm_api.open_dispenser()
for bill, count in bills_plan.items():
self.atm_api.move_banknote_to_dispenser(bill, count)
return True
Explanation:
- First, we try to cover the amount with the largest banknotes.
- For each banknote, we calculate how many are needed and how many are available.
- We form a payout plan (bills_plan).
- If after distribution the amount is not zero, it means the exact sum cannot be dispensed.
- If it is possible, we open the dispenser and move the banknotes according to the plan.