Flutter三方库openapi_dart_common的鸿蒙适配实战
2026/10/14 11:20:12
分级税率定义如下,希望定义一个税务计算器,分层计算应缴纳的税费。
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
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))