选择卡片(卡片少,成本低)-性能问题

时间:2019-02-18 09:48:13

标签: python

n-手中的卡数,例如:n = 4

收藏-按照n收集卡片,例如:collection = [1,3,4,7]

d表示卡总数,例如:10 [1,2,3,4,5,6,7,8,9,10]

卡1费用1;卡5费用5

场景:需要挑选不在收集列表中的卡片,并且卡片价格低于(d),并且最大数量的可能不需要显示卡片

eg: sum of (2+5) <10 so we need to show (fewer cards ,cost less) accepted
eg: sum of (2+6) < 10 rejected (fewer cards ,cost more) 
eg: sum of (2+5+6) < 10 rejected (more cards ,cost more,count more than d) 
eg: sum of  (2+8) < 10 rejected (cost more)

对于小数据获取性能问题,它工作正常:

方案1:

start = time. time()
n=4
collection=[1,3,4,7]
d=10
lis=[]
list1=[]
[lis.append(x+1) for x in range(0,d)]
[lis.remove(x) for x in collection]  
#print(lis)
#for L in range(0, len(lis)+1):
for subset in itertools.combinations(lis, d%n):
    if sum(subset)<=d:
        #print(subset)
        list1.append(subset)
k = list(map(lambda x: len(x),list1))
s = list(filter (lambda x: len(x)==max(k),list1))
m = list(filter(lambda x: sum(x) == min(list(map(lambda x: sum(x),s))),s))
print(*m[0],sep='\n')
end = time. time()
print(end - start)

结果: 2 5 时间0.0

场景2: n = 8 collection = [1,3,4,7,20,25,50,60] d = 100

结果 2 5 6 8

时间:762.9762706756592

1 个答案:

答案 0 :(得分:4)

如果我正确理解了您的问题,我认为这可以实现您想要的功能:

def pick_cards(collection, d):
    collection_set = set(collection)
    # The ordered sequence of cards not in collection
    pickable = (i for i in range(1, d + 1) if i not in collection_set)
    # Sum of picked cards
    s = 0
    # Picked cards
    picked = []
    for pick in pickable:
        # If the card does not go over the limit
        if s + pick < d:
            # Add card
            picked.append(pick)
            s += pick
        else:
            # Otherwise finish
            break
    return picked

# Examples
print(pick_cards([1, 3, 4, 7], 10))
# [2, 5]
print(pick_cards([1, 3, 4, 7, 20, 25, 50, 60], 100))
# [2, 5, 6, 8, 9, 10, 11, 12, 13, 14]