Python中的所得税计划

时间:2016-08-31 04:42:42

标签: python

我一直在尝试解决编码实验室练习,但我的程序中一直出现错误。请帮助看看这段代码并告诉我它有什么问题。

问题:

  

国家X使用分级比率计算其公民的税,如下所示:

     

每年收入:0 - 1000

     

税率:0%

     

年收入:1,001 - 10,000

     

税率:10%

     

年收入:10,001 - 20,200

     

税率:15%

     

年收入:20,201 - 30,750

     

税率:20%

     

每年收入:30,751 - 50,000

     

税率:25%

     

年收入:超过50,000

     

税率:30%

     

编写一个名为calculate_tax的Python函数,该函数将作为   参数,包含人名的键值对的字典   钥匙和他们的年收入作为价值观。

     

该函数应返回包含键值对的字典   同一个人的名字作为钥匙和他们的年度税单作为   值。例如,给出下面的示例输入:

    {
        ‘Alex’: 500,
        ‘James’: 20500,
        ‘Kinuthia’: 70000
    } The output would be as follows:

    {
        ‘Alex’: 0,
        ‘James’: 2490,
        ‘Kinuthia’: 15352.5
    }
     

詹姆斯的税收计算如下:

     

前1000(1000 - 0)

     

计算:1,000 * 0%

     

税:0

     

接下来的9000(10,000 - 1,000)

     

计算:9,000 * 10%

     

税:900

     

接下来的10,200(20,200 -10,000)

     

计算:10,200 * 15%

     

税:1530

     

剩下的300(20,500 - 20,200)

     

计算:300 * 20%

     

税:60

     

总收入:20,500

     <总税收:0 + 900 + 1530 + 60 = 2490

我的代码

income_input = {}

for key in income_input.keys():
    income_input[key] = income

def calculate_tax(income_input):

    if (income >= 0) and (income <= 1000):
        tax = (0*income)

    elif (income > 1000) and (income <= 10000):
        tax = (0.1 * (income-1000))

    elif (income > 10000) and (income <= 20200):
        tax = ((0.1*(10000-1000)) + (0.15*(income-10000)))

     elif (income > 20200) and (income <= 30750):
        tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200)))

    elif (income > 30750) and (income <= 50000):
        tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750)))

    elif (income > 50000):
        tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000)))   
    else:
        pass

    for key in income_input.keys():
        income_input[key] = tax

    return tax

测试

from unittest import TestCase

class CalculateTaxTests(TestCase):
  def test_it_calculates_tax_for_one_person(self):
    result = calculate_tax({"James": 20500})
    self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}")

  def test_it_calculates_tax_for_several_people(self):
    income_input = {"James": 20500, "Mary": 500, "Evan": 70000}
    result = calculate_tax(income_input)
    self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result,
      msg="Should return {} for the input {}".format(
            {"James": 2490.0, "Mary": 0, "Evan": 15352.5},
            {"James": 20500, "Mary": 500, "Evan": 70000}
      )
    )

  def test_it_does_not_accept_integers(self):
    with self.assertRaises(ValueError) as context:
      calculate_tax(1)
      self.assertEqual(
        "The provided input is not a dictionary.",
        context.exception.message, "Invalid input of type int not allowed"
      )

  def test_calculated_tax_is_a_float(self):
    result = calculate_tax({"Jane": 20500})
    self.assertIsInstance(
      calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict")
    self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.")

  def test_it_returns_zero_tax_for_income_less_than_1000(self):
    result = calculate_tax({"Jake": 100})
    self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000")

  def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self):
    with self.assertRaises(ValueError, msg='Allow only numeric input'):
      calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5})

  def test_it_return_an_empty_dict_for_an_empty_dict_input(self):
    result = calculate_tax({})
    self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict')

运行代码后的输出

THERE IS AN ERROR/BUG IN YOUR CODE
Results: 
Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, NameError("global name 'income' is not defined",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable

更新代码

    income_input = {}

  def calculate_tax(income_input):
    for key in income_input.items():
         tax = 0

    if (income_input[key]>= 0) and (income_input[key]<= 1000):
        tax = (0*income_input[key])

    elif (income_input[key]> 1000) and (income_input[key]<= 10000):
        tax = (0.1 * (income_input[key]-1000))

    elif (income_input[key]> 10000) and (income_input[key]<= 20200):
        tax = ((0.1*(10000-1000)) + (0.15*(income_input[key]-10000)))

    elif (income_input[key]> 20200) and (income_input[key]<= 30750):
        tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income_input[key]-20200)))

    elif (income_input[key]> 30750) and (income_input[key]<= 50000):
        tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income_input[key]-30750)))

    elif (income_input[key]> 50000):
        tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income_input[key]-50000)))

    else:
        pass
