Filter Restaurants by Vegan-Friendly, Price and Distance

Given the array of restaurants and the specific filters, we want to filter the restaurants and return their IDs sorted by rating and then by ID.

The code can be simple by using Python’s built-in functions for filtering and sorting.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
        # Filter the restaurants according to the given constraints
        filtered_restaurants = [
            r for r in restaurants 
            if (veganFriendly == 0 or r[2] == veganFriendly) 
            and r[3] <= maxPrice 
            and r[4] <= maxDistance
        ]

        # Sort the filtered restaurants by rating and then by ID
        sorted_restaurants = sorted(filtered_restaurants, key=lambda x: (-x[1], -x[0]))

        # Return only the IDs of the sorted restaurants
        return [r[0] for r in sorted_restaurants]

Explanation:

  1. We first filter the restaurants based on the provided constraints. We include a restaurant if the veganFriendly filter is 0 or if it matches the restaurant’s vegan-friendly status, and if its price and distance are within the given maximum limits.
  2. We then sort the filtered restaurants by rating in descending order, and by ID in descending order for those with the same rating.
  3. Finally, we extract and return the IDs of the sorted restaurants.

This code applies the given filters and then orders the restaurants as required, providing the correct result.