【问题标题】:How to increment something multiple times?如何多次增加一些东西?
【发布时间】:2019-10-17 05:27:21
【问题描述】:

所以我有这段代码:

 def effective_rate(db : {str: {(int,int) : float}}, state : str, income : int ) -> float:
        tax = 0
        for state in db.values():
            for(lower_limit, higher_limit), tax_rate in state.items():
                if (income >= lower_limit):
                    tax = tax + (tax_rate*(higher_limit - lower_limit))
                    if (income <= higher_limit):
                        tax = tax + (tax_rate*(income-lower_limit)) 
                        return tax

这是检查我的代码:

db1 = {'CT': {(      0,  12_499): .02,
                      ( 12_500,  49_999): .04, 
                      ( 50_000,    None): .06},

               'IN': {(0, None): .04},

               'LA': {(      0,   9_999): .03,
                      ( 10_000,  12_499): .05,
                      ( 12_500,  49_999): .055,
                      ( 50_000, 299_999): .06,
                      (300_000,    None): .078},

                'MA': {(0, None): .055}}
        answer = effective_rate(db1,'CT',40_000)

我遇到的问题是我的结果应该打印0.0337495 另一个问题是如果higher_limit 是None,它会引发TypeError: unsupported operand type(s) for -: 'NoneType' and 'int' 我将如何使它为 if 语句增加不止一次并且正确?以及如何阻止错误引发?

【问题讨论】:

  • 你为什么不把None改成一个非常高的值,比如99999999999?顺便说一句:“12_500”怎么会是整数?
  • @Aryerez 从 3.6 开始我们可以这样写整数:python.org/dev/peps/pep-0515

标签: python if-statement nested increment


【解决方案1】:

使用更简单的数据结构。不要试图定义税收等级的两个端点,只需记住低端点,因为每个等级一直到下一个等级的低端点。 (考虑一下如果收入是 49,999 美元和几美分会发生什么!)那么,下一个问题是逻辑错误:

            if (income >= lower_limit):
                tax = tax + (tax_rate*(higher_limit - lower_limit))
                if (income <= higher_limit):
                    tax = tax + (tax_rate*(income-lower_limit)) 
                    return tax

如果收入在某个等级之内,这将首先添加整个等级的边际税,除了达到收入水平的边际税 - 只需要第二部分。

或者,我们可以通过将差异存储在每个等级的税率中来简化。例如,在'LA' 我们可以这样做:

'LA': ((0, .03), # all income is taxed at least 3%
       (10_000, .02), # income $10k and above is taxed an additional 2%
       (12_500, .005), # and so on
       (50_000, .005),
       (300_000, .018)),

请注意,我不使用字典,而是使用 2 元组的元组。原因是我们必须确定括号的顺序,反正我们不把这些数据当作字典——我们不想解决“税率是多少”的问题对于给定的括号?”,因为我们将迭代地考虑括号。

该计划是对收入超过 30 万的人累计征收 7.8% 的税:之前所有步骤的 6%,最后一步的 1.8%。我们只需要这样做的逻辑:

    for bottom_of_bracket, tax_rate in state.items():
        if income >= bottom_of_bracket:
            tax += tax_rate * (income - bottom_of_bracket)
        # it doesn't matter if some brackets are above the income,
        # because they will fail the if condition.
    # only after considering all the brackets do we have the final tax.

最后一个考虑是我们只能从函数返回一次。您已经编写它来迭代 db 中的所有状态,但我们只关心其中一个状态 - 名为 state 的状态传递给函数。使用它在 db 中查找正确的状态数据(现在我们使用 dicts 来表示它们的用途 :))。

【讨论】:

    猜你喜欢
    • 2012-08-11
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 2016-04-01
    相关资源
    最近更新 更多