兴趣:通过一个测试用例但不是一秒钟?

时间:2018-03-04 18:56:46

标签: python python-3.x

class creditCard:
    def __init__(self,limit, apr, balance):
        self.limit = limit
        self.apr = apr
        self.balance = balance
        self.charges = {}
        self.payments = {}

    def charge(self, amount, day):
        if amount > self.limit - self.balance:
            return False

        self.charges[day] = amount
        self.balance += amount

    def payment(self, amount, day):
        if amount > self.limit - self.balance:
            return False

        self.payments[day] = amount
        self.balance -= amount

    def interest(self, balance):
        return (balance * self.apr) / 365

    def days_balance(self, balance_day):
        balance_to_date = 0
        months_interest = 0
        for day in range(1, balance_day+1):
            balance_to_date += self.charges.get(day, 0)
            balance_to_date -= self.payments.get(day, 0)
            months_interest += self.interest(balance_to_date)

            if day % 30 == 0:
                balance_to_date += months_interest
                months_interest = 0

        return round(balance_to_date, 2)

我有这个程序,我写的一个任务,其中的方向非常混乱(我将在下面发布)但我得到两个测试用例,我通过我的第一个测试用例,但我的第二个测试用例我必须做数学或逻辑错误?函数days_balance()应返回411.99但返回411.89我使用相同的函数来计算我的第一个测试用例的兴趣,所以我不明白为什么它在我的第二个测试用例中不能正常工作。任何见解或建议将不胜感激。

路线:

给出信用卡:

  • 每张卡都有APR和限制
  • 每日收盘时计算利息,但不适用。 (我的第一期)
  • 在每个30天期间(开放日除外)结束时,余额适用于余额
  • 在第28/29天要求余额会得到相同的结果,但在第30天要求余额会给你余额+所有应计利息。

软件应该:

  • 创建一个帐户(开一张新卡)
  • 跟踪收费
  • 跟踪付款
  • 提供任何特定日期(开户后10天)的未结余额

测试用例:

  • 客户以1%的限额开立信用卡,年利率为35%
  • 客户在开幕当天收取500美元
  • 不再收取费用
  • 第30天他欠$ 514.38

测试案例2:

  • 客户打开信用卡,限额为1k,年利率为35%
  • 客户在开幕当天收取500美元
  • 开业后15天,他支付200美元(余额现在300)
  • 开放后25天他再收取100美元(余额现在为400)
  • 月末的总余额为411.99

以下是我如何调用每个方法(我的测试)

测试1:

customer1 = creditCard(1000, 0.35, 0)
customer1.charge(500, 1)
print(customer1.days_balance(30))

测试2:

customer2 = creditCard(1000, 0.35, 0)
customer2.charge(500, 1)
customer2.payment(200, 15)
customer2.charge(100, 25)
print(customer2.days_balance(30))

1 个答案:

答案 0 :(得分:0)

您计算30天后的预期余额如下:

((500 * 0.35) / 365) * 15 + ((300 * 0.35) / 365) * 10 + ((400 * 0.35) / 365) * 5 ~= 411.99

您的代码会像这样计算余额:

((500 * 0.35) / 365) * 14 + ((300 * 0.35) / 365) * 10 + ((400 * 0.35) / 365) * 6 ~= 411.89

这看起来像是经典的一次性错误。我建议严格遵守0索引代码以避免这些。

您可以在方法中插入打印调用,以了解months_interest如何演变:

def days_balance(self, balance_day):
    balance_to_date = 0
    months_interest = 0
    for day in range(1, balance_day+1):
        balance_to_date += self.charges.get(day, 0)
        balance_to_date -= self.payments.get(day, 0)
        months_interest += self.interest(balance_to_date)

        if day % 30 == 0:
            balance_to_date += months_interest
            months_interest = 0

        print(day, months_interest, balance_to_date)

    return round(balance_to_date, 2)

再考虑一下,我认为你的代码做了它应该做的事情,但测试用例的逻辑是关闭的。如果客户在第25天收取100个款项并且在第30天支付利息,那么该帐户将在+400持续6天。