Skip to main content

Ex 17: Atm Withdrawal Simulator

Problem

Simulate a backend feature for an ATM. Customers can request multiple withdrawals during a session. Handle each request based on the current account balance.

Rules

  • Define simulate_atm_withdrawals(balance: int, withdrawals: list[int]) -> list[str].
  • Use a while loop with a manual index to process the withdrawals.
  • Update the balance after each successful withdrawal.
  • Return the full list of log messages, including the final balance.

Boilerplate

Copy below code and paste to our IDE for head start.

# Write our code inside this function
def simulate_atm_withdrawals(balance: int, withdrawals: list[int]) -> list[str]:
pass # remove this

# Call with test data
print(simulate_atm_withdrawals(200, [100, 500, 50]))

Expected Output

['Withdrawn: 100', 'Insufficient funds for requested amount: 500', 'Withdrawn: 50', 'Remaining Balance: 50']

Solution

Only view the solution after trying our best.

Show solution
def simulate_atm_withdrawals(balance: int, withdrawals: list[int]) -> list[str]:
result: list[str] = []
index: int = 0

while index < len(withdrawals):
amount = withdrawals[index]
if amount <= balance:
balance -= amount
result.append(f"Withdrawn: {amount}")
else:
result.append(f"Insufficient funds for requested amount: {amount}")
index += 1

result.append(f"Remaining Balance: {balance}")
return result

# Test call
print(simulate_atm_withdrawals(200, [100, 500, 50]))

Details

Using a manual index with a while loop is a standard way to simulate how C-style arrays were processed. It gives us explicit control over the index variable, allowing we to easily handle the index += 1 step manually.