Python code to calculate the maximal amount of baggage is allowed using recursive function

2024/11/15 17:58:19

I am new to python and I have an assignment, I need to write a recursive function that takes two arguments (Weights, W), weights is the list of weights of baggage and W is the maximal weight a student can take, in python 2.7 that calculates the maximal amount of baggage a student can take and does not pass the maximal limit (W), for example if:

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

This is my code but it returns error:

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

Error message:

Traceback (most recent call last):File "", line 1, in calc_max_baggage ([5], 0)File "C:/Users/user/Desktop/לימודים/פייתון Python/עבודות בית/ex6/test_ex6.py", line 12, in calc_max_baggagereturn calc_max_baggage()TypeError: calc_max_baggage() takes exactly 2 arguments (0 given)

I am totally not sure about my code I think its totally wrong

Weights is the list of weights and W is the maximal weight.
Given this, I want to know how many items from the weights[] list can be brought on the plane.
*I can't change the funtion calc_max_baggage(weights, W) that takes two arguments.

W can also be negative, in that case the function returns 0.

IT MUST BE SOLVED WITH RECURSION ONLY AND WITHOUT LOOPS

Thanks

Answer

We can slightly modify the powerset recipe from the itertools doumentation to not use an explicit loop:

from itertools import chain, combinationsdef 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)))

For each combination of luggage, we can filter out all of those that exceed the maximum weight, then take the one with the most items:

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, ((),)) is so if W is negative we return no bags anyways, even though technically the sum of their weights is greater than W.

This will return the actual set of items, rather than its length, but you can easily convert it.

>>> 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)
()

If you need a recursive component, you can define powerset recursively, though it's markedly less efficient

def powerset(seq):if not seq:return ((),)else:head, *tail = seqtail_pow = powerset(tail)with_head = tuple(map(lambda t: (head,) + t, tail_pow))return with_head + tail_pow
https://en.xdnf.cn/q/120429.html

Related Q&A

How to flatten a nested dictionary? [duplicate]

This question already has answers here:Flatten nested dictionaries, compressing keys(32 answers)Closed 10 years ago.Is there a native function to flatten a nested dictionary to an output dictionary whe…

Find an element in a list of tuples in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…

print dictionary values which are inside a list in python

I am trying to print out just the dict values inside a list in python.car_object = {}cursor = self._db.execute(SELECT IDENT, MAKE, MODEL, DISPLACEMENT, POWER, LUXURY FROM CARS)for row in cursor:objectn…

Triangle of numbers on Python

Im asked to write a loop system that prints the following:0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0However, my script prints this:0 1…

Using regex to ignore invalid syntax [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

What is the requirements.txt file? What should be in it in this particular case?

I am switching from Replit to PebbleHost to host my Python bot. What do I put in my requirements.txt file? These are the imports that I have at the start of my bot. import asyncio import datetime impo…

Is this a linux or a virtualenv error?

I asked this question 4 days ago.Now, when I open a terminal, I see this:and this:Is it related to the initial problem i had, or it a python and virtualenv issue?

Python code to authenticate to website, navigate through links and download files

Im looking something which could be interesting to you as well. Im developing a feature using Python, which should be able to authenticate (using userid/password and/or with other preferred authentica…

How to get sum of products of all combinations in an array in Python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

How to get value from entry (Tkinter), use it in formula and print the result it in label

When using the function entry of Tkinter, you can write a string value and do things with it; but Im actually working with formulas. The idea is fairly simple: to put a bunch of boxes to fill with numb…