满199-100,最佳组合,python代码实现

2016-06-02  本文已影响41人  04a07ffbfb62
"""
JD优惠满减策略,floor为下限,l1为价格列表
"""
import itertools

l1 = [50, 56, 62, 48, 48, 48, 38, 50, 34, 45, 23, 67, 76]
floor = 199

def check(l, floor):
    """
    Check the price list ,if sum of price list is lower than floor price.
    If it is, return false, otherwise, return true.
    """
    if sum(l) < floor:
        print 'The sum of combination is lower than floor: ',l1
        return False
    else:
        return True

def minCombination(l, floor):
    """
    Find the best combination of price list which is equal to floor price or 
    most close to floor price.
    l2: price list's all combinations with no duplicates
    
    returns a list
    """
    l2 = list()
    l3 = list()
    for i in range(1, len(l1)+1):
        iter = itertools.combinations(l1, i)
        l2.append(list(iter))

    for i in range(len(l2)):
        for j in range(len(l2[i])):
            if sum(l2[i][j]) == floor:
                return list(l2[i][j])
            elif sum(l2[i][j]) > floor:
                l3.append(list(l2[i][j]))

    sumlist = map(sum, l3)
    index = sumlist.index(min(sumlist))
    return l3[index]

def leftCombination(minlist, l):
    """
    Compute the price list when left price list can not create the combination

    returns a list
    """
    temp = l[:]
    for i in minlist:
        temp.remove(i)
    return temp

while check(l1, floor):
    minlist = minCombination(l1, floor)
    print 'This is minimum combination: ', minlist
    leftlist = leftCombination(minlist, l1)
    l1 = leftlist
上一篇下一篇

猜你喜欢

热点阅读