Skip to content

Instantly share code, notes, and snippets.

@wisner23
Created March 28, 2018 13:26
Show Gist options
  • Save wisner23/2fddf8e071e47a9ae0103ff4d2c556ec to your computer and use it in GitHub Desktop.
Save wisner23/2fddf8e071e47a9ae0103ff4d2c556ec to your computer and use it in GitHub Desktop.
'''
Troco
Funcionários de empresas comerciais que trabalham como caixa tem uma grande responsabilidade em suas mãos.
A maior parte do tempo de seu expediente de trabalho é gasto recebendo valores de clientes e, em alguns casos, fornecendo troco.
Seu desafio é fazer um programa que leia o valor total a ser pago e o valor efetivamente pago,
informando o menor número de cédulas e moedas que devem ser fornecidas como troco.
Deve-se considerar que há:
cédulas de R$100,00, R$50,00, R$10,00, R$5,00 e R$1,00;
moedas de R$0,50, R$0,10, R$0,05 e R$0,01.
Abaixo contem duas soluções, ambas utilizando diferentes abordagens para lidar com os decimais.
'''
class InvalidPaymentException(Exception):
pass
_BILLS_AND_COINS = [ 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50, 100 ]
def change(price, value):
if value < price:
raise InvalidPaymentException()
result = 0
value = value - price
for bill in reversed(_BILLS_AND_COINS):
if value == 0:
break
while value > bill or abs(value - bill) < 0.01:
result += 1
value -= bill
return result
def change2(price, value):
if value < price:
raise InvalidPaymentException()
result = 0
value = value - price
for bill in reversed(_BILLS_AND_COINS):
if value == 0:
break
while value >= bill:
result += 1
value = round(value - bill, 2)
return result
import pytest
from change import change, InvalidPaymentException
def test_should_return_zero_when_price_equals_value():
result = change(0.50, 0.50)
assert result == 0
def test_should_return_one_when_price_is_zero_and_value_is_one():
result = change(0, 1)
assert result == 1
def test_should_return_exception_when_value_is_less_than_price():
with pytest.raises(InvalidPaymentException):
change(100, 50)
def test_should_return_one_when_price_is_zero_and_value_is_five():
result = change(0, 5)
assert result == 1
def test_should_return_two_when_price_is_zero_and_value_is_two():
result = change(0, 2)
assert result == 2
def test_should_return_one_when_price_is_one_and_value_is_six():
result = change(1, 6)
assert result == 1
def test_should_return_one_when_price_is_one_and_value_is_five():
result = change(1, 5)
assert result == 4
def test_should_return_seven_when_price_is_11_55_and_value_is_23_90():
result = change(11.55, 23.9)
assert result == 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment