Program to find out the number of people who get a food packet using Python

PythonServer Side ProgrammingProgramming

Suppose in a conference, there are two types of people. The first type of people prefers a vegetarian lunch, and the other type prefers a non-vegetarian lunch. But there are a limited number of packets, and if the vegetarians receive a non-vegetarian packet or vice versa; they will not take that packet and wait until they get their preferred one. So, the two different types of packets and people are denoted as 0 for vegetarian and 1 for non-vegetarian. Now we are given two arrays, one containing n number of food packets denoted by 0 and 1 and another array containing the queue of m number of people, and their preferences are denoted by 0 and 1. So, if one person does not receive their preferred packet, they re-enter the queue at the end and wait for their preferred packet. So, we have to find out the number of people without food packets so that we can arrange their preferred packets.

So, if the input is like people = [0,1,1,0], packets = [0, 1, 0, 0], then the output will be 1.

So two people are preferring non-veg food and there is only one non-veg packet. The first person in the line preferring non-veg gets that packet and the other person keeps waiting because there is no other non-veg packet. So, the output is 1.

To solve this, we will follow these steps −

  • temp_arr := a new list containing values 0 and 0

  • for each person in people, do

    • temp_arr[person] := temp_arr[person] + 1

  • k := 0

  • while k < size of packets, do

    • if temp_arr[packets[k]]>0, then

      • temp_arr[packets[k]] := temp_arr[packets[k]] - 1

    • otherwise,

      • come out from the loop

    • k := k + 1

  • return size of packets - k


Let us see the following implementation to get better understanding −

def solve(people, packets):
   temp_arr = [0,0]
   for person in people:
      temp_arr[person] += 1
   k = 0
   while k < len(packets):
      if temp_arr[packets[k]]>0:
      k += 1
   return len(packets) - k

print(solve([0,1,1,0], [0, 1, 0, 0]))


[0,1,1,0], [0, 1, 0, 0]


Published on 05-Oct-2021 12:48:51