Skip to content
🤔prompts chat🧠
🔍
question:# New Question: String Formatting Utility Design and implement a class `StringFormatter` that provides several utility methods for common string manipulation tasks. Your class should offer methods to format the strings in different ways. **Class Definition**: `StringFormatter` **Methods**: 1. `to_title_case(text: str) -> str`: Converts the input text to title case (first letter of each word capitalized). 2. `to_snake_case(text: str) -> str`: Converts the input text to snake case (words are lowercased and separated by underscores). 3. `to_caps_lock(text: str) -> str`: Converts the input text to all uppercase letters. 4. `to_lower_case(text: str) -> str`: Converts the input text to all lowercase letters. 5. `reverse(text: str) -> str`: Reverses the characters in the input text. **Input**: - All methods take a single string (`text`). **Output**: - Each method returns a single string representing the transformed version of the input text. **Constraints**: - The input string can contain alphabets, numbers, spaces, and punctuation. # Example ```python formatter = StringFormatter() print(formatter.to_title_case("hello world")) # Output: "Hello World" print(formatter.to_snake_case("Hello World")) # Output: "hello_world" print(formatter.to_caps_lock("Hello World")) # Output: "HELLO WORLD" print(formatter.to_lower_case("Hello World")) # Output: "hello world" print(formatter.reverse("Hello World")) # Output: "dlroW olleH" ``` # Performance Requirements: - The methods should handle strings of length up to `10^6` efficiently. Implement the `StringFormatter` class ensuring all transformations are correctly handled and edge cases (like empty strings or excessive spaces) are properly managed.

answer:import re class StringFormatter: @staticmethod def to_title_case(text: str) -> str: Converts the input text to title case (first letter of each word capitalized). return text.title() @staticmethod def to_snake_case(text: str) -> str: Converts the input text to snake case (words are lowercased and separated by underscores). text = re.sub(r'[W_]+', ' ', text) return '_'.join(text.lower().split()) @staticmethod def to_caps_lock(text: str) -> str: Converts the input text to all uppercase letters. return text.upper() @staticmethod def to_lower_case(text: str) -> str: Converts the input text to all lowercase letters. return text.lower() @staticmethod def reverse(text: str) -> str: Reverses the characters in the input text. return text[::-1]

question:# Coding Assessment Question **Objective**: Assess students' ability to analyze and implement efficient data structures and algorithms for solving real-world problems. **Background**: In a vast and interconnected city, the delivery company wants to streamline its delivery routes. The city is represented as a grid, and each point on the grid may have different elevations, making some routes more costly in terms of travel effort. Your task is to implement an algorithm that calculates the minimum cost to travel from the top-left corner to the bottom-right corner of the grid, only moving right or down. The cost of entering each cell is defined by its elevation. **Task**: 1. **Function Implementation**: Implement a function called `min_travel_cost` that: - Accepts a 2D list `grid` representing the elevations of each point in the city. - Returns the minimum cost to travel from the top-left corner to the bottom-right corner. 2. **Constraints**: - You may travel right or down at each step. - The grid size can be up to 1000x1000. 3. **Edge Cases**: Handle possible edge cases such as: - Minimal grid size of 1x1. - Grids where all elevations are the same. **Input/Output**: - Input: `min_travel_cost(grid: List[List[int]]) -> int` - `grid`: A 2D list of integers representing the elevation costs. - Output: Returns the minimum travel cost from the top-left to the bottom-right. **Constraints**: - 1 ≤ len(grid), len(grid[0]) ≤ 1000 - 0 ≤ elevation value in `grid` ≤ 10000 **Performance Requirements**: - Your solution should execute efficiently within time and space constraints for the upper limit of grid size 1000x1000. # Example ```python def min_travel_cost(grid: List[List[int]]) -> int: pass # Example Usage assert min_travel_cost([[1, 3, 1], [1, 5, 1], [4, 2, 1]]) == 7 assert min_travel_cost([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == 21 assert min_travel_cost([[1]]) == 1 assert min_travel_cost([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) == 0 ``` Provide a well-commented and efficient solution to this problem.

answer:from typing import List def min_travel_cost(grid: List[List[int]]) -> int: Calculate the minimum travel cost to move from the top-left corner to the bottom-right corner of the grid, only allowing moves to the right or down. rows, cols = len(grid), len(grid[0]) # Create a dp table to store the minimum cost to reach each cell dp = [[0] * cols for _ in range(rows)] # Initialize the top-left corner dp[0][0] = grid[0][0] # Fill the first row (can only come from the left) for j in range(1, cols): dp[0][j] = dp[0][j-1] + grid[0][j] # Fill the first column (can only come from above) for i in range(1, rows): dp[i][0] = dp[i-1][0] + grid[i][0] # Fill the rest of the dp table for i in range(1, rows): for j in range(1, cols): dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j] # The bottom-right corner will have the result return dp[rows-1][cols-1]