income_input[key] = tax

return income_input

新错误消息

    THERE IS AN ERROR/BUG IN YOUR CODE
    Results: 
    Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, KeyError(('Jane', 20500),), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable

不知道如何消除KeyError错误。

12 个答案:

答案 0 :(得分:3)

@KaiserPhemi 它不是实验室平台问题。您的代码没有捕获它应该捕获的错误。我通过了那个测试。这是一个有效的算法:

def calculate_tax(people):
        while True:
            try:
                iterating_people = people.keys()
                for key in iterating_people:
                    earning = people[key]
                    if earning <= 1000:
                        people[key] = 0 
                    elif earning in range(1001,10001):
                        tax1 = 0 * 1000
                        tax2 = 0.1 * (earning - 1000)
                        total_tax = tax1 + tax2
                        people[key] = total_tax
                    elif earning in range(10001,20201):
                        tax1 = 0 * 1000
                        tax2 = 0.1 *9000
                        tax3 = 0.15 * (earning - 10000)
                        total_tax = tax1+tax2+tax3
                        people[key] = total_tax
                    elif earning in range(20201,30751):
                        tax1 = 0 * 1000
                        tax2 = 0.1 * 9000
                        tax3 = 0.15 * 10200
                        tax4 = 0.20 * (earning - 20200)
                        total_tax = tax1+tax2+tax3+tax4
                        people[key] = total_tax
                    elif earning in range(30751,50001):
                        tax1 = 0 * 1000
                        tax2 = 0.1 * 9000
                        tax3 = 0.15 * 10200
                        tax4 = 0.20 * 10550
                        tax5 = 0.25 * (earning - 30750)
                        total_tax = tax1+tax2+tax3+tax4+tax5
                        people[key] = total_tax
                    elif earning > 50000:
                        tax1 = 0 * 1000
                        tax2 = 0.1 * 9000
                        tax3 = 0.15 * 10200
                        tax4 = 0.20 * 10550
                        tax5 = 0.25 * 19250
                        tax6 = 0.3 * (earning - 50000)
                        total_tax = tax1+tax2+tax3+tax4+tax5+tax6
                        people[key] = total_tax
                return people
                break
            except (AttributeError,TypeError):
                raise ValueError('The provided input is not a dictionary')

干杯!

答案 1 :(得分:2)

分离数据和代码

您可以采用更灵活的方式执行此操作,并且比详细if -elif系列稍短。

这将拆分数据代码,从而可以轻松更改税率范围和税率(在范围和最高税率/收入中定义),而无需更改代码。无论您有多少税率和税率,如果您定义了范围和最高税率,函数calctax(income)将完成其工作:

# define maximum tax rate and when it applies (income/max rate)
maxinc = 50000; maxtax = 30
# define tax ranges; bottom, top and the according tax percentage
ranges = [   
    [0, 1000, 0],
    [1000, 10000, 10],
    [10000, 20200, 15],
    [20200, 30750, 20],
    [30750, 50000, 25],
    ]

def calctax(income):
    pay = []
    for r in ranges:
        if all([income > r[0], income > r[1]]):
            pay.append((r[1]-r[0]) * r[2]/100)
        elif all([income > r[0], income <= r[1]]):
            pay.append((income-r[0]) * r[2]/100)
    if income > maxinc:
        pay.append((income-maxinc) * maxtax/100)
    return int(sum(pay))

# The test:
taxes = {"Alex": 500, "James": 20500, "Kinuthia": 70000}
for key in taxes:
    taxes[key] = calctax(taxes[key])

print(taxes)

> {'Kinuthia': 15352, 'James': 2490, 'Alex': 0}

如果分配是必须在一个函数中:

def calctax(tax_dict):
    # define maximum tax rate and when it applies (income/max rate)
    maxinc = 50000; maxtax = 30
    # define tax ranges; bottom, top and the according tax percentage
    ranges = [   
        [0, 1000, 0],
        [1000, 10000, 10],
        [10000, 20200, 15],
        [20200, 30750, 20],
        [30750, 50000, 25],
        ]
    for key in tax_dict:
        pay = []
        income = tax_dict[key]
        for r in ranges:
            if all([income > r[0], income > r[1]]):
                pay.append((r[1]-r[0]) * r[2]/100)
            elif all([income > r[0], income <= r[1]]):
                pay.append((income-r[0]) * r[2]/100)
        if income > maxinc:
            pay.append((income-maxinc) * maxtax/100)  
        taxes[key] = int(sum(pay))
        return tax_dict

