
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Car Pooling in Python
Suppose there is a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east, so we cannot turn around and drive west. We have given a list of trips, trip[i] = [num_passengers, start_location, end_location], that contains information about the ith trip:, so that is the number of passengers that must be picked up, and the locations to pick them up and drop them off. Here the locations are given as the number of kilometers due east from our vehicle's initial location. Our module will return true if and only if it is possible to pick up and drop off all passengers for all the given trips. So if trips are like [[2,1,5],[3,3,7]] and capacity is 5, then the output will be true.
To solve this, we will follow these steps −
- make one array called stops, of size 1000, and fill this with 0
- for i in trips
- stops[i[1]] := stops[i[1]] + i[0]
- stops[i[2]] := stops[i[1]] – i[0]
- for i in stops −
- capacity := capacity – i
- if capacity < 0, then return false
- return true when capacity >= 0
Let us see the following implementation to get better understanding −
Example
class Solution(object): def carPooling(self, trips, capacity): stops = [0 for i in range(1001)] for i in trips: stops[i[1]]+=i[0] stops[i[2]]-=i[0] for i in stops: capacity-=i if capacity<0: return False return capacity>=0 ob = Solution() print(ob.carPooling([[2,1,5],[3,3,7]],5))
Input
[[2,1,5],[3,3,7]] 5
Output
True
- Related Articles
- Synchronization and Pooling of processes in Python
- Synchronization and Pooling of processes in C#
- How to apply a 2D Average Pooling in PyTorch?
- How to apply a 2D Max Pooling in PyTorch?\n
- Distinguish between pooling of interest and purchase method
- What is connection pooling in C# and how to achieve it?
- Race Car in C++
- Car Fleet in C++
- Electric Car
- Solar Car
- Count passing car pairs in C++
- How to Live in Your Car?
- A car is travelling with a speed of $36\ km/h$. The driver applied the brakes and retards the car uniformly. The car is stopped in $5\ sec.$ Find the acceleration of car.
- Who invented the car?
- Program to find the size of the longest sublist where car speed is constant in python
