226k views
5 votes
Write a test program that prompts the user to enter the number of the items and weight for each item and the weight capacity of the bag, and displays the maximum total weight of the items that can be placed in the bag. Here is a sample run:

1 Answer

4 votes

Answer:

The program in Python is as follows:

n = int(input("Number of weights: "))

weights= []

for i in range(n):

inp = float(input("Weight: "))

weights.append(inp)

capacity = float(input("Capacity: "))

possible_weights = []

for i in range(n):

for j in range(i,n):

if capacity >= weights[i] + weights[j]:

possible_weights.append(weights[i] + weights[j])

print("Maximum capacity is: ",max(possible_weights))

Explanation:

This gets the number of weights from the user

n = int(input("Number of weights: "))

This initializes the weights (as a list)

weights= []

This iteration gets all weights from the user

for i in range(n):

inp = float(input("Weight: "))

weights.append(inp)

This gets the weight capacity

capacity = float(input("Capacity: "))

This initializes the possible weights capacity (as a list)

possible_weights = []

This iterates through the weights list

for i in range(n):

for j in range(i,n):

This gets all possible weights that can be carried by the bag

if capacity >= weights[i] + weights[j]:

possible_weights.append(weights[i] + weights[j])

This prints the maximum of all possible weights

print("Maximum capacity is: ",max(possible_weights))

User Nayroby
by
4.3k points