Reputation: 71
I'm trying to solve is question about the box and the container, box(list of sizes of boxes) fits in a container(list of sizes of containers) of same size or greater. Initially, nth index box checks with the nth index of the container. if it does not meet the requirement it goes and checks with the next container(immediate right index). It should return if index of the container after last match found.
box_list = [1, 3, 7, 8]
container_list = [1, 2, 5, 6]
here box at 0 index fits in container at 0 index. and 1st index box at 2 nd index container.
2nd and 3rd index box does not fit in any container in container list output should be 3 as 5 (2nd index of the container list where last match found).
I tried using nested loops but is there a better way of doing this. Thank you!
Upvotes: 1
Views: 119
Reputation: 1134
You can use a for loop that iterates through the length of the box_list
and another for loop that iterates from the index of box_list
to the length of box_list
. Then you can use a conditional that checks if the box at that index is greater than the container at that index.
for i in range(len(box_list)):
for j in range(i, len(container_list)):
if box_list[i] > container_list[j]:
print("Box at " + str(i) + " doesn't fit the container at " + str(j))
else:
print("Box at " + str(i) + " fits in container at " + str(j))
break
Upvotes: 0
Reputation: 43
I suppose the output should be the index of the last container that matches a box. The below snippet outputs the index of the last matching container. If no match is found, this outputs -1.
box_list = [1, 3, 7, 8]
container_list = [1, 2, 5, 6]
last_index = -1;
j=0;
for i in range(len(box_list)):
while(j < len(container_list) and box_list[i] > container_list[j]):
j=j+1;
if(j>=len(container_list)):
break;
if box_list[i] <= container_list[j]:
last_index = j;
j=j+1;
print(last_index);
Upvotes: 1