Program to check all listed delivery operations are valid or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of strings called orders. Each element in the orders list starts with either "P" or "D". The "P" indicates that is picked up, and "D" means "delivery". And these letters are followed by the order id number. For example, "P6" indicates pick up order 6. We have to check whether orders list is valid or not based on these rules −

  • We cannot delivery an order before pickup
  • Every pickup must be delivered
  • An order which is already been picked up and also delivered cannot be picked up or delivered again

So, if the input is like orders = ["P1", "D1", "P2", "P3", "D3", "D2"], then the output will be True, because first order is delivered after picking up, and for the second and third order they are picked up at once and also delivered finally.

To solve this, we will follow these steps −

  • a := a new map
  • if orders have any duplicate entries, then
    • return False
  • for each i in orders, do
    • if i starts with "P", then
      • a[pick up order number] = 1
    • otherwise when i starts with "D", then
      • if order number is not in a, then
        • return False
      • otherwise,
        • a[delivery order number] decrease by 1
  • return true when sum of all elements present in list of all values of a is same as 0, otherwise false

Example

Let us see the following implementation to get better understanding −

def solve(orders):
   a = {}
   if len(set(orders)) != len(orders):
      return False
   for i in orders:
      if i[0] == "P":
         a[i[1:]] = 1
      elif i[0] == "D":
         if i[1:] not in a:
            return False
         else:
            a[i[1:]] -= 1
   return sum(a.values()) == 0

orders = ["P1", "D1", "P2", "P3", "D3", "D2"]
print(solve(orders))

Input

["P1", "D1", "P2", "P3", "D3", "D2"]

Output

True
raja
Published on 14-Oct-2021 11:45:32
Advertisements