测试:

taxes = {"Alex": 500, "James": 20500, "Kinuthia": 70000}
print(calctax(taxes))

> > {'Kinuthia': 15352, 'James': 2490, 'Alex': 0}

让代码正常工作

您的代码并不完全正确;你需要获取字典并为循环中的每个项目计算税收,编辑字典的相应项目并输出编辑的项目:

income_input = {"Alex": 500, "James": 20500, "Kinuthia": 70000}

def calculate_tax(income_input):
    for item in income_input:
        income = income_input[item]
        # print(income)

        if (income >= 0) and (income <= 1000):
            tax = (0*income)

        elif (income > 1000) and (income <= 10000):
            tax = (0.1 * (income-1000))

        elif (income > 10000) and (income <= 20200):
            tax = ((0.1*(10000-1000)) + (0.15*(income-10000)))

        elif (income > 20200) and (income <= 30750):
            tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200)))

        elif (income > 30750) and (income <= 50000):
            tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750)))

        elif (income > 50000):
            tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000)))   
        else:
            pass
        income_input[item] = int(tax)
    return income_input

测试:

print(calculate_tax(income_input))
> {'Kinuthia': 15352, 'James': 2490, 'Alex': 0}

答案 2 :(得分:1)

您尚未在代码中的任何位置为变量income定义或分配值。

在您的代码中,

def calculate_tax(income_input):

    for key in income_input.keys():
        income=income_input[key]
....

答案 3 :(得分:1)

我的代码遇到了同样的问题。解决方案必须通过所有测试,包括隐藏的测试。隐藏我的意思是你的代码可能会通过所有测试,但由于隐藏测试失败,它可能仍然无法提交。程序的语法可能是正确的,但根据解决方案的测试,程序的预期结果可能是错误的。

答案 4 :(得分:0)

请检查以下代码:

  • 您正试图获取功能以外的收入。所以你得到错误
  • 根据问题,您需要使用与收入字典相同的键创建计算税的新字典并将其返回。

def calculate_tax(income_dict):



    tax_dict = {}
    #This will solve the error you were getting
    #Get income dictionary as input 
    #Get income of individuals and calculate tax for it
    for key in income_dict.keys():

        income = income_dict[key]


        tax = 0
        if (income >= 0) and (income <= 1000):
            tax = (0*income)

        elif (income > 1000) and (income <= 10000):
            tax = (0.1 * (income-1000))

        elif (income > 10000) and (income <= 20200):
            tax = ((0.1*(10000-1000)) + (0.15*(income-10000)))

        elif (income > 20200) and (income <= 30750):
            tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200)))

        elif (income > 30750) and (income <= 50000):
            tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750)))

        elif (income > 50000):
            tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000)))   
        else:
            pass
        #Save calculated tax in tax dictionary
        tax_dict[key]=tax
    #Last return tax dictionary     
    return tax_dict

您需要修改您编写的单元测试中的某些内容。 检查内联评论。

from unittest import TestCase

class CalculateTaxTests(TestCase):

  def test_it_calculates_tax_for_one_person(self):
    result = calculate_tax({"James": 20500})
    self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}")

  def test_it_calculates_tax_for_several_people(self):
    income_input = {"James": 20500, "Mary": 500, "Evan": 70000}
    result = calculate_tax(income_input)
    self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result,
      msg="Should return {} for the input {}".format(
            {"James": 2490.0, "Mary": 0, "Evan": 15352.5},
            {"James": 20500, "Mary": 500, "Evan": 70000}
      )
    )

  def test_it_does_not_accept_integers(self):
    #Should be AttributeError instead of ValueError
    with self.assertRaises(AttributeError) as context:
      calculate_tax(1)
      self.assertEqual(
        "The provided input is not a dictionary.",
        context.exception.message, "Invalid input of type int not allowed"
      )

  def test_calculated_tax_is_a_float(self):
    result = calculate_tax({"Jane": 20500})
    self.assertIsInstance(
      calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict")
    self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.")

  def test_it_returns_zero_tax_for_income_less_than_1000(self):
    result = calculate_tax({"Jake": 100})
    self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000")

  def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self):
    #Should be TypeError instead of ValueError
    with self.assertRaises(TypeError, msg='Allow only numeric input'):
      calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5})

  def test_it_return_an_empty_dict_for_an_empty_dict_input(self):
    result = calculate_tax({})
    self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict')

