使用递归函数允许使用Python代码来计算最大行李重量

时间:2018-12-14 13:48:01

标签: python python-2.7 function recursion count

我是python的新手,我有一个作业,我需要编写一个带有两个参数(Weights,W)的递归函数,weights是行李重量的列表,W是学生可以承受的最大重量,在python 2.7中计算学生可以携带但不超过最大限制(W)的最大行李重量,例如:

>>> calc_max_baggage([5], 0)
>>> 0
>>> calc_max_baggage ([1, 1, 1], 5)
>>> 3
>>> calc_max_baggage([4, 2, 3, 1], 5)
>>> 2

这是我的代码,但返回错误:

def calc_max_baggage (weights, W):
weights = []
res = []
W = int
def number_of_index(weights, W, i): 
    if max(weights) > W:
        return res
    else:
        count += i in weights

return calc_max_baggage()

错误消息:

  

回溯(最近通话最近):     文件“”,第1行,位于       calc_max_baggage([5],0)     文件“ C:/ Users / user / Desktop /לימודים/פייתוןPython /עבודותבית/ ex6 / test_ex6.py”,第12行,位于calc_max_baggage中       返回calc_max_baggage()   TypeError:calc_max_baggage()恰好接受2个参数(给定0个参数)

我完全不确定我的代码,我认为它是完全错误的

Weights是权重列表,W是最大权重。
鉴于此,我想知道权重[]列表中可以带多少个物品。
*我无法更改带有两个参数的功能calc_max_baggage(weights, W)

W也可以是负数,在这种情况下,该函数将返回0。

必须仅在没有环的情况下使用递归来解决

谢谢

1 个答案:

答案 0 :(得分:0)

我们可以从itertools doumentation稍微修改powerset的配方,以不使用显式循环:

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(map(lambda r: combinations(s, r), range(len(s)+1)))

对于每种行李箱,我们都可以过滤掉所有超过最大重量的行李,然后选择携带最多物品的行李:

def calc_max_baggage(weights, W):
    weights = powerset(weights)
    filtered = filter(lambda items: sum(items) <= W, weights)
    filtered = chain(filtered, ((),)) 
    return max(filtered, key=len)

filtered = chain(filtered, ((),))是这样,如果W为负数,即使从技术上说它们的重量之和大于W,我们也不会退回任何行李。

这将返回实际的一组项目,而不是其长度,但是您可以轻松地对其进行转换。

>>> calc_max_baggage([4, 2, 3, 1], 5)
(4, 1)
>>> calc_max_baggage ([1, 1, 1], 5)
(1, 1, 1)
>>> calc_max_baggage([5], 0)
()

如果需要递归组件,则可以递归定义{{​​1}},尽管效率明显较低

powerset