diff --git a/currency_converter.py b/currency_converter.py new file mode 100644 index 0000000..adea0d4 --- /dev/null +++ b/currency_converter.py @@ -0,0 +1,29 @@ +from decimal import Decimal + +rates = [("USD", "EUR", 0.74), ("EUR", "JPY", 145.949)] +cents = Decimal("0.01") + + +def convert(rates, value, from_code, to_code): + """Take a monetary value in one currency and return a value in another + currency""" + if from_code == to_code: + return str(value) + " " + to_code + else: + returned_list = [(origin, destination, rate) + for (origin, destination, rate) + in rates if from_code == origin] + returned_tuple = returned_list[0] + returned_rate = returned_tuple[2] + new_value = returned_rate * value + return str(new_value) + " " + to_code + + +def convert_reverse(rates, value, from_code, to_code): + returned_list = [(destination, origin, rate) + for (destination, origin, rate) + in rates if to_code == destination] + returned_tuple = returned_list[0] + returned_rate = returned_tuple[2] + new_value = Decimal(value / returned_rate).quantize(cents) + return str(new_value) + " " + to_code diff --git a/more_tests.py b/more_tests.py new file mode 100644 index 0000000..2a3dac1 --- /dev/null +++ b/more_tests.py @@ -0,0 +1,10 @@ + + + + # returned_list = [(origin, destination, rate) for (origin, destination, rate) + # in rates if from_code == origin] + # returned_tuple = returned_list[0] + # returned_rate = returned_tuple[2] + # new_value = returned_rate * value + # return new_value + # #return ("{} {}".format(return_value, to_code)) diff --git a/test_currency_converter.py b/test_currency_converter.py new file mode 100644 index 0000000..57d962a --- /dev/null +++ b/test_currency_converter.py @@ -0,0 +1,24 @@ +import currency_converter as cc +rates = [("USD", "EUR", 0.74), ("EUR", "JPY", 145.949)] + + +def test_one_to_one(): + assert cc.convert(rates, 1, "USD", "USD") == "1 USD" + + +def test_conversion_simple(): + assert cc.convert(rates, 1, "USD", "EUR") == "0.74 EUR" + + +def test_conversion(): + assert cc.convert(rates, 0.5, "USD", "EUR") == "0.37 EUR" + assert cc.convert(rates, 2, "EUR", "JPY") == "291.898 JPY" + + +def test_conversion_2_dollars(): + assert cc.convert(rates, 2, "USD", "EUR") == "1.48 EUR" + + +def test_reverse(): + assert cc.convert_reverse(rates, 2, "EUR", "USD") == "2.70 USD" + assert cc.convert_reverse(rates, 145.949, "JPY", "EUR") == "1.00 EUR"