Program to sorting important mails from different mailboxes in Python


Suppose we have a list of mailboxes. Here in each mailbox a list of strings is given, here each string is either "J" for junk, "P" for personal, "W" for Work. We will go through each mailbox in round robin order starting from the first mailbox, filtering out J, to form a single list and return the list.

So, if the input is like mailboxes = [["W", "P"],["J", "P", "J"],["W"]], then the output will be ["W", "W", "P", "P"], as in order and without filtering, we have W -> J -> W -> P -> P -> J, now since we filter out the junk we get W -> W -> P -> P.

To solve this, we will follow these steps −

  • n_mailboxes := size of mailboxes
  • result := a new list
  • counts := a list of size n_mailboxes, then fill with 0
  • more := True
  • while more is non-zero, do
    • more := False
    • for i in range 0 to n_mailboxes, do
      • index := counts[i], mailbox := mailboxes[i]
      • if index < size of mailbox, then
        • more := True
        • counts[i] := counts[i] + 1
        • mail := mailbox[index]
        • if mail is not same as "J", then
          • insert mail at the end of result
  • return result

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, mailboxes):
      n_mailboxes = len(mailboxes)
      result = []
      counts = [0]*n_mailboxes
      more = True
      while more:
         more = False
         for i in range(n_mailboxes):
            index, mailbox = counts[i], mailboxes[i]
            if index < len(mailbox):
               more = True
               counts[i] += 1
               mail = mailbox[index]
               if mail != "J":
                  result.append(mail)
         return result
ob = Solution()
mailboxes = [["W", "P"],["J", "P", "J"],["W"]]
print(ob.solve(mailboxes))

Input

[["W", "P"],["J", "P", "J"],["W"]]

Output

['W', 'W', 'P', 'P']

Updated on: 05-Oct-2020

315 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements