Python Quizs

CK CK 3788 
Created at
Updated at  
502 0 0

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)

 

Tags Pandas Python Algorithms Python Coding Python Quiz Facebook X
Comments 0
Similar posts
  1. Python code to convert PDF file to Excel Spreadsheet
    701
  2. Simple Example to get the total number of records in BigQuery with Python
    666
  1. What is RedisVL?
    109
  2. What “GPU Clustering” Really Means (And How to Code for It)
    204
  3. How to Build a Python Chatbot That Writes and Runs Code Using Microsoft AutoGen (With Sample Code)
    239
  4. Beyond Prompt Engineering: Why Loop Engineering is the Future of Autonomous AI
    303
  5. A Python Code to get the Server Instance ID for Remote Management
    362
  6. From Local Python Web to Standalone
    2,046
  7. Demystifying FAISS: Your Guide to ANN(Approximate Nearest Neighbor) Search
    320
  8. TensorRT for LLMs: Speed, Scale, and Why Startups Choose It Over TensorFlow
    461
  9. Python ML Technologies used for the target Segmentation
    378
  10. Managing WHITE_LIST in FastAPI to Improve the Server Security
    349
  11. A common async example
    972
  12. Milvus and LLM Integration - Very Smart Approach!
    297
  13. Automated API Documentation with PyCharm
    892
  14. How to install python 3.9 alongside python 3.8 on CentOS 7?
    711
  15. How to run Python 3.9 on Mac?
    652
  16. Automated OpenAPI documentation for a Python Flask API
    1,120
  17. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,030
  18. Uploading a file to a Google Drive Folder programmatically with Python
    3,307
  19. Garbage Collection when your system does not have enough memory in your Python App
    1,014
  20. Method to maximize full CPU performance with Python
    317
  21. How do I get the maximum available of thread in python?
    991
  22. Using Queue Algorithm with Redis - RPUSH and LPOP
    770
  23. Use cache concept with Redis : Let's do Redis programming with Python
    533
  24. Installing Python 3.8 in a venv environment on CentOS 7
    463
  25. CUDA versus OpenCL
    579
  26. Simple gRPC server based on Python
    396
  27. Python script to list files on your Google Drive and download one of them
    941
  28. Coinbase Python API - Basic Example
    462
  29. AWS Lambda Code Example based on Python
    333
  30. Python code using GPU on CentOS with AWS
    1,252
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    21,044
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    252
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    515
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  14. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    232
  15. TPU & GPU Cluster Management Tools
    245
  16. The Concept of Scaffolding in AI Agents
    234
  17. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  18. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  19. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  20. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  21. Machine Learning: Training vs. Ranking
    222
  22. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  23. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  24. Designing a Data Curation System Around a Vector Database
    221
  25. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  26. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  27. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  28. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  29. Understanding Data Lineage
    263
  30. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    167