question:# Coding Assessment Question **Context:** You are developing a utility module for managing game scores. One of the functionalities required is to compute the rank of a particular score in a list of scores. The rank should be determined based on the highest scores, with 1 being the highest rank. The ranking should handle ties by assigning the same rank to equal scores and skipping the next ranks accordingly. # Task: Implement a function `rank_scores(scores: List[int], target: int) -> int` that computes the rank of a given `target` score in a list of `scores`. Function Signature: ```python def rank_scores(scores: List[int], target: int) -> int: pass ``` # Input: - A list of integers `scores`. - An integer `target`. # Output: - Return the rank (an integer) of the `target` score in the list of `scores`. If the `target` does not appear in the list, return `-1`. # Constraints: - The input `scores` list will have the following properties: * The length of `scores` will be between 0 and (10^5). * Each score in `scores` and the `target` score will be between (-10^9) and (10^9). - You should handle cases where the input types are not as expected by raising a `TypeError`. # Example: ```python >>> rank_scores([100, 200, 50, 100, 75], 100) 2 >>> rank_scores([100, 200, 50, 100, 75], 200) 1 >>> rank_scores([100, 200, 50, 100, 75], 50) 4 >>> rank_scores([100, 200, 50, 100, 75], 300) -1 >>> rank_scores([], 100) -1 >>> rank_scores([100, 200, 50, 100, 75], -100) -1 >>> rank_scores("invalid input", 100) Traceback (most recent call last): ... TypeError: 'scores' should be a list of integers >>> rank_scores(None, 100) Traceback (most recent call last): ... TypeError: 'scores' should be a list of integers >>> rank_scores([100, 200, 50, 100, 75], "invalid target") Traceback (most recent call last): ... TypeError: 'target' should be an integer ``` **Note:** You should ensure your function handles edge cases like an empty list and invalid input types providing meaningful error messages.

answer:from typing import List def rank_scores(scores: List[int], target: int) -> int: if not isinstance(scores, list) or not all(isinstance(score, int) for score in scores): raise TypeError("'scores' should be a list of integers") if not isinstance(target, int): raise TypeError("'target' should be an integer") if target not in scores: return -1 sorted_unique_scores = sorted(set(scores), reverse=True) rank = sorted_unique_scores.index(target) + 1 return rank

question:# Problem Statement A security system has been implemented to monitor temperature fluctuations in a server room. The system records the temperature once every minute, and stores these readings in an array. Your task is to create a function that will determine the number of times a certain temperature threshold is exceeded for a given consecutive number of minutes. **Function Signature:** ```python def count_exceedances(temperature_readings: List[int], threshold: int, duration: int) -> int: pass ``` # Inputs: 1. **temperature_readings (List[int]):** An array representing the temperature readings taken each minute (1 ≤ len(temperature_readings) ≤ 10^5). 2. **threshold (int):** An integer representing the temperature threshold. 3. **duration (int):** An integer representing the number of consecutive minutes to check the temperature readings (1 ≤ duration ≤ len(temperature_readings)). # Outputs: - **Returns (int):** The number of times the temperature exceeded the threshold consecutively for the given number of minutes. # Example: ```python print(count_exceedances([70, 72, 68, 65, 74, 75, 76, 70, 69, 71], 72, 3)) # Output: 1 ``` Explanation: In the given example, the only consecutive sequence of 3 temperatures where all readings exceed 72 is [74, 75, 76]. The function thus returns `1` for this single exceedance. --- By maintaining a consistent format, scope, and difficulty as the sample question, this new question integrates seamlessly into the original set. The focus on list manipulation and loop-based logic provides a challenge of similar complexity, targeting proficiency in handling arrays.

answer:from typing import List def count_exceedances(temperature_readings: List[int], threshold: int, duration: int) -> int: Counts the number of times the temperature exceeds the threshold for at least the given number of consecutive minutes. :param temperature_readings: List of temperature readings. :param threshold: The temperature threshold. :param duration: Number of consecutive minutes to consider. :return: The number of exceedances. if len(temperature_readings) < duration: return 0 exceedances_count = 0 consecutive_count = 0 for i in range(len(temperature_readings)): if temperature_readings[i] > threshold: consecutive_count += 1 if consecutive_count >= duration: exceedances_count += 1 else: consecutive_count = 0 return exceedances_count

Released under the chat License.

has loaded