我有一个产品名叫toy。
它的销售有一系列折扣。
客户购买toy一段时间,当到达expire_time时,他会续订。
因此,toy实例具有pay_time和expire_time字段:
class Toy(models.Model):
pay_time = DateTimeField()
expire_time = DateTimeField()当客户有一个toy实例时,pay_time是2018.01.01,expire_time是2018.05.01。现在,当时间到达2018.05.01,客户将更新产品。
续订策略折扣表如下:
renew_discounts_list: [
{
discount: 0.20,
min_mon: 1,
max_mon:3
},
{
discount: 0.15,
min_mon: 4,
max_mon:6
},
....
]如果客户希望续订17月,则计算非常复杂。
我想要一个折扣的结果,这是我需要的输出:
[
{
'months': 1,
'disconts': 0.15 #(4~6: 0.15)
},
{
'months': 3,
'disconts': 0.10 #(7~9: 0.10)
},
....
]结果的总months为17。
我试着用法官来解决这个问题,但这不是一个很好的解决办法。
发布于 2018-06-14 08:09:59
可以将递归用于计算:
我假设toy实例为dict:
toy = {
'pay_time': 1, # there I use the count replace of the datetime, you can change by yourself.
'expire_time': 4
}我列出了一个discounts策略列表:
discounts = [
{
'min_month': 1,
'max_month': 3,
'discounts': 0.30
},
{
'min_month': 4,
'max_month': 6,
'discounts': 0.25
},
{
'min_month': 7,
'max_month': 9,
'discounts': 0.10
},
{
'min_month': 10,
'max_month': 13,
'discounts': 0.08
}
]使用递归方法:
def get_discount_recursion(discounts_list, months):
expire_months = toy.get('expire_time') - toy.get('pay_time')
total_months = months + expire_months
left_months = 0
if get_max_month() < total_months:
disc_months = total_months - get_max_month() + 1
disc = {
'months': disc_months,
'discounts': 0
}
left_months = months - disc_months
discounts_list.append(disc)
else:
for item in discounts:
print('item,' , item, total_months, months)
if (item.get('min_month') <= total_months and item.get('max_month') >= total_months):
if item.get('min_month') <= expire_months and item.get('max_month') > expire_months:
disc_months = total_months - expire_months + 1
else:
disc_months = total_months - item.get('min_month') + 1
left_months = months - disc_months
disc = {
'months': disc_months,
'discounts': item.get('discounts')
}
discounts_list.append(disc)
if left_months <= 0: return discounts_list
else: return get_discount_recursion(discounts_list, left_months)
def get_max_month():
max = 0
for item in discounts:
max = item.get('max_month') if item.get('max_month') > max else max
return max我已经测试过:
res = get_discount_recursion([], 13)
print(res)产出:
[{'months': 4, 'discounts': 0}, {'months': 3, 'discounts': 0.08}, {'months': 3, 'discounts': 0.1}, {'months': 3, 'discounts': 0.25}]https://stackoverflow.com/questions/50849592
复制相似问题