source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_instruct_75k
8,873
Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock at most twice. The function should take a list of integers representing the prices of a stock on different days and return an integer representing the maximum profit. You cannot engage in multiple transactions at ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_profit(prices: List[int]) -> int: """ Calculate the maximum profit that can be obtained by buying and selling a stock at most twice. Args: prices (List[int]): A list of integers repr...
magic_instruct_75k
8,882
Write a Python function to create minibatches of data for training a neural network. The function should take a list of tuples, where each tuple contains a sequence of words and its corresponding label, and an integer representing the size of each minibatch. The function should return a list of minibatches, where each ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def minibatches(data: List[Tuple[List[str], int]], minibatchSize: int) -> Tuple[List[List[List[str]]], List[List[int]]]: """ Create minibatches of data for training a neural network. Args: ...
magic_instruct_75k
8,888
Write a Python function to delete a specific proxy from a list of proxies. Each proxy is represented as a string in the format "host:port". The function should take in the list of proxies and the proxy to be deleted as parameters, and return the updated list of proxies after removing the specified proxy. The code shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def delete_proxy(proxies: List[str], proxy_to_delete: str) -> List[str]: """ Deletes a specific proxy from a list of proxies. Args: proxies (List[str]): A list of strings representing proxie...
magic_instruct_75k
8,899
Write a Python program to generate a form based on a given set of fields and their corresponding categories. The form should be structured as a dictionary where the keys are the categories and the values are lists of fields belonging to each category. Additionally, the program should be able to validate whether a given...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Tuple def generate_form(fields: List[Tuple[str, Dict[str, Tuple[str, ...]]]]) -> Dict[str, List[str]]: """ Generate a form dictionary from a list of tuples. Args: fields: A list of tu...
magic_instruct_75k
8,906
Write a Python function to calculate the volume of a rectangular extrusion and verify its correctness. The function should take the outer rectangle dimensions (length, width), inner rectangle dimensions (length, width), extrusion height, and expected volume as input. The function should return a boolean value indicatin...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_and_verify_volume(outer_length: float, outer_width: float, inner_length: float, inner_width: float, height: float, expected_volume: float) -> bool: """ Calculate the volume of a rectangular extrusion and verify its...
magic_instruct_75k
8,907
Write a Python function to aggregate the total resources for each unique VM flavor from a list of VM details. Each VM detail is represented as a list containing the following information in order: ID (int), Name (str), VCPU count (int), VMEM size in GB (int), Disk size in GB (int). The function should return a dictiona...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def aggregate_resources(vm_details: List[List[Union[int, str]]]) -> Dict[str, List[int]]: """ Aggregate the total resources for each unique VM flavor from a list of VM details. Args: ...
magic_instruct_75k
8,913
Write a Python function to replace all occurrences of a lowercase letter with its corresponding uppercase letter in a given string, without using the `replace` method. The function should return the modified string. The code should start with: ```python def replace_letters(s: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def replace_letters(s: str) -> str: """ Replaces all occurrences of a lowercase letter with its corresponding uppercase letter in the given string. Args: s (str): The input string consisting of lowercase and upperca...
magic_instruct_75k
8,975
Write a Python function to determine whether a given integer is a palindrome. A palindrome is a number that reads the same backward as forward. For example, 121 is a palindrome, while 123 is not. The function should start with: ```python def is_palindrome(x: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(x: int) -> bool: """ Determine whether a given integer is a palindrome. Args: x (int): The integer to check for palindrome property. Returns: bool: True if the integer is a palindrome,...
magic_instruct_75k
8,989
Write a Python function `generate_model_summary(model_layers_info)` that takes a list of dictionaries `model_layers_info` as input and returns a dictionary containing the following information: - "total_num_layers": Total number of layers in the model. - "total_params": Total number of parameters in the model. - "layer...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def generate_model_summary(model_layers_info: List[Dict[str, any]]) -> Dict[str, any]: """ Generates a summary report for a machine learning model's layers. Args: model_layers_info (Li...
magic_instruct_75k
8,993
Write a Python function to filter out the names of people who are 18 years or older from a given list of tuples, where each tuple contains a person's name and their age. The function should return a new list containing only the names of the adults. The code should start with: ```python from typing import List, Tuple ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def filter_adults(people: List[Tuple[str, int]]) -> List[str]: """ Filters out the names of people who are 18 years or older from a given list of tuples. Args: people (List[Tuple[str,...
magic_instruct_75k
8,998
Write a Python function to generate a configuration file content for a server based on the provided server address and email address. The function should take two parameters: `server_address` (a string) and `email_address` (a string). The function should return a string containing the configuration file content in the ...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_config_file(server_address: str, email_address: str) -> str: """ Generates a configuration file content for a server based on the provided server address and email address. Args: server_address (str): T...
magic_instruct_75k
9,029
Write a Python function to determine if a given string is a palindrome. A palindrome is a sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization. The function should take a string as input and return `True` if the string is a palindrome, and `False` otherwi...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(s: str) -> bool: """ Determine if a given string is a palindrome. A palindrome is a sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization...
magic_instruct_75k
9,031
Write a Python function to update a dictionary of filter parameters based on a given field name and its corresponding value. The function should take in the dictionary of filter parameters, the field name, and the value to filter by, and update the dictionary accordingly. The function should return the updated dictiona...
Here is the Python code to solve the given problem in the markdown block: ```python def update_filter_params(filter_params: dict, field: str, slug: str) -> dict: """ Updates the filter parameters dictionary with the given field and its corresponding value. Args: filter_params (dict): The dictionary...
magic_instruct_75k
9,041
Write a Python function `compare_values` that takes two integer parameters, `code` and `value`. The function should return the result of a predefined function `value_fx` if `code` is equal to `value`. If `code` is not equal to `value`, the function should return the string 'fade'. The function should be implemented wit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Union def compare_values(code: int, value: int) -> Union[int, str]: """ Compares the given `code` and `value`. If they are equal, returns the result of `value_fx`. Otherwise, returns the string 'fade'. ...
magic_instruct_75k
9,056
Write a Python function to calculate the product of all elements in a given list using the `reduce` function from the `functools` module. The function should take a list of integers as input and return the product of all the elements in the list. The function should handle cases where the list is empty by returning 1, ...
Here is the Python code to solve the given problem in the markdown block: ```python from functools import reduce from typing import List def calculate_product(nums: List[int]) -> int: """ Calculate the product of all elements in a given list of integers. Args: nums (List[int]): A list of integers ...
magic_instruct_75k
9,063
Write a Python function to update the visibility and enabling/disabling status of various UI elements based on the selected keyboard brightness option. The function should take a string representing the selected keyboard brightness option and return a dictionary containing the status of each UI element. The UI elements...
Here is the Python code to solve the given problem in the markdown block: ```python def updateUIElements(keyboardBrightnessOption: str) -> dict: """ Updates the visibility and enabling/disabling status of various UI elements based on the selected keyboard brightness option. Args: keyboardBrightness...
magic_instruct_75k
9,081
Write a Python function `process_header(header_data)` that takes a tuple `header_data` as input and processes it to generate a dictionary with specific key-value pairs. The input tuple contains four elements: `seg_ns`, `seg_lens`, `seg_means`, and `arm_lengths`. Each element is a list. The function should create a dict...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple, Dict def process_header(header_data: Tuple) -> Dict[str, Tuple[float, float, float]]: """ Processes the input tuple to generate a dictionary with segment names as keys and tuples of segment length, mea...
magic_instruct_75k
9,104
Write a Python function to generate optical illusion patterns based on given parameters. The function should take in the strength of the illusion, an array of colors for the rectangles and backgrounds, and an array of RGB values for the colors. The illusion type is determined by the strength of the illusion, where a st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def generate_optical_illusion(illusion_strength: int, colors: List[str], rgb: List[Tuple[int, int, int]]) -> Dict[str, str]: """ Generates an optical illusion pattern based on the given para...
magic_instruct_75k
9,126
Write a Python function to generate new names for a list of image files based on their directory and index. The function should take two lists as input: one for directory names and another for image names. It should return a dictionary mapping the original image names to their new names based on the following logic: - ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def generate_new_names(directory_names: List[str], image_names: List[str]) -> Dict[str, str]: """ Generates new names for a list of image files based on their directory and index. Args: ...
magic_instruct_75k
9,129
Write a Python function to count the occurrences of a specific key in a list of dictionaries. The function should return a new dictionary where the keys are the values associated with the specified key in the input dictionaries, and the values are the counts of how many times each value appears. If the input list is em...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_key_occurrences(list_of_dicts: List[Dict[str, any]], key: str) -> Dict[any, int]: """ Counts the occurrences of a specific key in a list of dictionaries. Args: list_of_dicts ...
magic_instruct_75k
9,130
Write a Python function to process form data based on a test mode flag. If the test mode flag is set to `True`, the function should return a message indicating that the form data processing is disabled. If the test mode flag is set to `False`, the function should process the form data and return a message indicating su...
Here is the Python code to solve the given problem in the markdown block: ```python def process_form_data(form_data: dict, test_mode: bool) -> str: """ Processes the form data based on the test mode flag. Args: form_data (dict): A dictionary containing form field names as keys and their correspondi...
magic_instruct_75k
9,135
Write a Python function to reverse a given string without using any built-in string reversal functions or methods. The function should handle both uppercase and lowercase letters, as well as special characters and spaces. The code should start with: ```python def reverse_string(input_str: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_string(input_str: str) -> str: """ Reverses the given string without using any built-in string reversal functions or methods. Args: input_str (str): The string to be reversed. Returns: str: ...
magic_instruct_75k
9,154
Write a Python function to filter a dictionary containing meter names and their corresponding regions based on a specified region. The function should return a new dictionary containing only the meter names associated with the specified region. The code should start with: ```python from typing import Dict def filter_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def filter_meters_by_region(meter_dict: Dict[str, str], region: str) -> Dict[str, str]: """ Filters a dictionary of meter names and regions based on a specified region. Args: meter_dict (Dic...
magic_instruct_75k
9,156
Create a Python function that processes a configuration dictionary and returns a modified version of it. The configuration dictionary contains parameters for the ImFEATbox library, and your function needs to update specific parameters based on certain conditions. The function should start with: ```python from typing i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def update_imfeatbox_params(params: Dict[str, any]) -> Dict[str, any]: """ Updates specific parameters in the configuration dictionary for the ImFEATbox library based on the value of "feature_extraction"...
magic_instruct_75k
9,159
Write a Python function to process the raw output of a network device's "show ethernet-switching table" command and extract MAC address entries in a specific format. The function should take the raw output as input and return a list of dictionaries, where each dictionary contains the MAC address, interface, and VLAN in...
Here is the Python code to solve the given problem in the markdown block: ```python import re from typing import List, Dict def process_switching_table(raw_output: str) -> List[Dict[str, str]]: """ Processes the raw output of a network device's "show ethernet-switching table" command and extracts MAC addre...
magic_instruct_75k
9,171
Write a Python function to extract the repository name and the file path from a given code snippet. The repository name is the first part of the code snippet, and the file path is the second part. The repository name and file path are separated by a newline character (`\n`). The function should return a tuple containin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def extract_repo_and_file(code_snippet: str) -> Tuple[str, str]: """ Extracts the repository name and the file path from a given code snippet. The code snippet is expected to have the repository na...
magic_instruct_75k
9,176
Write a Python function to calculate the total area of a 2D terrain map represented by a grid of elevation values. The terrain map is given as a 2D list of integers, where each integer represents the elevation at that point on the map. The total area of the terrain is defined as the sum of the areas of all the individu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_total_area(terrain_map: List[List[int]]) -> int: """ Calculate the total area of a 2D terrain map represented by a grid of elevation values. Args: terrain_map (List[List[int]])...
magic_instruct_75k
9,183
Write a Python function to perform color conversion operations on a list of RGB colors. The function should take two parameters: a list of operations and a list of RGB colors. Each operation in the list can be either "min" or "max", indicating whether to find the minimum or maximum value of the RGB components for the c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def color_conversion(operations: List[str], colors: List[Tuple[int, int, int]]) -> List[int]: """ Perform color conversion operations on a list of RGB colors. Args: operations (List[s...
magic_instruct_75k
9,193
Write a Python function to compare the relationship representations of two entities and determine if they are not equal. The function should take two entities as input and return a boolean value indicating whether their relationship representations are not equal. The entities are assumed to have a method `get_relations...
Here is the Python code to solve the given problem in the markdown block: ```python def relationship_not_equal(entity1, entity2) -> bool: """ Compares the relationship representations of two entities and returns whether they are not equal. Args: entity1: The first entity to compare. entity2...
magic_instruct_75k
9,204
Write a Python function to process a list of strings based on a specific condition. The function should replace any string in the list that starts with a '#' symbol with an empty string, and then return the modified list. The function should be named `process_strings` and should take a list of strings as input. The co...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_strings(value: List[str]) -> List[str]: """ Processes a list of strings by replacing any string that starts with a '#' symbol with an empty string. Args: value (List[str]): A lis...
magic_instruct_75k
9,241
Write a Python function to apply a list of mathematical operations successively to an initial value of 0. Each operation in the list is represented as a string consisting of a mathematical operation followed by a number. The operations can be "add", "subtract", "multiply", or "divide". The result of each operation shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def apply_operations(operations: List[str]) -> int: """ Applies a list of mathematical operations successively to an initial value of 0. Args: operations (List[str]): A list of strings where...
magic_instruct_75k
9,263
Write a Python function to calculate the time it takes for a sewing machine to produce a single stitch based on its speed and the size of the stitches. The function should take two parameters: `stitchSpeed` (an integer representing the speed of the sewing machine) and `stitchSize` (an integer representing the size of t...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_stitch_time(stitch_speed: int, stitch_size: int) -> float: """ Calculate the time it takes for a sewing machine to produce a single stitch. Args: stitch_speed (int): The speed of the sewing machine, in...
magic_instruct_75k
9,295
Write a Python function to calculate the average score of a set of test results represented as a dictionary. The keys in the dictionary are the names of the tests (strings), and the values are the scores obtained (floats). The function should return the average score rounded to two decimal places. If the dictionary is ...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_average_score(test_results: dict) -> float: """ Calculate the average score of a set of test results. Args: test_results (dict): A dictionary where the keys are the names of the tests (strings) ...
magic_instruct_75k
9,307
Write a Python function to simulate a lottery process for selecting winners from a pool of applicants. The function should generate a specified number of random numbers to determine the winners and additional random numbers for supplementary data. The function should start with: ```python import random def simulate_lo...
Here is the Python code to solve the given problem in the markdown block: ```python import random from typing import List def generateOtherRandomNumbers(total_applicants: int, lottery_numbers: List[int]) -> List[int]: """ Generate supplementary random numbers that are not included in the lottery numbers. ...
magic_instruct_75k
9,309
Write a Python function to generate a formatted summary of server resource status from a given JSON object. The JSON object contains various metrics about the server's resources, such as CPU information, number of running virtual machines, free disk space, hypervisor version, available disk space, local disk space, fre...
Here is the Python code to solve the given problem in the markdown block: ```python import json def resource_status(resource_info: dict) -> str: """ Generate a formatted summary of server resource status from a given JSON object. Args: resource_info (dict): A dictionary containing server resource ...
magic_instruct_75k
9,312
Write a Python function `generate_flume_command` that constructs a command to deploy an Apache Flume agent based on customizable configurations. The function should accept the following parameters: - `agent_name` (string): The name of the Flume agent. Default value is "agent". - `conf_dir` (string): The Flume configura...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_flume_command(agent_name="agent", conf_dir="/opt/flume/conf/", flume_opts="-Dflume.root.logger=INFO,console", config_file="/opt/flume/conf/flume-conf.properties", additional_args=[]): """ Generates a command to depl...
magic_instruct_75k
9,319
Write a Python function that simulates the behavior of a provided Bash script used to generate Verilog code from Register Description Language (RDL) files. The function should take the `IPNAME` as input and return the command that would be executed by the Bash script. The command should include the execution of two Pyt...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_verilog_command(IPNAME: str) -> str: """ Generates a command string that simulates the behavior of a Bash script used to generate Verilog code from RDL files. Args: IPNAME (str): The name of the IP bloc...
magic_instruct_75k
9,320
Create a Python class `Library` that simulates a simple library management system. The class should allow users to add, remove, and display books in the library. Each book will have a title, author, and genre. Additionally, the class should provide the functionality to search for books by title or author. The `Library...
Here is the Python code to solve the given problem in the markdown block: ```python class Library: def __init__(self): """ Initializes an empty list to store books. """ self.books = [] def add_book(self, title, author, genre): """ Adds a new book to the library. ...
magic_instruct_75k
9,344
Create a Python class `RawFetcher` with a method `start()` that initiates an asynchronous data fetching process and returns `True` upon successful initiation. The data fetching process should simulate a delay using the `time.sleep()` function. The class should not use any external libraries or modules other than the st...
Here is the Python code to solve the given problem in the markdown block: ```python import threading import time class RawFetcher: """ A class to simulate an asynchronous data fetching process. Methods: start(): Initiates the data fetching process and returns True upon successful initiation. "...
magic_instruct_75k
9,355
Write a Python function to extract and return a list of non-Python dependencies from a given code snippet. The code snippet contains comments that specify the dependencies to be loaded. Each comment starts with `# >` followed by the name of the dependency. The function should be named `load_dependencies` and should tak...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def load_dependencies(code_snippet: str) -> List[str]: """ Extracts and returns a list of non-Python dependencies from a given code snippet. The code snippet contains comments that specify the depen...
magic_instruct_75k
9,389
Write a Python function to extract external citations from a list of citations in a legal document. Each citation is represented as a tuple containing three strings: the title, the constant string "CFR", and the part number. The function should ignore any citations that match the title and part being parsed, as they ar...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def extract_external_citations(citations: List[Tuple[str, str, str]], title: str, part: str) -> List[Tuple[str, str, str]]: """ Extracts external citations from a list of citations in a legal docu...
magic_instruct_75k
9,447
Write a Python function to determine whether a given set of nodes forms a convex hull based on the provided hull indices. The function should take two parameters: - `nodes`: a list of 2D nodes represented as tuples of two integers representing their x and y coordinates. - `hull`: a list of integers representing the ind...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def is_convex_hull(nodes: List[Tuple[int, int]], hull: List[int]) -> bool: """ Determine whether the given set of nodes forms a convex hull based on the provided hull indices. Args: n...
magic_instruct_75k
9,480
Write a Python function to simulate the behavior of the `PresentationManager` class described in the given Swift code snippet. The function should encapsulate the functionalities of setting presentation options, toggling full screen mode, and hiding the cursor. The function should accept a window identifier (simulated ...
Here is the Python code to solve the given problem in the markdown block: ```python def manage_presentation(window_id: str) -> None: """ Simulates the behavior of a macOS PresentationManager class that manages presentation options, toggles full screen mode, and hides the cursor for a given window. Args...
magic_instruct_75k
9,481
Write a Python function `extract_script_info(script)` that processes a multi-line string `script` containing commented-out lines and extracts specific information into a dictionary. The function should extract the following information: 1. The name of the backup folder. 2. The list of feature choices labels. 3. The lis...
Here is the Python code to solve the given problem in the markdown block: ```python import re def extract_script_info(script: str) -> dict: """ Extracts specific information from commented-out lines in a script and returns it as a dictionary. Args: script (str): A multi-line string representing th...
magic_instruct_75k
9,483
Create a Python function `mystery_function(arr)` that replicates the behavior of the given `mysteryFunction` in the code snippet. The `mystery_function` should take a list `arr` as input and return the modified list based on the behavior of the original `mysteryFunction`. The function should reverse the input list. Th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def mystery_function(arr: List[int]) -> List[int]: """ Reverses the input list. Args: arr (List[int]): The input list of integers to be reversed. Returns: List[int]: The reverse...
magic_instruct_75k
9,487
Write a Python function to extract the caret offset for each text field in a list of `InputTextField` instances. The caret offset is the position of the cursor within the text. The function should utilize the provided methods `_getCaretOffset` and `_getSelectionOffsets` to achieve this. The code should start with: ```...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List class InputTextField: def _getRawSelectionOffsets(self): # Mock implementation for demonstration purposes return [0, 0] def _getCaretOffset(self): # We want the active (moving) e...
magic_instruct_75k
9,496
Write a Python function to generate an annotation legend from a given dictionary of parameters. The function should format the key-value pairs from the dictionary into a string that represents the annotation legend. The output string should include the keys and their corresponding values, separated by a hyphen, and all...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_annotation_legend(params: dict) -> str: """ Generates an annotation legend from a dictionary of parameters. Args: params (dict): A dictionary where keys are parameter names and values are their correspo...
magic_instruct_75k
9,525
Write a Python function to find the nth number in the Fibonacci sequence. The Fibonacci sequence starts with 1 and 1, and each subsequent number is the sum of the two preceding numbers. The function should take an integer `n` as input and return the nth number in the sequence. The function should handle edge cases such...
Here is the Python code to solve the given problem in the markdown block: ```python def fibonacci_sequence(n: int) -> int: """ Calculate the nth number in the Fibonacci sequence. The Fibonacci sequence starts with 1 and 1, and each subsequent number is the sum of the two preceding numbers. Args: ...
magic_instruct_75k
9,526
Write a Python function to extract the `alt` text from an HTML image tag. The `alt` text is the descriptive text that is displayed if the image cannot be loaded. The function should take a string representing an HTML image tag as input and return the `alt` text. The input string will always contain a valid HTML image t...
Here is the Python code to solve the given problem in the markdown block: ```python import re def extractAltText(htmlImageTag: str) -> str: """ Extracts the alt text from an HTML image tag. Args: htmlImageTag (str): A string representing an HTML image tag with an alt attribute. Returns: ...
magic_instruct_75k
9,527
Write a Python function to convert a given color image represented as a 2D array of pixels into a grayscale image. Each pixel in the input image is represented by a tuple of three integers (r, g, b), where r, g, and b are the red, green, and blue color components, respectively. The function should average the r, g, and...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def process_image(image: List[List[Tuple[int, int, int]]], img_bytes_per_line: int) -> List[List[int]]: """ Convert a color image represented as a 2D array of pixels into a grayscale image. A...
magic_instruct_75k
9,543
Write a Python function to implement a CPU task scheduler that assigns a new task to the CPU core with the least total task duration. If multiple cores have the same total task duration, the task should be assigned to the core with the lowest index. The function should return the index of the CPU core to which the task...
Here is the Python code to solve the given problem in the markdown block: ```python def assignTask(cpuLists: dict, taskId: str, taskDuration: int) -> int: """ Assigns a new task to the CPU core with the least total task duration. If multiple cores have the same total task duration, the task is assigned to t...
magic_instruct_75k
9,544
Write a Python function `process_training_config(config)` that processes a configuration dictionary for a deep learning training pipeline. The function should extract specific information from the dictionary and perform calculations based on the extracted data. Specifically, the function should: 1. Calculate the total ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Tuple def process_training_config(config: Dict) -> Tuple[int, str]: """ Processes a configuration dictionary for a deep learning training pipeline. Args: config (Dict): A dictionary contain...
magic_instruct_75k
9,551
Write a Python function to validate a software license key based on specific criteria. The license key is represented as a string containing alphanumeric characters and dashes. The function should check if the license key is valid according to the following rules: 1. The key must consist only of alphanumeric characters...
Here is the Python code to solve the given problem in the markdown block: ```python def validate_license_key(license_key: str, key_length: int, group_length: int) -> bool: """ Validates a software license key based on specific criteria. Args: license_key (str): The license key to be validated. ...
magic_instruct_75k
9,570
Write a Python function to generate a command-line string for training a DensePose model using the Detectron2 library. The function should take the configuration name, batch size, and base learning rate as inputs and return a complete command string that includes the configuration file, resume flag, batch size, base le...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_training_command(cfg_name: str, batch_size: int, base_lr: float) -> str: """ Generates a command-line string for training a DensePose model using the Detectron2 library. Args: cfg_name (str): The name o...
magic_instruct_75k
9,588
Write a Python function to process a dictionary containing details of supplier invoices and credit notes. The function should take the input dictionary and return a new dictionary containing specific details extracted from the input. The input dictionary, `sup_details`, contains the following key-value pairs: - "suppli...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict # Define the INV_TYPE and ISD_TYPE dictionaries INV_TYPE = { "ISD": "ISD Invoice", "ISDCN": "ISD Credit Note" } ISD_TYPE = { "Other Details Amended": "Other Details Amended", "Other Details": "O...
magic_instruct_75k
9,589
Write a Python function to generate a random double within a given range. The function should take in a minimum and maximum value and return a random double within that range. The code should start with: ```python import random def get_random_double(min_val: float, max_val: float) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python import random def get_random_double(min_val: float, max_val: float) -> float: """ Generates a random double within the specified range [min_val, max_val]. Args: min_val (float): The minimum value of the range. ...
magic_instruct_75k
9,606
Write a Python function to count the occurrences of each type of database migration operation from a given list of operations. Each operation is represented as a tuple where the first element is the type of operation (one of "create", "alter", "delete", or "rename") and the second element is the name of the migration. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def count_migration_operations(operations: List[Tuple[str, str]]) -> Dict[str, int]: """ Counts the occurrences of each type of database migration operation from a given list of operations. ...
magic_instruct_75k
9,635
Write a Python function to extract the content between two specific markers in a given string. The function should take in a string and two marker strings as input and return the content between the markers. If the markers are not found or are in the wrong order, the function should return an empty string. The code sh...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_content(input_string: str, start_marker: str, end_marker: str) -> str: """ Extracts the content between two specific markers in a given string. Args: input_string (str): The input string from which to ex...
magic_instruct_75k
9,638
Write a Python function to count the occurrences of each type of database migration operation in a given list. Each operation is represented as an instance of a class from the `migrations` module, which contains classes such as `AlterField`, `AddField`, `DeleteModel`, etc. The function should return a dictionary where ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_migration_operations(operations: List) -> Dict[str, int]: """ Counts the occurrences of each type of database migration operation in a given list. Args: operations (List): A ...
magic_instruct_75k
9,644
Write a Python function to rearrange a list of lowercase letters such that all the odd-indexed letters are placed before all the even-indexed letters. The function should take a list of lowercase letters as input and return the rearranged list. The code should start with: ```python from typing import List def rearran...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def rearrange_letters(letter_list: List[str]) -> List[str]: """ Rearranges a list of lowercase letters such that all odd-indexed letters are placed before all even-indexed letters. Args: let...
magic_instruct_75k
9,651
Write a Python function to simulate a simple job scheduling algorithm that minimizes the total waiting time for a list of jobs. Each job is represented as a tuple `(start_time, duration)`, where `start_time` is the time at which the job becomes available for execution, and `duration` is the time it takes to complete th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def minimize_waiting_time(jobs: List[Tuple[int, int]]) -> List[Tuple[int, int]]: """ Simulates a job scheduling algorithm to minimize the total waiting time for a list of jobs. Args: ...
magic_instruct_75k
9,656
Write a Python function to extract and return specific dimensions from a weather dataset stored in a `CfGribDataStore` object. The function should return a dictionary containing the dimensions 'number', 'dataDate', 'dataTime', 'level', and 'values'. The `CfGribDataStore` object has a method `get_dimensions()` that retu...
Here is the Python code to solve the given problem in the markdown block: ```python def get_dataset_dimensions(datastore) -> dict: """ Extracts and returns specific dimensions from a weather dataset stored in a `CfGribDataStore` object. Args: datastore: A `CfGribDataStore` object containing weather...
magic_instruct_75k
9,658
Write a Python function `get_abbreviation(position: str) -> str` that takes a string representing a football player's position and returns the corresponding abbreviation. The positions and their abbreviations are defined in a dictionary. If the input position is not found in the defined choices, the function should ret...
Here is the Python code to solve the given problem in the markdown block: ```python def get_abbreviation(position: str) -> str: """ Returns the abbreviation for a given football player's position. Args: position (str): The full name of the football player's position. Returns: str: The ...
magic_instruct_75k
9,664
Write a Python function to determine if a given binary tree is a valid binary search tree (BST). A binary tree is considered a valid BST if for each node, the values in the left subtree are less than the node's value, and the values in the right subtree are greater than the node's value. Additionally, both the left and...
Here is the Python code to solve the given problem in the markdown block: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_valid_bst(root: TreeNode) -> bool: """ Determines if the given binary tree ...
magic_instruct_75k
9,678
Write a Python function `create_submission_class` that dynamically generates a new class based on a given class name. The new class should have a method `submit` that prints "Submitting <class_name>" when called. The function should return the newly created class. The function signature is: ```python def create_submis...
Here is the Python code to solve the given problem in the markdown block: ```python def create_submission_class(class_name: str) -> type: """ Dynamically creates a new class with the provided class name and a method `submit`. Args: class_name (str): The name of the class to be created. Returns...
magic_instruct_75k
9,687
Write a Python function to find the largest integer whose square is less than or equal to a given non-negative integer `x`. The function should use a binary search algorithm to efficiently determine this integer. The code should start with: ```python def largest_square_root(x: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def largest_square_root(x: int) -> int: """ Find the largest integer whose square is less than or equal to the given non-negative integer `x`. Args: x (int): The non-negative integer for which to find the largest in...
magic_instruct_75k
9,692
Write a Python function to calculate the maximum number of buns that can be purchased with a given amount of money. The function should take the price of a bun and the amount of money available as input and return the maximum number of whole buns that can be purchased. The function should handle cases where the price o...
Here is the Python code to solve the given problem in the markdown block: ```python def max_buns(bun_price: float, money: float) -> int: """ Calculate the maximum number of whole buns that can be purchased with a given amount of money. Args: bun_price (float): The price of a single bun. mon...
magic_instruct_75k
9,694
Write a Python function to count the occurrences of specific words in a given text. The function should be case-insensitive and ignore any punctuation marks. Additionally, the function should be able to handle large text inputs efficiently. The words to be counted are predefined and include "the", "of", "be", "from", a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List import re def count_specific_word_occurrences(text: str, words_to_count: List[str]) -> Dict[str, int]: """ Counts the occurrences of specific words in a given text. The function is case-insensitive...
magic_instruct_75k
9,705
Write a Python function to compare the contents of two text files and produce an output based on the comparison. The function should take two file paths as input and compare their contents. If the contents match, the function should write "Files match" to an output file. If the contents do not match, the function shoul...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def compare_files(file1_path: str, file2_path: str, outfile_path: str) -> None: """ Compare the contents of two text files and write the comparison result to an output file. Args: file1_pat...
magic_instruct_75k
9,713
Write a Python function to process a message payload and extract specific information from it. The message payload is a dictionary containing three key-value pairs: 'arg', 'local_vars', and 'timestamp'. The function should return a formatted string that includes the 'arg', 'local_vars' (formatted as key-value pairs sep...
Here is the Python code to solve the given problem in the markdown block: ```python def process_message(msg_payload: dict) -> str: """ Processes a message payload and extracts specific information from it. Args: msg_payload (dict): A dictionary containing three key-value pairs: 'arg' (s...
magic_instruct_75k
9,715
Write a Python function to count the frequency of each unique word in a given list of tokens and return a dictionary where the keys are the unique words and the values are their respective frequencies. The function should be case-sensitive, meaning that "Apple" and "apple" should be considered different words. The cod...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_word_frequency(tokens: List[str]) -> Dict[str, int]: """ Counts the frequency of each unique word in a given list of tokens. Args: tokens (List[str]): A list of strings where...
magic_instruct_75k
9,720
Write a Python function to determine the dimensions of processed images based on their aspect ratios and a condition applied to the first element of the image's anchor point. The function should take a list of 3D numpy arrays representing the original images and a list of integers representing the aspect ratios of thes...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import List, Tuple def processed_image_dimensions(images: List[np.ndarray], aspect_ratios: List[int]) -> List[Tuple[int, int]]: """ Determine the dimensions of processed images based on their aspe...
magic_instruct_75k
9,749
Write a Python function to validate MongoDB ObjectIDs. MongoDB ObjectIDs are 12-byte identifiers used as primary keys for documents in MongoDB. They consist of a 4-byte timestamp, a 5-byte random value, and a 3-byte incrementing counter, all encoded as hexadecimal strings. Your task is to implement a function `validat...
Here is the Python code to solve the given problem in the markdown block: ```python import re def validate_objectid(objectid: str) -> bool: """ Validates whether the given string is a valid MongoDB ObjectID. MongoDB ObjectIDs are 12-byte identifiers used as primary keys for documents in MongoDB. They ...
magic_instruct_75k
9,750
Write a Python function to calculate the sum of all even numbers in a given list of integers. The function should take a list of integers as input and return the sum of all the even numbers in the list. If the input list is empty or does not contain any even numbers, the function should return 0. The code should start...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_even_numbers(nums: List[int]) -> int: """ Calculate the sum of all even numbers in a given list of integers. Args: nums (List[int]): A list of integers. Returns: int:...
magic_instruct_75k
9,755
Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock at most once, given a list of integers representing the daily stock prices. If it is not possible to make a profit, the function should return 0. The code should start with: ```python from typing import List def...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_profit(prices: List[int]) -> int: """ Calculate the maximum profit that can be obtained by buying and selling a stock at most once. Args: prices (List[int]): A list of integers repre...
magic_instruct_75k
9,770
Write a Python function to find the maximum product of any three integers from a given list of integers. If the input list contains less than three integers, the function should return `None`. The function should be efficient and handle both positive and negative integers. The code should start with: ```python from ty...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def max_product_of_three(nums: List[int]) -> Optional[int]: """ Calculate the maximum product of any three integers from the given list. Args: nums (List[int]): The list of integer...
magic_instruct_75k
9,802
Write a Python function to extract the title and the URL of the stylesheet link from an HTML code snippet. The HTML code snippet will be provided as a string, and you need to parse it to extract the title and the URL of the stylesheet link. The function should return a dictionary containing the title and the URL of the...
Here is the Python code to solve the given problem in the markdown block: ```python import re def extract_title_and_stylesheet(html_code: str) -> dict: """ Extracts the title and the URL of the stylesheet link from an HTML code snippet. Args: html_code (str): The HTML code snippet from which to ex...
magic_instruct_75k
9,804
Write a Python function to calculate the sum of all even Fibonacci numbers up to a given limit. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones. The function should take an integer `limit` as input and return the sum of all even Fibonacci numbers that are less...
Here is the Python code to solve the given problem in the markdown block: ```python def even_fibonacci_sum(limit: int) -> int: """ Calculate the sum of all even Fibonacci numbers up to a given limit. Args: limit (int): The upper bound for the Fibonacci numbers to consider. Returns: int...
magic_instruct_75k
9,811
Write a Python function to calculate the nth Fibonacci number using an iterative approach. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The function should take an integer `n` as input and return the nth Fibonacci number. The fun...
Here is the Python code to solve the given problem in the markdown block: ```python def calculateFibonacci(n: int) -> int: """ Calculate the nth Fibonacci number using an iterative approach. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually...
magic_instruct_75k
9,814
Write a Python function to extract segments of data from a given input string based on a specified delimiter. The input string contains segments of data separated by the "=" delimiter. The function should return a list containing the extracted segments. If the input string is empty, the function should return an empty ...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_segments(input_string: str) -> list: """ Extracts segments of data from a given input string based on the "=" delimiter. Args: input_string (str): A string containing segments of data separated by the "=...
magic_instruct_75k
9,825
Write a Python script to convert a batch of SVG files to PNG format using the Inkscape command-line tool. The script should also create symbolic links for the newly generated PNG files and remove the original SVG files. The script should handle cases where the PNG file already exists and provide appropriate feedback if...
Here is the Python code to solve the given problem in the markdown block: ```python import os import subprocess def convert_svg_to_png(directory: str): """ Convert all SVG files in the specified directory to PNG format using the Inkscape command-line tool. Create symbolic links for the newly generated PNG ...
magic_instruct_75k
9,829
Write a Python function to validate the initialization of a window extractor for a 2D grid. The function should check if the window width is greater than 0 and return an appropriate status message based on the validation results. The function should take the top-left corner position, the bottom-right corner position, t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple, Literal def initialize_window_extractor(top_left: Tuple[int, int], bottom_right: Tuple[int, int], center: Tuple[int, int], padding_type: Literal['zero', 'edge', 'reflect']) -> str: """ Validates the in...
magic_instruct_75k
9,831
Write a Python function to process a list of piecewise linear costs by removing the first element if it exists and returning the modified list. If the list is empty or does not contain any elements, the function should return an empty list. The function should be named `process_piecewise_linear_cost` and should start w...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_piecewise_linear_cost(piecewise_linear_cost: List[int]) -> List[int]: """ Processes a list of piecewise linear costs by removing the first element if it exists and returning the modified list...
magic_instruct_75k
9,838
Write a Python function to parse and extract information from a setup configuration dictionary. The dictionary contains details about a Python package, including its name, version, packages, and whether it is zip-safe. The function should return a formatted string containing the package information in a specific patter...
Here is the Python code to solve the given problem in the markdown block: ```python def format_package_info(setup_info: dict) -> str: """ Formats the package information from a setup configuration dictionary into a specified pattern. Args: setup_info (dict): A dictionary containing details about a ...
magic_instruct_75k
9,861
Write a Python function to implement a custom assertion function that compares two values and prints a message indicating whether they are equal or not. The function should be named `assertEquals` and should take two arguments: the original value and the comparison value. The function should handle both numerical and s...
Here is the Python code to solve the given problem in the markdown block: ```python def assertEquals(original_value, comparison_value): """ Compares two values and prints a message indicating whether they are equal or not. Args: original_value: The original value to be compared. comparison_...
magic_instruct_75k
9,868
Create a Python function to calculate the sales tax for a given product based on its category and the applicable tax rule. The function should be able to handle different tax rates for different product categories. The code should start with: ```python from typing import Dict, Union def calculate_sales_tax(product_cat...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Union def calculate_sales_tax(product_category: str, product_price: float, tax_rules: Dict[str, float]) -> float: """ Calculate the sales tax for a given product based on its category and the applicable...
magic_instruct_75k
9,870
Write a Python function to reorder a list of columns based on a given order. The function should take in a list of columns and a list of indices representing the desired order of the columns. The function should then return the reordered list of columns based on the given indices. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reorder_columns(col_list: List[str], col_order: List[int]) -> List[str]: """ Reorders a list of columns based on a given order of indices. Args: col_list (List[str]): The original list o...
magic_instruct_75k
9,887
Write a Python function to simulate the behavior of the `QoSHandlerFactory` class in the given C++ code snippet. The function should create and return a QoS handler object based on the specified QoS level. The QoS levels are represented by an enum class `QoSLevel`, which includes the values `BestEffort`, `AtLeastOnce`,...
Here is the Python code to solve the given problem in the markdown block: ```python from enum import Enum from typing import Any class QoSLevel(Enum): BestEffort = 1 AtLeastOnce = 2 ExactlyOnce = 3 class QoSHandler: """ Base class for all QoS handlers. """ def deliver_message(self) -> str:...
magic_instruct_75k
9,932
Write a Python function to implement a custom stack data structure. The stack should support the following operations: 1. `push(element)`: Add an element to the top of the stack. 2. `pop()`: Remove and return the element at the top of the stack. If the stack is empty, return `None`. 3. `peek()`: Return the element at t...
Here is the Python code to solve the given problem in the markdown block: ```python class Stack: def __init__(self): """ Initialize an empty stack. """ self.elements = [] def push(self, element): """ Add an element to the top of the stack. Args: ...
magic_instruct_75k
9,938
Write a Python function to convert a given indentation level to the corresponding number of spaces based on a predefined tab size. The function should take an integer representing the indentation level and return an integer representing the equivalent number of spaces. The predefined tab size is four spaces. The code ...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_indentation_to_spaces(indent_level: int) -> int: """ Converts a given indentation level to the corresponding number of spaces based on a predefined tab size. Args: indent_level (int): The indentation lev...
magic_instruct_75k
9,941
Write a Python function to find the longest common subsequence (LCS) of two given strings. The function should return the length of the LCS. The code should start with: ```python def longest_common_subsequence(str1: str, str2: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_common_subsequence(str1: str, str2: str) -> int: """ Calculate the length of the longest common subsequence (LCS) of two given strings. Args: str1 (str): The first string. str2 (str): The second ...
magic_instruct_75k
9,945
Write a Python function to apply a series of image transformations to an input image. Each transformation function is applied sequentially to the image, and the resulting image is passed as input to the next transformation function. The final transformed image is then returned. The function should be defined as follows...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def apply_transformations(image: np.ndarray, transformations: list) -> np.ndarray: """ Apply a series of transformations to the input image. Args: image: numpy.ndarray - The input image as a NumPy ar...
magic_instruct_75k
9,955
Write a Python function to extract specific metadata details from a given dictionary based on a list of criteria. The function should return a new dictionary containing only the key-value pairs that match the criteria specified in the list. If a key in the criteria list is not present in the metadata dictionary, it sho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def extract_metadata(metadata: dict, criteria: List[str]) -> dict: """ Extracts specific metadata details from a given dictionary based on a list of criteria. Args: metadata (dict): A dictio...
magic_instruct_75k
9,958
Create a Python function to determine the maximum sum of a subarray within a given array. The function should efficiently compute the maximum sum using Kadane's algorithm. The code should start with: ```python from typing import List def max_subarray_sum(arr: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_subarray_sum(arr: List[int]) -> int: """ Calculate the maximum sum of a subarray within the given array using Kadane's algorithm. Args: arr (List[int]): The input array of integers. ...
magic_instruct_75k
9,960
Write a Python function to count the frequency of each alphabetic character in a given string and return the characters along with their frequencies in descending order. The function should ignore any non-alphabetic characters and treat uppercase and lowercase letters as the same character. The code should start with:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def character_frequency(s: str) -> Dict[str, int]: """ Counts the frequency of each alphabetic character in the given string and returns the characters along with their frequencies in descending orde...
magic_instruct_75k
10,034
Write a Python function to determine if a given positive integer `n` is a power of 3. A number is considered a power of 3 if it can be expressed as \(3^k\) for some non-negative integer `k`. The function should return `True` if `n` is a power of 3, and `False` otherwise. The code should start with: ```python def is_po...
Here is the Python code to solve the given problem in the markdown block: ```python def is_power_of_three(n: int) -> bool: """ Determine if a given positive integer `n` is a power of 3. Args: n (int): The positive integer to check. Returns: bool: True if `n` is a power of 3, False othe...
magic_instruct_75k
10,046
Write a Python function to generate a unique filename for saving a neural network model at each epoch during training. The filename should follow a specific format and include the epoch number. The filename format should be: "vt-XXX.pth", where "XXX" represents the epoch number padded with leading zeros to make it a 3-...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_model_filename(epoch: int) -> str: """ Generates a unique filename for saving a neural network model at each epoch. The filename follows the format "vt-XXX.pth", where "XXX" is the epoch number padded with lead...
magic_instruct_75k
10,056
Write a Python function to find the longest common subsequence (LCS) between two given strings. The function should return the length of the LCS. The code should start with: ```python from typing import List def longest_common_subsequence(str1: str, str2: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def longest_common_subsequence(str1: str, str2: str) -> int: """ Calculate the length of the longest common subsequence (LCS) between two strings. Args: str1 (str): The first string. ...
magic_instruct_75k
10,069
Write a Python function to parse and extract specific information from a Git LFS (Large File Storage) pointer file. The function should take a string representing the content of a Git LFS pointer file and return a dictionary containing the following information: 1. Repository name 2. Version URL 3. SHA256 hash 4. File ...
Here is the Python code to solve the given problem in the markdown block: ```python def parse_git_lfs_pointer(pointer_file: str) -> dict: """ Parses and extracts specific information from a Git LFS pointer file. Args: pointer_file (str): The content of a Git LFS pointer file. Returns: ...
magic_instruct_75k
10,075
Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock at most once, given a list of integers representing the daily stock prices. If it is not possible to make any profit, the function should return 0. The code should start with: ```python from typing import List d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_profit(prices: List[int]) -> int: """ Calculate the maximum profit that can be obtained by buying and selling a stock at most once. Args: prices (List[int]): A list of integers where...