简体   繁体   中英

How to check if a number in a list is less than another number in a list

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM