问题描述:
分级税率定义如下,希望定义一个税务计算器,分层计算应缴纳的税费。
brackets = [ (0, 0.10), (10000, 0.20), (30000, 0.30) ]def calculate_tax(income, brackets): # Your code here tax = 0 for k in brackets[::-1]: threshold = k[0] tax_r = k[1] if income > threshold: tax += (income - threshold)*tax_r income = income - (income - threshold) return tax# Method 2: def calculate_tax(income, brackets): # Your code here tax = 0 brackets.reverse() for k in brackets: threshold = k[0] tax_r = k[1] if income > threshold: tax += (income - threshold)*tax_r income = income - (income - threshold) return tax# Test case calculate_tax(50000, brackets)Output:
11000.0
Notes:
lst.reverse()会直接修改原列表。reverse()返回的是None,而不是反转后的列表!
不能写成:lst = lst.reverse()(Error!此时lst会变成None)。- 使用切片
[::-1]可以生成一个新列表:lst = [1, 2, 3, 4, 5] lst_reverse = lst[::-1] print(lst_reverse) - 本税务计算器采用累进税率制。它不是将总收入直接乘以最高税率,而是针对不同收入区间分别计算税额。
完整可运行代码:
brackets = [ (0, 0.10), (10000, 0.20), (30000, 0.30) ] def calculate_tax(income, brackets): # Your code here tax = 0 for k in brackets[::-1]: threshold = k[0] tax_r = k[1] if income > threshold: tax += (income - threshold)*tax_r income = income - (income - threshold) return tax # Test case print(calculate_tax(50000, brackets))