| Method Chaining DataFrame animals
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| name | object |
| species | object |
| age | int |
| weight | int |
+-------------+--------+
Write a solution to list the names of animals that weigh strictly more than 100 kilograms.
Return the animals sorted by weight in descending order.
The result format is in the following example.
Example 1:
Input:
DataFrame animals:
+----------+---------+-----+--------+
| name | species | age | weight |
+----------+---------+-----+--------+
| Tatiana | Snake | 98 | 464 |
| Khaled | Giraffe | 50 | 41 |
| Alex | Leopard | 6 | 328 |
| Jonathan | Monkey | 45 | 463 |
| Stefan | Bear | 100 | 50 |
| Tommy | Panda | 26 | 349 |
+----------+---------+-----+--------+
Output:
+----------+
| name |
+----------+
| Tatiana |
| Jonathan |
| Tommy |
| Alex |
+----------+
Explanation:
All animals weighing more than 100 should be included in the results table.
Tatiana's weight is 464, Jonathan's weight is 463, Tommy's weight is 349, and Alex's weight is 328.
The results should be sorted in descending order of weight.
In Pandas, method chaining enables us to perform operations on a DataFrame without breaking up each operation into a separate line or creating multiple temporary variables.
Can you complete this task in just one line of code using method chaining?
Answer - the question is asking to complete the task in one line of code def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
return animals[animals['weight'] > 100].sort_values(by='weight', ascending=False)[['name']]
Another Answer import pandas as pd
def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
result = {
"name":[]
}
# sort table
animals_sorted = animals.sort_values(by='weight',ascending=False)
# get records
for animal in animals_sorted.itertuples():
if animal.weight>100:
result["name"].append( animal.name )
# return
return pd.DataFrame(result)
Check if Grid can be Cut into Sections You are given an integer n representing the dimensions of an n x n grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates rectangles, where rectangles[i] is in the form [startx, starty, endx, endy], representing a rectangle on the grid. Each rectangle is defined as follows:
(startx, starty): The bottom-left corner of the rectangle.
(endx, endy): The top-right corner of the rectangle.
Note that the rectangles do not overlap. Your task is to determine if it is possible to make either two horizontal or two vertical cuts on the grid such that:
Each of the three resulting sections formed by the cuts contains at least one rectangle.
Every rectangle belongs to exactly one section.
Return true if such cuts can be made; otherwise, return false.
Example 1:
Input: n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]
Output: true
Explanation:
The grid is shown in the diagram. We can make horizontal cuts at y = 2 and y = 4. Hence, output is true.
Example 2:
Input: n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,3]]
Output: true
Explanation:
We can make vertical cuts at x = 2 and x = 3. Hence, output is true.
Example 3:
Input: n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]
Output: false
Explanation:
We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.
Constraints:
3 <= n <= 109
3 <= rectangles.length <= 105
0 <= rectangles[i][0] < rectangles[i][2] <= n
0 <= rectangles[i][1] < rectangles[i][3] <= n
No two rectangles overlap.
Code I implemented class Solution:
def checkValidCuts(self, n: int, rectangles: List[List[int]]) -> bool:
def print_matrix(m):
nonlocal x, y
for x in range( 0, n+1):
for y in range( 0, n+1):
print( f"{m[x][y]}", end=" ")
print( "")
# set initial matrix
matrix = {}
for i in range(0,n+1):
matrix[i] = {}
for j in range(0, n+1):
matrix[i][j] = 0
for rectangle in rectangles:
# set coordinate
x1 = rectangle[0]
y1 = rectangle[1]
x2 = rectangle[2]
y2 = rectangle[3]
if x2>n: return False
if y2>n: return False
# leave foot prints within the range
for x in range(x1, x2+1):
for y in range( y1, y2+1):
matrix[x][y] += 1
if matrix[x][y]>2:
print_matrix(matrix)
return False
print(matrix)
return True
Solutions Found from typing import List
class Solution:
def isPossible(self, rectangles: List[List[int]], k: int) -> bool:
# Sort rectangles based on the k-th coordinate (either x or y)
rectangles.sort(key=lambda x: x[k])
cuts = 0
mx = rectangles[0][k + 2] # Track the maximum endpoint
# Iterate through rectangles to check for possible cuts
for rect in rectangles:
b, e = rect[k], rect[k + 2]
# If there's a valid gap, increment the cut count
if mx <= b:
cuts += 1
# Update the maximum endpoint
mx = max(mx, e)
# At least two valid cuts should be present
return cuts >= 2
def checkValidCuts(self, n: int, rectangles: List[List[int]]) -> bool:
return self.isPossible(rectangles, 0) or self.isPossible(rectangles, 1)
|