Kattis problem Credit Card Payment failing test case

37 Views Asked by At

Once again I am looking for Kattis problems to solve in python3 and I have come across another one that I have encountered a hidden test case. The problem is Credit Card Payment (problem ID: creditcard), available here. I've understood the problem to be of a few parts, and I started with some pseudocode:

input n
for every test case
while the balance is more than 0
add the interest rate to the balance
then subtract the affordable amount from the balance
add the month counter by one
if the month counter reaches 1200
append "impossible" to the results list and break
outside of the while loop, append the current month
finally print all the results

It seems simple enough to me at first.

I then got to work implementing it. I had multiple solutions on how to round half up, and each one gave a slightly different amount of test cases passed. My current code with the most amount passed (2/5):

n = int(input())
from math import floor
def round_half_up(num, decimals=0):
    multiplier = 10**decimals
    return floor(num * multiplier + 0.5) / multiplier
results = []
for i in range(n):
    rbm = input().split()
    rate = float(rbm[0])
    balance = float(rbm[1])
    money = float(rbm[2])
    month = 0
    while balance > 0:
        interest = balance * (rate / 100)
        interest = float(round_half_up(interest, 2))
        balance += interest
        balance -= money
        month += 1
        if month >= 1200:
            month = "impossible"
            break
    results.append(month)
for result in results:
    print(result)

To round the interest, I also tried round(interest * 100) / 100 but there was still 2/5 test cases passed. I tried using a function

def round_decimal(x):
  return x.quantize(Decimal(".01"), rounding=ROUND_HALF_UP)

and calling it like interest = float(round_decimal(Decimal(str(interest)))) but that only passed 1/5, with the second test case being a runtime error. At this point I expected it to go wrong honestly. There must be something wrong with my code, I can't get it right the first time and I knew that from the start.

On the competitive programming book I found the problem from, it says in the description "real life issue; precision error issue if we do not convert double (with just 2 digits after decimal point) into long long"

Can anybody help me work out what's wrong with my code and why test cases aren't working?

0

There are 0 best solutions below