Python 中的所得税程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39240884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:02:17  来源:igfitidea点击:

An Income Tax program in Python

python

提问by Phemi

I have been trying to solve a coding lab exercise but I keep getting errors in my program. Kindly help look at this code and tell me what's wrong with it.

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

Question:

题:

Country X calculates tax for its citizens using a graduated scale rate as shown below:

Yearly Income: 0 - 1000

Tax Rate: 0%

Yearly Income: 1,001 - 10,000

Tax Rate: 10%

Yearly Income: 10,001 - 20,200

Tax Rate: 15%

Yearly Income: 20,201 - 30,750

Tax Rate: 20%

Yearly Income: 30,751 - 50,000

Tax Rate: 25%

Yearly Income: Over 50,000

Tax Rate: 30%

Write a Python function named calculate_tax that will take as an argument, a dictionary containing key-value pairs of people's names as the keys and their yearly incomes as the values.

The function should return a dictionary containing key-value pairs of the same people's names as keys and their yearly tax bill as the values. For example, given the sample input below:

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

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

The tax for James would be calculated as follows:

The first 1000 (1000 - 0)

Calculation: 1,000 * 0%

Tax: 0

The next 9000 (10,000 - 1,000)

Calculation: 9,000 * 10%

Tax: 900

The next 10,200 (20,200 -10,000)

Calculation: 10,200 * 15%

Tax: 1530

The remaining 300 (20,500 - 20,200)

Calculation: 300 * 20%

Tax: 60

Total Income: 20,500

Total Tax: 0 + 900 + 1530 + 60 = 2490

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

My Code

我的代码

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

Test

测试

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')

Output after running code

运行代码后的输出

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

Updated Code

更新代码

    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

New Error Message

新的错误信息

    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

Don't know how to eliminate the KeyErrorerror.

不知道如何消除KeyError错误。

回答by Eke Diala Enyinnaya

@KaiserPhemi Its not a lab platform issue. Your code is not catching the errors it is supposed to catch. I've passed that test. Here's an algorithm that works:

@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')

Cheers!

干杯!

回答by Jacob Vlijm

Separating data and code

分离数据和代码

You can do this in a more flexibel way, and a bit shorter than the verbose if -elif-series.

您可以以更灵活的方式执行此操作,并且比冗长的if -elif系列短一点。

This will split the dataand the codemaking it possible to easily change the tax ranges and rates (defined in ranges and the top- rate/income) without having to change the code. No matter how many tax ranges and rates you have, the function calctax(income)will do its job if you defined the ranges and the top- rate:

这将拆分数据代码,从而可以轻松更改税收范围和税率(在范围和最高税率/收入中定义),而无需更改代码。无论您有多少税收范围和税率,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}

if the assignment is it mustbe in one function:

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

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

The test:

考试:

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

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

Making your code work

让你的代码工作

Your code is not entirely correct; you need to grab the dictionary and calculate taxes for each item in a loop, edit the corresponding item of the dictionary and output the edited one:

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

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

The test:

考试:

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

回答by Annapoornima Koppad

You have not defined or assigned a value to the variable incomeanywhere in the code.

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

In your code,

在您的代码中,

def calculate_tax(income_input):

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

回答by hashi

am having the same problem with my code. the solution has to pass all the tests including the hidden ones. with hidden i mean your code might pass all the tests and it might still not submitt due to failure of hidden tests. the syntax of the program could be right but the intended outcome of the program could be wrong according to the tests of the solution.

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

回答by user6788660

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

回答by Dinesh Pundkar

Please check the code below :

请检查以下代码:

  • You are trying to access income outside function. So you are getting error
  • According to question, you need to create new dictionary for calculated tax with same keys as income dictionary and return it.
  • 您正试图在职能之外获得收入。所以你得到错误
  • 根据问题,您需要使用与收入字典相同的键为计算税创建新字典并返回。

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

You need to modify certain things in unit tests you have written. Check the comments inline.

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

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')

Output:

输出:

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>

回答by Phemi

Thanks everyone. I've been able to solve this. As rightly pointed out by @Eke Enyinnaya Nelson, I need to catch the errors.

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

Final Code

最终代码

    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')

Cheers!

干杯!

回答by Enogwe Victor

my own code which is very much correct and the fastest way to write this function is by recursively calculating total tax per person here is what i get below Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, AttributeError("'_AssertRaisesContext' object has no attribute 'exception'",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable

我自己的代码非常正确,编写此函数的最快方法是递归计算每人的总税收,这是我在下面得到的内部错误:runTests aborted:TestOutcomeEvent(handled=False, test=, result=, result= 'error', exc_info=(, AttributeError("'_AssertRaisesContext' object has no attribute 'exception'",), ), reason=None, expected=False, shortLabel=None, longLabel=None) 不是 JSON 可序列化的

then it clicked i went to the tests and raised value error for test values that fail and voila it clicked

然后它点击了我去测试并引发了失败的测试值的值错误,瞧它点击

回答by robert oriato

If you were to run just the Script alone, This Could Work

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

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)

Note: This is to help you understand the logics in algorithm

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

回答by Jonathan

My take :)

我的看法:)

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')