编写一个Python程序,对于每个事务,它都会对客户ID和事务中的总销售额进行输入。然后它读取一个名为discount的文本文件。存储有关销售额折扣的信息的文本,如上表1所示。文本文件以纯文本格式存储信息,如下所示。
Less than $100 --> 0%
From $100 up to less than $500 --> 10%
From $500 up to less than $1,000 --> $40 PLUS 20%
From $1,000 up to less than $2,000 --> $140 PLUS 30%
$2,000 and above --> $440 PLUS 40%
答案 0 :(得分:0)
#!/usr/bin/python
from __future__ import division
class Discount(object):
def __init__(self,min_value=0,max_value=0,flat_discount=0,discount=0):
self.min_value = min_value
self.max_value = max_value
self.flat_discount = flat_discount
self.discount = discount
def is_applicable(self,amount):
if amount > self.max_value:
return False
if amount >= self.min_value and amount <= self.max_value:
return True
def apply_discount(self,bill_amount):
if bill_amount >= self.min_value and bill_amount <= self.max_value:
final_bill = 0
amount_discount = bill_amount * (self.discount / 100)
final_bill += bill_amount - amount_discount
if self.flat_discount != 0:
final_bill = final_bill - self.flat_discount
return final_bill
d0 = Discount()
d1 = Discount(9,100,0,0)
d2 = Discount(101,500,0,10)
d3 = Discount(501,1000,40,20)
d4 = Discount(1001,2000,140,30)
d5 = Discount(2001,99999999,440,40)
amounts = [100,434,4242,2221,424,667,22]
for amount in amounts:
for discount_offer in [d0,d1,d2,d3,d4,d5]:
if discount_offer.is_applicable(amount):
print "Final Price for %s is %s" % (amount, discount_offer.apply_discount(amount))
您必须将折扣数据存储到Python更易于阅读的某种形式中。我建议ConfigParser
配置看起来像
[Discount1]
min_value = '0'
max_value = '100'
discount = '0'
flat_discount = '0'
然后您可以使用它来创建这些对象