price_range = [0, 1000000, 5000000, 10000000, 50000000, 100000000, 1000000000] # 中标金额区间划分 material = [0.015, 0.011, 0.008, 0.005, 0.0025, 0.0005] # 物资费率 service = [0.015, 0.008, 0.0045, 0.0025, 0.0001, 0.0005] # 服务费率 process = [0.01, 0.007, 0.0055, 0.0035, 0.002, 0.0005] # 工程费率 def service_charge_calculation(price, item): # 设置累加部分初始值为0 result1 = 0 # 定义列表,拿到下标范围 a_list = [] for i in range(6, 0, -1): if price >= price_range[i]: a_list.append(i) # print(a_list) # 计算累加部分result1 for i in a_list: # print(i) result_accumulate = (price_range[i] - price_range[i - 1]) * item[i - 1] # print(result_accumulate) result1 += result_accumulate # 计算超出标准部分result0 if price < price_range[1]: result0 = price * item[0] else: result0 = (price - price_range[a_list[0]]) * item[a_list[0]] # print(result0) # 两部分相加 result = result0 + result1 print('=========', result) if __name__ == "__main__": service_charge_calculation(8000000, service)
再把小程序优化一下,但是没什么思路,想写成类对象,还想用递归,都没整明白,还是一个函数到底吧,起码比上一版简单点儿了…>_<!