gpt4 book ai didi

python - Python中的所得税程序

转载 作者:行者123 更新时间:2023-11-28 20:17:41 25 4
gpt4 key购买 nike

。。
问题:
X国使用分级税率表计算其公民的税收,如下所示:
Yearly Income: 0 - 1000
Tax Rate: 0%
年收入:1001-10000
税率:10%
Yearly Income: 10,001 - 20,200
Tax Rate: 15%
年收入:20201-30750
Tax Rate: 20%
Yearly Income: 30,751 - 50,000
税率:25%
Yearly Income: Over 50,000
税率:30%
编写一个名为calculate_tax的Python函数,它将
argument, a dictionary containing key-value pairs of people's names as

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
。例如,给定以下示例输入:

    {
‘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:
前1000(1000-0)
Calculation: 1,000 * 0%
税:0
下一个9000(10000-1000)
Calculation: 9,000 * 10%
Tax: 900
The next 10,200 (20,200 -10,000)
Calculation: 10,200 * 15%
税款:1530
The remaining 300 (20,500 - 20,200)
计算:300*20%
Tax: 60
总收入:20500
Total Tax: 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

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

更新的代码
    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

不知道如何消除 KeyError错误。

最佳答案

分离数据和代码
你可以用更灵活的方式来做,并且比冗长的if -elif系列稍微短一点。
这将拆分数据和代码,使得无需更改代码就可以轻松更改税率范围和税率(定义在范围和最高税率/收入中)。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:

# 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}

关于python - Python中的所得税程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39240884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com