
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Passenger Pickup and Drop Feasibility in Python
Suppose we have a matrix called requested_trips where each row containing [start_x, end_x, num_passengers], and we also have a capacity value. Now each requested trip asks to pick up num_passengers passenger at start_x and drop them off at end_x. We also have a car with the capacity that is given, and start at position x = 0. We want to to pick up every passenger and can only move right side, we have to check whether we can pick up and drop off everyone.
So, if the input is like trips = [[1, 25, 2], [3, 4, 3],[5, 12, 3]] capacity = 6, then the output will be True
To solve this, we will follow these steps −
events := a new list
-
for each set (sx, ex, np) in trips, do
insert pair (sx, np) at the end of events
insert pair (ex, −np) at the end of events
carrying := 0
-
for each pair (loc, delta) in the list of events (in sorted order), do
carrying := carrying + delta
-
if carrying > capacity, then
return False
return True
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, trips, capacity): events = [] for sx, ex, np in trips: events.append((sx, np)) events.append((ex, -np)) carrying = 0 for loc, delta in sorted(events): carrying += delta if carrying > capacity: return False return True ob = Solution() trips = [ [1, 25, 2], [3, 4, 3], [5, 12, 3] ] capacity = 6 print(ob.solve(trips, capacity))
Input
trips = [ [1, 25, 2], [3, 4, 3], [5, 12, 3] ] capacity = 6
Output
True