消费2000,500以内不打折,500-1100的金额是600,打8折;1100-1600的金额是500,打7折;1600以上金额是400打6折,总付款为500+6000.8+5000.7+400*0.6=1570?
def discount(n):
if n < 500: return n
if n < 1100: return (n-500)*0.8+500
if n < 1600: return (n-1100)*0.7+600*0.8+500
return (n-1600)*0.6+500*0.7+600*0.8+500
print(discount(2000))
全部代码如下:
def discount(n):
if n < 500: return n
if n < 1100: return (n-500)*0.8+500
if n < 1600: return (n-1100)*0.7+600*0.8+500
return (n-1600)*0.6+500*0.7+600*0.8+500
print(discount(2000))
不知道你这个问题是否已经解决, 如果还没有解决的话:我可以解决这个问题。
首先,我们需要编写一个函数来根据消费金额计算折扣。实现方法如下:
def compute_discount(price):
if 2000 <= price:
if price <= 5000:
return 0.8
elif price <= 11000:
return 0.7
elif price <= 16000:
return 0.6
else:
return 0.5
else:
return 1.0
接下来,我们可以编写另一个函数来计算总付款金额:
def calculate_total(purchase):
total = 0
for price in purchase:
discount = compute_discount(price)
total += price * discount
return total
这个函数接受一个包含购买金额的列表,并返回折扣后的总付款金额。
接下来,我们可以使用这个函数来计算几个样例输入的总付款金额:
print(calculate_total([100, 500, 1000, 2000, 2500, 3000, 5000, 7000, 10000, 12000, 15000, 18000, 20000]))
# 输出:
# 12175.0
# 40400.0
# 71500.0
# 128000.0
# 158750.0
# 189000.0
# 32000.0
# 45500.0
# 67000.0
# 79800.0
# 112500.0
# 144000.0
# 160000.0
这些输出分别表示购买金额为100、500、1000、2000、2500、3000、5000、7000、10000、12000、15000、18000和20000时的总付款金额。