码迷,mamicode.com
首页 > 其他好文 > 详细

Code Signal_练习题_Knapsack Light

时间:2018-08-17 19:57:42      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:car   amp   习题   class   click   each   code   练习题   技术分享   

You found two items in a treasure chest! The first item weighs weight1 and is worth value1, and the second item weighs weight2 and is worth value2. What is the total maximum value of the items you can take with you, assuming that your max weight capacity is maxW and you can‘t come back for the items later?

Note that there are only two items and you can‘t bring more than one item of each type, i.e. you can‘t take two first items or two second items.

Example

    • For value1 = 10weight1 = 5value2 = 6weight2 = 4, and maxW = 8, the output should be
      knapsackLight(value1, weight1, value2, weight2, maxW) = 10.

      You can only carry the first item.

    • For value1 = 10weight1 = 5value2 = 6weight2 = 4, and maxW = 9, the output should be
      knapsackLight(value1, weight1, value2, weight2, maxW) = 16.

      You‘re strong enough to take both of the items with you.

    • For value1 = 5weight1 = 3value2 = 7weight2 = 4, and maxW = 6, the output should be
      knapsackLight(value1, weight1, value2, weight2, maxW) = 7.

      You can‘t take both items, but you can take any of them.

 

我的解答:

def knapsackLight(value1, weight1, value2, weight2, maxW):
    dic = {weight1:value1, weight2:value2}
    if min(weight1, weight2) > maxW:
        return 0
    elif max(weight1, weight2) > maxW:
        return dic[min(weight1, weight2)]
    elif weight1 + weight2 > maxW:
        return max(value1, value2)
    else:
        return value1 + value2

 

技术分享图片
def knapsackLight(v1, w1, v2, w2, W):
    return max(int(w1 <= W) * v1, int(w2 <= W) * v2, int(w1 + w2 <= W) * (v1 + v2))


# 这都是些什么脑子...
膜拜大佬

 

Code Signal_练习题_Knapsack Light

标签:car   amp   习题   class   click   each   code   练习题   技术分享   

原文地址:https://www.cnblogs.com/YD2018/p/9494924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!