输出:

C:\Users\dinesh_pundkar\Desktop>nosetests -v b.py
test_calculated_tax_is_a_float (b.CalculateTaxTests) ... ok
test_it_calculates_tax_for_one_person (b.CalculateTaxTests) ... ok
test_it_calculates_tax_for_several_people (b.CalculateTaxTests) ... ok
test_it_does_not_accept_integers (b.CalculateTaxTests) ... ok
test_it_return_an_empty_dict_for_an_empty_dict_input (b.CalculateTaxTests) ... ok
test_it_returns_zero_tax_for_income_less_than_1000 (b.CalculateTaxTests) ... ok
test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric (b.CalculateTaxTests
) ... ok

----------------------------------------------------------------------
Ran 7 tests in 0.000s

OK

C:\Users\dinesh_pundkar\Desktop>

答案 5 :(得分:0)

def calculate_tax(income_input="dictionary", data= {"Alex": 500, "James": 20500, "Kinuthia": 70000}):
       for item in income_input():
        if (income_input >= 0) and (income_input <= 1000):
             tax = (0*income_input)

        elif (income_input > 1000) and (income_input <= 10000):
             tax = (0.1 * (income_input-1000))

        elif (income_input > 10000) and (income_input <= 20200):
             tax = ((0.1*(10000-1000)) + (0.15*(income_input-10000)))

        elif (income_input > 20200) and (income_input <= 30750):
             tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + 
             (0.2*(income_input-20200)))

        elif (income_input > 30750) and (income_input <= 50000):
             tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) +
             (0.2*(30750-20200)) + (0.25*(income_input-30750)))

        elif (income_input > 50000):
             tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + 
             (0.2*(30750-20200)) + (0.25*(50000-30750)) + 
             (0.3*(income_input-50000)))   
        else:
          pass
          keys = set(data)
          return income_input, keys

答案 6 :(得分:0)

谢谢大家。我已经能够解决这个问题。正如@Eke Enyinnaya Nelson正确指出的那样,我需要抓住错误。

最终代码

    def calculate_tax(payroll):
        while True:
           try:
             for key in payroll.keys():
                 income = payroll[key]
               if income <= 1000 or income < 0:
                  payroll[key] = 0
               elif income in range(1001, 10001):
                   payroll[key] = 0.1 * (payroll[key]-1000)
               elif income in range(10001, 20201):
                   payroll[key] = ((0.1*(10000-1000)) + (0.15*(payroll[key]-10000)))
               elif income in range(20201, 30751):
                   payroll[key] = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(payroll[key]-20200)))
               elif income in range(30751 , 50001):
                   payroll[key] = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(payroll[key]-30750)))
               elif income > 50000:
                   payroll[key] = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(payroll[key]-50000)))
               else:
                    pass                
             return payroll
             break

           except (AttributeError,TypeError):
               raise ValueError('The provided input is not a dictionary')

干杯!

答案 7 :(得分:0)

我自己的代码是非常正确的,编写此函数的最快方法是递归计算每人的总税 这是我在下面得到的 内部错误:runTests中止:TestOutcomeEvent(processed = False,test =,result =,outcome ='error',exc_info =(,AttributeError(“'_ _ AssertRaisesContext'对象没有属性'exception'”,),),reason = None ,expected = False,shortLabel = None,longLabel = None)不是JSON可序列化的

然后它点击了我去了测试并且提出了值测试值失败的错误并且点击了

答案 8 :(得分:0)

如果您只运行脚本,这可以工作

