递归检查是否可以从数字列表中创建给定数字的总和

时间:2018-12-05 18:08:29

标签: python python-2.7

我得到一个号码和一个清单。我必须在列表中找到最大数量的数字,才能得出给定数字的总和。

def calc_max_baggage (weights, W):
    if W==0: # if W == 0 or weights == []: is the same.
        return 0
    elif weights==[]:
        return 0
    elif sum(weights)==W:
        return len(weights)
    elif weights[-1]==W:
        return 1
    elif W==0:
        return 1
    option1 = 0+calc_max_baggage(weights[:-1], W)
    option2 = 0+calc_max_baggage(weights[1:], W)
    return max(option2,option1)
print calc_max_baggage([3,1,2,3,2,1],6)

预期输出:4-最大输出为1 + 2 + 2 + 1

实际输出:3

2 个答案:

答案 0 :(得分:0)

您可以通过递归尝试列表中元素的不同组合来解决此问题(动态编程)。这样。

def calc_max_baggage(li, tot, current_bagage=0, max_baggage=0):
    if tot == 0 or len(li)==0: return current_bagage
    if tot < 0: return 0
    for i in range(len(li)):
        temp = calc_max_baggage(li[:i] + li[i+1:], tot-li[i], current_bagage+1)
        if temp > max_baggage:
            max_baggage = temp
    return max_baggage

答案 1 :(得分:0)

这是您问题的答案。请让其他人解释一下它为什么起作用,因为我只是理解这一点才能使它适合您的答案:

from itertools import chain, combinations


weights = (3, 1, 2, 3, 2, 1)
W = 6
# weights = (3, 1, 2, 3, 2, 1) / w = 6 / Output: 4
# weights = [1, 1, 1] / w = 2 / Output: 2
# weights = (1, 1, 1) / w = 7 / Output: 3
# weights = [4,2,1,3] / w = 5 / Output: 2
# weights = [5] / w =5 / Output: 1

def powerset(iterable):
    """
    :param iterable: the iterable you want to find all combinations for
    :return: each combination of the iterables in this example:
    :example: 
    weights = (3, 1, 2, 3, 2, 1)
    w = len(weights)
    powersets = []
    for x in powerset(weights):
        if sum(x) == w:
            print(x)
            powersets.append(len(x))
    Output >>>
    (3, 3)
    (3, 1, 2)
    (3, 1, 2)
    (3, 2, 1)
    (3, 2, 1)
    (1, 2, 3)
    (1, 3, 2)
    (2, 3, 1)
    (3, 2, 1)
    (1, 2, 2, 1)
    4
    """
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

def calc_max_baggage(weights, W):    
    powersets = []

    # for x in powerset(weights):
    #     if sum(x) <= w:
    #         print(x)
    #         powersets.append(len(x))
    # Because you said no for loops somewhere:
    powersets = [len(x) for x in powerset(weights) if sum(x) <= W]
    print(max(powersets))
calc_max_baggage(weights, W)

从哪里被解除:

https://docs.python.org/3/library/itertools.html#itertools-recipes

希望这会有所帮助:)

免责声明:有效的python3代码。不确定是否可以更改打印以删除括号,但是您可以尝试:)