EasyPython

DRY — Don't Repeat Yourself

PythonClean CodeDRYRefactoring

The functions below share ~80% of their logic. Any change to the formatting must be made in 3 places.

# dirty
def format_usd(amount):
    if amount < 0:
        return '-$' + f'{abs(amount):.2f}'
    return '$' + f'{amount:.2f}'

def format_eur(amount):
    if amount < 0:
        return '-€' + f'{abs(amount):.2f}'
    return '€' + f'{amount:.2f}'

def format_gbp(amount):
    if amount < 0:
        return '-£' + f'{abs(amount):.2f}'
    return '£' + f'{amount:.2f}'

Refactor by extracting a generic format_currency(amount, symbol) helper. Then solve(amount, kind) dispatches to the right formatter — 'format_usd', 'format_eur', or 'format_gbp'.

Sample tests

Test #1USD positive
Input: [10.5,"format_usd"]
Output: "$10.50"
Test #2EUR negative
Input: [-10.5,"format_eur"]
Output: "-€10.50"
Test #3GBP zero
Input: [0,"format_gbp"]
Output: "£0.00"