def calculate_tax(d):
    d1={}#Dictionary for calculated tax
    income=0#Value to deduct tax from(Value in income dictionary)

    """cheking for Key pairs"""
    while True:
        try:
            d1=d.keys()
            for keys in d.keys():
                income=d[keys]
                if (income >=0) and (income<=1000):
                    tax=(0*income)
                    d[keys]=tax#Updtae  the key after taxation
                elif (income > 1000) and (income <= 10000):
                    tax = (0.1 * (income-1000))
                    d[keys]=tax#Updtae  the key after taxation
                elif (income > 10000) and (income <= 20200):
                    tax = ((0.1*(10000-1000)) + (0.15*(income-10000)))
                    d[keys]=tax#Updtae  the key after taxation
                elif (income > 20200) and (income <= 30750):
                    tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200)))
                    d[keys]=tax#Updtae  the key after taxation
                elif (income > 30750) and (income <= 50000):
                    tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750)))
                    d[keys]=tax#Updtae  the key after taxation
                elif (income > 50000):
                    tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000)))
                    d[keys]=tax#Updtae  the key after taxation

                    """updating d1 dictionary"""
                    d[keys]=tax

                return d1
                break
        except(AttributeError,TypeError):
            raise ValueError('The input provided is not A dictionary')
d2={'Alex': 700,'Njuguna': 20500,'Kinuthia': 70000,'Anex': 700,'Ngori': 20500,'jumaa': 70000}
calculate_tax(d2)

注意:这是为了帮助您了解算法中的逻辑

答案 9 :(得分:0)

我的看法:)

def calculate_tax(taxpayer):
    if taxpayer=={}: return {}
    try:
        isinstance(taxpayer, dict)
        output = {}
        for k in taxpayer.keys():
            try:
                isinstance(taxpayer[k], int)
                payer = k
                salary = taxpayer[k]
                ceilings = (1000, 10000, 20200, 30750, 50000)
                rates = {
                    1000: {'rate': 0, 'tax': 0},
                    10000: {'rate': 0.1, 'tax': 900},
                    20200: {'rate': 0.15, 'tax': 1530},
                    30750: {'rate': 0.2, 'tax': 2110.0},
                    50000: {'rate': 0.25, 'tax':4812.5}
                }
                tax = ceiling = tax_on_remnant = 0
                if salary>50000:
                    excess = salary-50000
                    tax_on_remnant = excess * 0.3
                    ceiling = 50000
                    blocks = ceilings[:ceilings.index(ceiling)+1]      
                else:
                    for k in ceilings:
                        if salary<=k:
                            ceiling = k
                            break
                    floor = ceilings[ceilings.index(ceiling)-1]
                    remnant = salary - floor
                    tax_on_remnant = remnant * rates[ceiling]['rate']
                    blocks = ceilings[:ceilings.index(ceiling)]
                for block in blocks:
                    tax +=  rates[block]['tax']
                tax = tax + tax_on_remnant
                output[payer]=tax
            except (TypeError):
                raise ValueError('Allow only numeric input')
        return output
    except (AttributeError,TypeError):
        raise ValueError('The provided input is not a dictionary')

答案 10 :(得分:0)

def calculate_tax(income_input):

for key in income_input.keys():
    income=income_input[key]


   tax_dict = {}
#This will solve the error you were getting
#Get income dictionary as input 
#Get income of individuals and calculate tax for it
for key in income_dict.keys():

    income = income_dict[key]


    tax = 0
    if (income >= 0) and (income <= 1000):
        tax = (0*income)

    elif (income > 1000) and (income <= 10000):
        tax = (0.1 * (income-1000))

    elif (income > 10000) and (income <= 20200):
        tax = ((0.1*(10000-1000)) + (0.15*(income-10000)))

    elif (income > 20200) and (income <= 30750):
        tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200)))

    elif (income > 30750) and (income <= 50000):
        tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750)))

    elif (income > 50000):
        tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000)))   
    else:
        pass
    #Save calculated tax in tax dictionary
    tax_dict[key]=tax
#Last return tax dictionary     
return tax_dict

答案 11 :(得分:0)

我们不必在代码中进行硬编码,我们可以创建这样的配置,并且它可以针对任意数量的存储桶进行扩展

tax_config = [
        {
            "min":0,
            "max":1000,
            "tax": 0
        },
        {
            "min":1000,
            "max":10000,
            "tax": 0.1
        },
        {
            "min":10000,
            "max":20200,
            "tax": 0.15
        },
        {
            "min":20200,
            "max":30750,
            "tax": 0.2
        },
        {
            "min":30750,
            "max":50000,
            "tax": 0.25
        },
        {
            "min":50001,
            "max":float('inf'),
            "tax": 0.3
        },
    ]
def calculate_tax(income_input):
    tax_percentage = 0
    for each in tax_config:
        tax_percentage += ((min(income_input, each['max'])-each['min'])*each['tax']) / (income_input/100)
        if income_input <= each['max']:
            break
    return (income_input/100)*tax_percentage