target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
def max_nesting_depth(s: str) -> int:
"""
Calculate the maximum nesting depth of parentheses in the string.
Args:
s (str): The input string containing round brackets.
Returns:
int: The maximum depth of nested parentheses.
"""
current_depth = 0
max_depth = 0
for char in s:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context:\nDevelop a function that evaluates the level of nesting in a given string based on the use of round brackets (parentheses). This is essential in understanding the depth of nested expressions in computational languages.\n\n#### Problem Stat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6800,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context:\nDevelop a function that evaluates the level of nesting in a given string based on the use of round brackets (parentheses). This is essential in understanding the depth of nested expressions in computatio... |
import heapq
def find_weighted_shortest_path(graph, start, end):
if start not in graph or end not in graph:
return None
distances = {node: float('infinity') for node in graph}
distances[start] = 0
predecessors = {node: None for node in graph}
priority_queue = []
heapq.heappush(priori... | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem Summary:\nYou need to implement a function that finds the shortest path in a weighted graph between two given nodes. Unlike the provided code snippets which handle unweighted graphs, you will need to account for varying path costs.\n\n### Detailed Description:\nWrite a funct... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6801,
"level": 1,
"question": "### Problem Summary:\nYou need to implement a function that finds the shortest path in a weighted graph between two given nodes. Unlike the provided code snippets which handle unweighted graphs, you will need to account for varying path costs.\n\n### D... |
def is_balanced_parentheses(s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping.values():
stack.append(char)
elif char in mapping:
if not stack or stack.pop() != mapping[char]:
return False
return not stack | simplelr_Evol | [
{
"content": "Question:\n### Can You Balance the Parentheses?\n\nGiven a string composed of only '(', ')', '{', '}', '[' and ']', your task is to determine if the given string is a balanced parentheses expression.\n\nA string is considered balanced if:\n1. Open brackets must be closed by the same type of bracke... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6802,
"level": 1,
"question": "### Can You Balance the Parentheses?\n\nGiven a string composed of only '(', ')', '{', '}', '[' and ']', your task is to determine if the given string is a balanced parentheses expression.\n\nA string is considered balanced if:\n1. Open brackets must b... |
def find_unique_character(s):
counts = {}
for char in s:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
for char in s:
if counts[char] == 1:
return char
return '_' | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the unique character in a string that appears only once. If there is no such character, return an underscore ('_').\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6803,
"level": 1,
"question": "Write a function to find the unique character in a string that appears only once. If there is no such character, return an underscore ('_').",
"split": "train"
} |
def sum_pairs(arr, sum):
seen = set()
for num in arr:
complement = sum - num
if complement in seen:
return (complement, num)
seen.add(num)
return None | simplelr_Apps | [
{
"content": "Question:\n## Task\n\nYou are required to write a function `sum_pairs()` that will take an array of integers `arr` and a single integer `sum`. The function should find the first pair of numbers in the array that adds up to the given `sum` and returns that pair as a tuple `(a, b)` where `a` and `b`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6804,
"level": 1,
"question": "## Task\n\nYou are required to write a function `sum_pairs()` that will take an array of integers `arr` and a single integer `sum`. The function should find the first pair of numbers in the array that adds up to the given `sum` and returns that pair as... |
def longestWorkingDays(days):
max_length = 0
max_start = 0
current_length = 0
current_start = 0
for i in range(len(days)):
if days[i] in {1, 2, 3, 4, 5}:
if current_length == 0:
current_start = i
current_length += 1
if current_length > max... | simplelr_Taco | [
{
"content": "Question:\nGiven an integer array representing the days of the week (0 for Sunday, 1 for Monday, ..., 6 for Saturday), write a function to find the longest sequence of consecutive days (not wrapping around) that are all working days (Monday to Friday). If there are multiple sequences with the same... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6805,
"level": 1,
"question": "Given an integer array representing the days of the week (0 for Sunday, 1 for Monday, ..., 6 for Saturday), write a function to find the longest sequence of consecutive days (not wrapping around) that are all working days (Monday to Friday). If there a... |
def title_case(s: str) -> str:
words = s.split()
processed = [word[0].upper() + word[1:].lower() for word in words]
return ' '.join(processed) | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are developing a text editor that allows users to format text by capitalizing the first letter of each word. Your task is to implement a function that performs this formatting.\n\n### Problem Statement\nWrite a function called `title_case(s: str) -> str` that takes a s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6806,
"level": 1,
"question": "### Scenario\nYou are developing a text editor that allows users to format text by capitalizing the first letter of each word. Your task is to implement a function that performs this formatting.\n\n### Problem Statement\nWrite a function called `title_... |
import string
def word_frequency(filename):
try:
with open(filename, 'r') as file:
text = file.read().lower()
# Remove punctuation
translator = str.maketrans('', '', string.punctuation)
text_no_punct = text.translate(translator)
words = text_no_pu... | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python script to analyze a text file for word frequency? For example, if the file contains the sentence \"Hello world hello\", the output should be a dictionary where the keys are words and the values are their frequencies: `{'hello': 2, 'world': 1}`. The script s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6807,
"level": 1,
"question": "Can you help me with a Python script to analyze a text file for word frequency? For example, if the file contains the sentence \"Hello world hello\", the output should be a dictionary where the keys are words and the values are their frequencies: `{'he... |
def unique_word_count(s):
return len(set(s.split())) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the total number of unique words in a given string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6808,
"level": 1,
"question": "Write a function to calculate the total number of unique words in a given string.",
"split": "train"
} |
def max_subarray_sum(nums):
if not nums:
return 0 # Assuming the function can handle empty arrays by returning 0
max_ending_here = max_so_far = nums[0]
for num in nums[1:]:
max_ending_here = max(num, max_ending_here + num)
max_so_far = max(max_so_far, max_ending_here)
return max... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A contiguous subarray is a subarray that appears within the original array with sequences of elements in the same order. You may assume numbers in `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6809,
"level": 1,
"question": "Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A contiguous subarray is a subarray that appears within the original array with sequences of elements in the same... |
from typing import List
def has_pair_with_sum(arr: List[int], k: int) -> bool:
seen = set()
for num in arr:
complement = k - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Code_Contests | [
{
"content": "Question:\nYou are given a list of integers `arr` and a single integer `k`. Your task is to determine if there exists a pair of distinct integers in the list such that their sum is equal to `k`. Note that the same elements of the list cannot be reused to form different pairs.\n\nWrite a function t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6810,
"level": 1,
"question": "You are given a list of integers `arr` and a single integer `k`. Your task is to determine if there exists a pair of distinct integers in the list such that their sum is equal to `k`. Note that the same elements of the list cannot be reused to form dif... |
def element_wise_min(v1, v2):
return [min(a, b) for a, b in zip(v1, v2)]
# Example usage
v1 = [1, 2, 3]
v2 = [3, 2, 1]
print(element_wise_min(v1, v2)) # Output: [1, 2, 1] | simplelr_Filter | [
{
"content": "Question:\nI have two small vectors, which I'll call `v1` and `v2`, each with three elements. I'd like to create a function that takes these vectors, and returns a new vector `v3` whose elements are the element-wise minimum of `v1` and `v2`. \n\nFor example, if `v1 = [1, 2, 3]` and `v2 = [3, 2, 1]... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6811,
"level": 1,
"question": "I have two small vectors, which I'll call `v1` and `v2`, each with three elements. I'd like to create a function that takes these vectors, and returns a new vector `v3` whose elements are the element-wise minimum of `v1` and `v2`. \n\nFor example, if `... |
def word_deletion_tool(document, M, targets):
words = document.split()
target_set = set(targets)
filtered_words = [word for word in words if word not in target_set]
return ' '.join(filtered_words) | simplelr_Code_Contests | [
{
"content": "Question:\nA software company is developing a new text editor, and one of the features they want to implement is the \"Word Deletion Tool\". This tool allows users to mark and delete specific words from a document. During the initial development, they need to create a function that simulates this ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6812,
"level": 1,
"question": "A software company is developing a new text editor, and one of the features they want to implement is the \"Word Deletion Tool\". This tool allows users to mark and delete specific words from a document. During the initial development, they need to cre... |
def rob(nums: list[int]) -> int:
if not nums:
return 0
n = len(nums)
if n == 1:
return nums[0]
prev_prev = 0
prev = nums[0]
for i in range(1, n):
current = max(prev, prev_prev + nums[i])
prev_prev, prev = prev, current
return prev | simplelr_Evol | [
{
"content": "Question:\nGiven an array of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. As a condition, you cannot rob two adjacent houses because that would trigger the alarm system.\n\nFor example, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6813,
"level": 1,
"question": "Given an array of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. As a condition, you cannot rob two adjacent houses because that would trigger... |
def sum_up_to(n):
if n < 1:
return 0
return n * (n + 1) // 2 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that returns the result of adding all numbers from 1 to the given number 'n'.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6814,
"level": 1,
"question": "Create a function that returns the result of adding all numbers from 1 to the given number 'n'.",
"split": "train"
} |
from typing import List
def find_insertion_point(sorted_array: List[int], target: int) -> int:
low = 0
high = len(sorted_array)
while low < high:
mid = (low + high) // 2
if sorted_array[mid] < target:
low = mid + 1
else:
high = mid
return low | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are part of a development team working on a real-time data processing system where maintaining a sorted list of elements is crucial. One of the core functionalities you need to implement involves efficiently finding the correct position to insert new elements to keep t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6815,
"level": 1,
"question": "### Scenario\nYou are part of a development team working on a real-time data processing system where maintaining a sorted list of elements is crucial. One of the core functionalities you need to implement involves efficiently finding the correct positi... |
def extract_sublist_with_slice(sequence: list[int], slice_params: dict[str, int | None]) -> list[int]:
start = slice_params['start']
stop = slice_params['stop']
# Handle the step parameter, defaulting to 1 if None
if slice_params['step'] is None:
step = 1
else:
step = slice_para... | simplelr_Docs | [
{
"content": "Question:\n**Title**: Working with the `PySlice` Module\n\n**Objective**: Assess the students' ability to utilize and manipulate slice objects in Python using the `PySlice` module from python310.\n\n**Task Description**:\n\nYou are given a task to implement a function `extract_sublist_with_slice` ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6816,
"level": 1,
"question": "**Title**: Working with the `PySlice` Module\n\n**Objective**: Assess the students' ability to utilize and manipulate slice objects in Python using the `PySlice` module from python310.\n\n**Task Description**:\n\nYou are given a task to implement a fun... |
import numpy as np
from sklearn.metrics.pairwise import pairwise_kernels
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
def compute_custom_kernel_and_train_svm(X_train, X_test, y_train, y_test, kernel_type):
# Mapping kernel_type to corresponding metric and parameters
metric_map = {
... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nDemonstrate your understanding of scikit-learn's `metrics.pairwise` submodule by implementing a function that computes pairwise kernels between two datasets using a specified kernel function and then uses this custom kernel to train a Support Vector Machine (SVM).\n\n##... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6817,
"level": 1,
"question": "#### Objective:\nDemonstrate your understanding of scikit-learn's `metrics.pairwise` submodule by implementing a function that computes pairwise kernels between two datasets using a specified kernel function and then uses this custom kernel to train a ... |
from typing import List
def cocktail_shaker_sort(arr: List[int]) -> List[int]:
n = len(arr)
start = 0
end = n - 1
swapped = True
while swapped:
swapped = False
# Forward pass: move larger elements to the end
for i in range(start, end):
if arr[i] < arr[i + 1]:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Implement Cocktail Shaker Sort\n\n**Context**: You are a software engineer tasked with developing a sorting feature for a budgeting application that ranks expenses in a list from highest to lowest. Given that users typically manage a relatively small list of expenses, your... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6818,
"level": 1,
"question": "### Question: Implement Cocktail Shaker Sort\n\n**Context**: You are a software engineer tasked with developing a sorting feature for a budgeting application that ranks expenses in a list from highest to lowest. Given that users typically manage a rela... |
from typing import List
def min_jumps(arr: List[int]) -> int:
n = len(arr)
if n <= 1:
return 0
current_end = 0
farthest = 0
jumps = 0
for i in range(n):
if i > current_end:
return -1 # Cannot reach, but as per problem statement, it's always reachable
farthes... | simplelr_Algorithm | [
{
"content": "Question:\n### Minimum Jumps to Reach End of Array\n\nYou are given an array of non-negative integers where each element represents the maximum number of steps you can take forward from that position. Your task is to find the minimum number of jumps required to reach the end of the array from the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6819,
"level": 1,
"question": "### Minimum Jumps to Reach End of Array\n\nYou are given an array of non-negative integers where each element represents the maximum number of steps you can take forward from that position. Your task is to find the minimum number of jumps required to r... |
def create_array(n):
return list(range(1, n + 1)) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in an integer n and returns an array of size n filled with values from 1 to n. How can this be done in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6820,
"level": 1,
"question": "Create a function that takes in an integer n and returns an array of size n filled with values from 1 to n. How can this be done in Python?",
"split": "train"
} |
def int_to_roman(num: int) -> str:
"""
Converts an integer between 1 and 3999 into its Roman numeral equivalent.
:param num: An integer to convert.
:return: The Roman numeral representation of the input integer.
"""
roman_numerals = [
(1000, 'M'),
(900, 'CM'),
(500, 'D'),... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Context\nYou are working on a historical education software that teaches students about Roman numerals. One of the features required is the ability to convert integer numbers into their Roman numeral equivalents. A Roman numeral is represented by a combination of the following symb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6821,
"level": 1,
"question": "#### Context\nYou are working on a historical education software that teaches students about Roman numerals. One of the features required is the ability to convert integer numbers into their Roman numeral equivalents. A Roman numeral is represented by ... |
def is_isomorphic(s1, s2):
if len(s1) != len(s2):
return False
map_s1_s2 = {}
map_s2_s1 = {}
for c1, c2 in zip(s1, s2):
if c1 in map_s1_s2:
if map_s1_s2[c1] != c2:
return False
else:
if c2 in map_s2_s1:
return Fals... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function to check if two strings are isomorphic. Two strings are isomorphic if the characters in string1 can be replaced to get string2, while maintaining the relative order of the characters. No two characters may map to the same character, but a character may map to it... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6822,
"level": 1,
"question": "Create a Python function to check if two strings are isomorphic. Two strings are isomorphic if the characters in string1 can be replaced to get string2, while maintaining the relative order of the characters. No two characters may map to the same chara... |
def batch_update(arr, updates):
n = len(arr)
if n == 0:
return []
# Initialize the difference array
diff = [0] * n
for update in updates:
start, end, val = update
diff[start] += val
if end + 1 < n:
diff[end + 1] -= val
# Compute the pref... | simplelr_Filter | [
{
"content": "Question:\nI have an array of integers, and I want to perform a batch update operation on it. I have a list of update operations, each of which specifies a start index, an end index, and a value to add to each element in the array from the start index to the end index, inclusive. After performing ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6823,
"level": 1,
"question": "I have an array of integers, and I want to perform a batch update operation on it. I have a list of update operations, each of which specifies a start index, an end index, and a value to add to each element in the array from the start index to the end ... |
import torch
def configure_and_multiply(
enable_tf32: bool,
enable_fp16_reduced_precision: bool,
enable_bf16_reduced_precision: bool,
cufft_cache_size: int,
device_id: int,
matrix_a: torch.Tensor,
matrix_b: torch.Tensor
) -> torch.Tensor:
"""
Configures CUDA backend settings and per... | simplelr_Docs | [
{
"content": "Question:\nManaging CUDA Backend Configurations\n\n**Objective**: This problem assesses your understanding of PyTorch's CUDA backend functionalities, particularly focused on mixed precision settings and performing matrix multiplications on GPUs.\n\n#### Problem Description:\nYou are tasked with im... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6824,
"level": 1,
"question": "Managing CUDA Backend Configurations\n\n**Objective**: This problem assesses your understanding of PyTorch's CUDA backend functionalities, particularly focused on mixed precision settings and performing matrix multiplications on GPUs.\n\n#### Problem D... |
def bubble_sort(nums):
nums_copy = nums.copy()
n = len(nums_copy)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if nums_copy[j] > nums_copy[j + 1]:
# Swap elements
nums_copy[j], nums_copy[j + 1] = nums_copy[j + 1], nums_copy[j]
... | simplelr_Filter | [
{
"content": "Question:\nWhat is the most efficient way to sort a list of numbers in Python without using built-in functions like `sort()`? Can you provide an example using a simple sorting algorithm?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6825,
"level": 1,
"question": "What is the most efficient way to sort a list of numbers in Python without using built-in functions like `sort()`? Can you provide an example using a simple sorting algorithm?",
"split": "train"
} |
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for _ in range(2, n + 1):
next_fib = a + b
a = b
b = next_fib
return b | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the Fibonacci number at a given position 'n'. The position 'n' is a non-negative integer. The function should return the Fibonacci number at that position.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6826,
"level": 1,
"question": "Write a function to find the Fibonacci number at a given position 'n'. The position 'n' is a non-negative integer. The function should return the Fibonacci number at that position.",
"split": "train"
} |
def move_tokens(board_dimensions, initial_positions, moves):
rows, cols = board_dimensions
current_positions = [list(pos) for pos in initial_positions]
direction_map = {
'up': (-1, 0),
'down': (1, 0),
'left': (0, -1),
'right': (0, 1)
}
for move in moves:
... | simplelr_Package | [
{
"content": "Question:\nYou are developing a software simulation of a simple 2D game board where players can place and move tokens. The board is represented as a grid of cells, each identified by its coordinates (row, column). Tokens can only be moved horizontally or vertically to adjacent cells, not diagonall... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6827,
"level": 1,
"question": "You are developing a software simulation of a simple 2D game board where players can place and move tokens. The board is represented as a grid of cells, each identified by its coordinates (row, column). Tokens can only be moved horizontally or vertical... |
def can_place_flowers(flowerbed, k):
n = len(flowerbed)
runs = []
i = 0
# Identify all runs of consecutive 0s
while i < n:
if flowerbed[i] == 0:
start = i
while i < n and flowerbed[i] == 0:
i += 1
end = i - 1
runs.append((s... | simplelr_Code_Contests | [
{
"content": "Question:\nYou have been assigned a role as a gardener to maintain a prestigious garden's flowerbed. The flowerbed is represented by a list of integers, where each element corresponds to a section of the flowerbed and is either 0 (empty) or 1 (occupied by a flower). You have also been given a numb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6828,
"level": 1,
"question": "You have been assigned a role as a gardener to maintain a prestigious garden's flowerbed. The flowerbed is represented by a list of integers, where each element corresponds to a section of the flowerbed and is either 0 (empty) or 1 (occupied by a flowe... |
def two_sum(array, target):
seen = {}
for i, num in enumerate(array):
complement = target - num
if complement in seen:
return (seen[complement], i)
seen[num] = i
return None | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\n\n#### Scenario\nIn a contest of competitive coding, you're tasked with helping a team develop an efficient function to solve a classic problem: the Two Sum Problem. This problem involves finding two numbers in an array that add up to a given target sum. You are to design ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6829,
"level": 1,
"question": "### Question\n\n#### Scenario\nIn a contest of competitive coding, you're tasked with helping a team develop an efficient function to solve a classic problem: the Two Sum Problem. This problem involves finding two numbers in an array that add up to a g... |
from collections import Counter
def first_non_repeating_char(s):
count = Counter(s)
for char in s:
if count[char] == 1:
return char
return ""
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes in a string and returns the first non-repeating character. If there’s no non-repeating character, the function should return an empty string - `firstNonRepeatingChar()` (`first_non_repeating_char()` for Python).\n\nA few examples:\n\n```\nfirstNonRepeatingCha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6830,
"level": 1,
"question": "Write a function that takes in a string and returns the first non-repeating character. If there’s no non-repeating character, the function should return an empty string - `firstNonRepeatingChar()` (`first_non_repeating_char()` for Python).\n\nA few exa... |
def longest_increasing_subsequence_with_constraint(arr, k):
n = len(arr)
if n == 0:
return 0
dp = [1] * n
s = [arr[i] for i in range(n)]
max_len = 1
for i in range(n):
for j in range(i):
if arr[j] < arr[i] and s[j] >= (arr[i] - k):
if dp[j] +... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` and an integer `k`. A **subsequence** is a sequence derived from the array by deleting some or no elements without changing the order of the remaining elements. Return the length of the longest **increasing subsequence** of `arr` such that the di... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6831,
"level": 1,
"question": "You are given an array of integers `arr` and an integer `k`. A **subsequence** is a sequence derived from the array by deleting some or no elements without changing the order of the remaining elements. Return the length of the longest **increasing subs... |
def fizzbuzz_list(numbers):
result = []
for n in numbers:
s = ''
if n % 3 == 0:
s += 'Fizz'
if n % 5 == 0:
s += 'Buzz'
if s:
result.append(s)
else:
result.append(str(n))
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to generate a list of strings based on a specific pattern. For each number `n` in the given list, the function should produce 'Fizz' if `n` is divisible by 3, 'Buzz' if `n` is divisible by 5, 'FizzBuzz' if `n` is divisible by both 3 and 5, and the number itself a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6832,
"level": 1,
"question": "Write a Python function to generate a list of strings based on a specific pattern. For each number `n` in the given list, the function should produce 'Fizz' if `n` is divisible by 3, 'Buzz' if `n` is divisible by 5, 'FizzBuzz' if `n` is divisible by bo... |
def rle_compress(text: str) -> str:
if not text:
return ""
result = []
prev = text[0]
count = 1
for c in text[1:]:
if c == prev:
count += 1
else:
result.append(prev + str(count))
prev = c
count = 1
result.append(prev + str(c... | simplelr_Algorithm | [
{
"content": "Question:\n### Compressing Large Text Files Challenge\n\n#### Background:\nYou are working on an application that deals with storing and transmitting large text files. To optimize storage and speed up transmission, you decide to implement a function that compresses text using Run-Length Encoding (... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6833,
"level": 1,
"question": "### Compressing Large Text Files Challenge\n\n#### Background:\nYou are working on an application that deals with storing and transmitting large text files. To optimize storage and speed up transmission, you decide to implement a function that compress... |
from collections import Counter
def count_frequencies(lst):
return dict(Counter(lst)) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that can determine the frequency of each unique value in a list and returns the results as a dictionary. The keys in the dictionary should be the unique values from the list, and the values should be the counts of how often each value appears. Optimize the funct... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6834,
"level": 1,
"question": "Create a Python function that can determine the frequency of each unique value in a list and returns the results as a dictionary. The keys in the dictionary should be the unique values from the list, and the values should be the counts of how often eac... |
def increment_by_index(lst):
return [x + i for i, x in enumerate(lst)] | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns a list with each integer incremented by its index in the original list. The function should handle an empty list as input and return an empty list in such cases.\n\n```python\nincrement_by_index([]) # => []\nincrement_by_index(... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6835,
"level": 1,
"question": "Write a function that takes a list of integers and returns a list with each integer incremented by its index in the original list. The function should handle an empty list as input and return an empty list in such cases.\n\n```python\nincrement_by_inde... |
def longest_common_prefix(strs):
if not strs:
return ""
shortest = min(strs, key=len)
for i in range(len(shortest)):
char = shortest[i]
for s in strs:
if s[i] != char:
return shortest[:i]
return shortest | simplelr_Filter | [
{
"content": "Question:\nGiven a list of strings, write a Python function to find the length of the longest common prefix among all strings in the list. For instance, given the strings \"flower\", \"flow\", \"flight\", the longest common prefix is \"fl\". If there is no common prefix, return an empty string. Ho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6836,
"level": 1,
"question": "Given a list of strings, write a Python function to find the length of the longest common prefix among all strings in the list. For instance, given the strings \"flower\", \"flow\", \"flight\", the longest common prefix is \"fl\". If there is no common... |
import re
def strings_to_dict(string_list):
result = {}
seen = set()
for s in string_list:
if re.fullmatch(r'^[a-zA-Z]+$', s):
if s not in seen:
seen.add(s)
result[s] = len(s)
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of strings as input and returns a dictionary with the strings as keys and their lengths as values. Additionally, the function should ignore any strings that contain numbers or special characters. The function should also handle cases where the i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6837,
"level": 1,
"question": "Write a Python function that takes a list of strings as input and returns a dictionary with the strings as keys and their lengths as values. Additionally, the function should ignore any strings that contain numbers or special characters. The function s... |
def is_prime_number(n: int) -> str:
if n < 2:
raise ValueError("Number must be greater than 0")
if n == 2:
return "Prime"
if n % 2 == 0:
return "Not Prime"
max_divisor = int(n ** 0.5) + 1
for i in range(3, max_divisor, 2):
if n % i == 0:
return "Not Prime"... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question\n\n#### Objective\nWrite a function `is_prime_number` to determine whether a given number is a prime number. A number is considered prime if it is greater than 1 and has no divisors other than 1 and itself.\n\n#### Function Signature\n```python\ndef is_prime_number(n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6838,
"level": 1,
"question": "### Coding Question\n\n#### Objective\nWrite a function `is_prime_number` to determine whether a given number is a prime number. A number is considered prime if it is greater than 1 and has no divisors other than 1 and itself.\n\n#### Function Signatur... |
from collections import deque
def walls_and_gates(rooms):
if not rooms or not rooms[0]:
return
m, n = len(rooms), len(rooms[0])
q = deque()
for i in range(m):
for j in range(n):
if rooms[i][j] == 0:
q.append((i, j))
directions = [(-1, 0), (... | simplelr_Data_Structure | [
{
"content": "Question:\nDistance to Nearest Gate\n\n#### Objective\nGiven a 2D grid initialized with `-1`, `0`, and `INF` values:\n\n* `-1` represents a wall or an obstacle that cannot be passed.\n* `0` represents a gate.\n* `INF` (2^31 - 1) represents an empty room.\n\nYou need to fill each empty room with th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6839,
"level": 1,
"question": "Distance to Nearest Gate\n\n#### Objective\nGiven a 2D grid initialized with `-1`, `0`, and `INF` values:\n\n* `-1` represents a wall or an obstacle that cannot be passed.\n* `0` represents a gate.\n* `INF` (2^31 - 1) represents an empty room.\n\nYou n... |
def trap(height):
if not height:
return 0
n = len(height)
left = 0
right = n - 1
max_left = 0
max_right = 0
total = 0
while left <= right:
if height[left] <= height[right]:
if height[left] > max_left:
max_left = height[left]
else:
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a sequence of integers representing the heights of buildings in a skyline. Your task is to determine the total amount of water that can be trapped between the buildings after it rains.\n\nThe water trapped is defined as the unit of water that can be accumulated between two... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6840,
"level": 1,
"question": "You are given a sequence of integers representing the heights of buildings in a skyline. Your task is to determine the total amount of water that can be trapped between the buildings after it rains.\n\nThe water trapped is defined as the unit of water ... |
from typing import List
def two_sum(nums: List[int], target: int) -> List[int]:
seen = {} # Dictionary to store the numbers we've seen and their indices
for index, num in enumerate(nums):
complement = target - num # Calculate the complement
if complement in seen: # Check if complement exists... | simplelr_Evol | [
{
"content": "Question:\nGiven an array of integers, write a function that returns the indices of the two numbers such that they add up to a specific target. You may assume that each input will have exactly one solution, and you may not use the same element twice. Your solution should have a linear runtime comp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6841,
"level": 1,
"question": "Given an array of integers, write a function that returns the indices of the two numbers such that they add up to a specific target. You may assume that each input will have exactly one solution, and you may not use the same element twice. Your solutio... |
def validate_integer_conversion(num: int) -> bool:
if num == 0:
byte_length = 1
else:
byte_length = (num.bit_length() + 7) // 8 # Equivalent to ceiling division by 8
# Check big-endian conversion
bytes_big = num.to_bytes(byte_length, byteorder='big')
num_from_big = int.from_byt... | simplelr_Data_Structure | [
{
"content": "Question:\nGiven the understanding of byte-integer conversion and endianness, implement a function that takes an integer, converts it to its byte representation, and then converts it back to ensure correctness. This question requires consideration of both big-endian and little-endian formats.\n\n#... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6842,
"level": 1,
"question": "Given the understanding of byte-integer conversion and endianness, implement a function that takes an integer, converts it to its byte representation, and then converts it back to ensure correctness. This question requires consideration of both big-end... |
from collections import Counter
def count_repeated_characters(sentence):
counts = Counter(sentence)
return {char: count for char, count in counts.items() if count > 1} | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the repeated characters in a sentence. The function should accept one parameter and return a dictionary containing characters and their counts. If no repeated characters are found, return an empty dictionary.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6843,
"level": 1,
"question": "Write a python function to calculate the repeated characters in a sentence. The function should accept one parameter and return a dictionary containing characters and their counts. If no repeated characters are found, return an empty dictionary.",
"s... |
def sort_descending(nums):
n = len(nums)
for i in range(n):
swapped = False
for j in range(n - i - 1):
if nums[j] < nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
swapped = True
if not swapped:
break
return nums | simplelr_Filter | [
{
"content": "Question:\nPropose an algorithm in Python for sorting a given list of numbers in descending order, without using any built-in sorting functions or libraries.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6844,
"level": 1,
"question": "Propose an algorithm in Python for sorting a given list of numbers in descending order, without using any built-in sorting functions or libraries.",
"split": "train"
} |
from collections import Counter
import heapq
def rearrange_string(s):
counts = Counter(s)
n = len(s)
if n == 0:
return ""
max_freq = max(counts.values())
if max_freq > (n + 1) // 2:
return ""
# Create a max heap using negative counts
heap = [(-v, k) for k, v in cou... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` containing lowercase and uppercase characters. You need to rearrange the characters so that no two adjacent characters are the same. If it is not possible to do so, return an empty string. Otherwise, return the rearranged string.\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6845,
"level": 1,
"question": "You are given a string `s` containing lowercase and uppercase characters. You need to rearrange the characters so that no two adjacent characters are the same. If it is not possible to do so, return an empty string. Otherwise, return the rearranged str... |
def find_max_recursive(lst):
if len(lst) == 1:
return lst[0]
else:
return max(lst[0], find_max_recursive(lst[1:]))
# Example usage
numbers = [5, 3, 7, 1]
print(find_max_recursive(numbers)) # Output: 7 | simplelr_Filter | [
{
"content": "Question:\nWrite a python code to find the maximum value in a given list of numbers using a recursive approach.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6846,
"level": 1,
"question": "Write a python code to find the maximum value in a given list of numbers using a recursive approach.",
"split": "train"
} |
import functools
@functools.lru_cache(maxsize=None)
def minReplacements(n):
if n == 1:
return 0
elif n % 2 == 0:
return 1 + minReplacements(n // 2)
else:
return 1 + min(minReplacements(n - 1), minReplacements(n + 1)) | simplelr_Apps | [
{
"content": "Question:\nGiven an integer `n`, determine the minimum number of replacements needed for `n` to become `1`. You can perform the following operations on `n`:\n\n1. If `n` is even, replace `n` with `n / 2`.\n2. If `n` is odd, you can either replace `n` with `n + 1` or `n - 1`.\n\nWrite a function `m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6847,
"level": 1,
"question": "Given an integer `n`, determine the minimum number of replacements needed for `n` to become `1`. You can perform the following operations on `n`:\n\n1. If `n` is even, replace `n` with `n / 2`.\n2. If `n` is odd, you can either replace `n` with `n + 1`... |
def are_anagrams(str1, str2):
if len(str1) != len(str2):
return False
return sorted(str1.lower()) == sorted(str2.lower()) | simplelr_Filter | [
{
"content": "Question:\nHow can I check if two strings are anagrams in Python? Could you provide a simple method to do this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6848,
"level": 1,
"question": "How can I check if two strings are anagrams in Python? Could you provide a simple method to do this?",
"split": "train"
} |
def max_of_three(a, b, c):
if a > b:
max_val = a
else:
max_val = b
if c > max_val:
max_val = c
return max_val
# Example usage
print(max_of_three(5, 12, 7)) # Output: 12 | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to return the maximum of three integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6849,
"level": 1,
"question": "Write a function to return the maximum of three integers.",
"split": "train"
} |
def min_path_sum(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
prev_row = [0] * n
prev_row[0] = grid[0][0]
for j in range(1, n):
prev_row[j] = prev_row[j-1] + grid[0][j]
for i in range(1, m):
current_row = [0] * n
current_row[0] = prev... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to determine the minimum path sum in a grid from the top left to the bottom right. You can only move right or down at any point in time. The grid consists of non-negative integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6850,
"level": 1,
"question": "Write a python function to determine the minimum path sum in a grid from the top left to the bottom right. You can only move right or down at any point in time. The grid consists of non-negative integers.",
"split": "train"
} |
def filter_less_than(lst, x):
result = []
for num in lst:
if num < x:
result.append(num)
return result
# Example usage:
lst = [10, 25, 17, 3, 8, 30, 2, 15]
x = 20
print(filter_less_than(lst, x)) # Output: [10, 17, 3, 8, 2, 15] | simplelr_Evol | [
{
"content": "Question:\nDesign a function that takes an array of integers and an integer 'x' as inputs, and returns an array containing only the integers from the input array that are less than 'x'. The returned array should maintain the order of the original array.\nlst = [10, 25, 17, 3, 8, 30, 2, 15]\nx = 20... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6851,
"level": 1,
"question": "Design a function that takes an array of integers and an integer 'x' as inputs, and returns an array containing only the integers from the input array that are less than 'x'. The returned array should maintain the order of the original array.\nlst = [1... |
def modify_values(dictionary, defaults, path=None):
if path is None:
path = []
result = dictionary.copy()
for key, value in defaults.items():
current_path = path + [key]
if isinstance(value, dict):
if key in result and isinstance(result[key], dict):
result... | simplelr_Filter | [
{
"content": "Question:\ndef modify_values(dictionary, defaults, path=None):\n if path is None:\n path = []\n result = dictionary.copy()\n for key, value in defaults.items():\n current_path = path + [key]\n if isinstance(value, dict):\n if key in result: \n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6852,
"level": 1,
"question": "def modify_values(dictionary, defaults, path=None):\n if path is None:\n path = []\n result = dictionary.copy()\n for key, value in defaults.items():\n current_path = path + [key]\n if isinstance(value, dict):\n ... |
def can_form_polygon(nums):
if len(nums) < 3:
return False
nums.sort()
sum_so_far = nums[0] + nums[1]
for i in range(2, len(nums)):
if sum_so_far > nums[i]:
return True
sum_so_far += nums[i]
return False | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums` representing a series of heights, determine whether a selection of `2` or more of these heights can form a polygon. To form a valid polygon, the sum of the lengths of any `2` sides must be **greater** than the length of the remaining side. Return whether su... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6853,
"level": 1,
"question": "Given an integer array `nums` representing a series of heights, determine whether a selection of `2` or more of these heights can form a polygon. To form a valid polygon, the sum of the lengths of any `2` sides must be **greater** than the length of th... |
from collections import deque
def ladder_length(start, end, wordList):
word_set = set(wordList)
if start == end:
return 1 if end in word_set else 0
if end not in word_set:
return 0
queue = deque()
queue.append((start, 1))
visited = set()
visited.add(start)
whil... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given two words, `start` and `end`, as well as a list of words called `wordList`. Your task is to discover the shortest transformation sequence from `start` to `end`, such that:\n\n1. Each transformed word must exist in `wordList`.\n2. Only one letter can be changed at a time.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6854,
"level": 1,
"question": "You are given two words, `start` and `end`, as well as a list of words called `wordList`. Your task is to discover the shortest transformation sequence from `start` to `end`, such that:\n\n1. Each transformed word must exist in `wordList`.\n2. Only one... |
import numpy as np
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
def compute_principal_component_analysis(X: np.ndarray, y: np.ndarray, n_components: int):
# Compute PCA with the given number of components, standardizing the data
pca = PCA(n_components=n_components, whiten=True)
X_p... | simplelr_Package | [
{
"content": "Question:\nYou are asked to implement a function `compute_principal_component_analysis` which performs Principal Component Analysis (PCA) on a given set of data points. Your task is to project the data onto a lower-dimensional subspace defined by the principal components, and visualize the results... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6855,
"level": 1,
"question": "You are asked to implement a function `compute_principal_component_analysis` which performs Principal Component Analysis (PCA) on a given set of data points. Your task is to project the data onto a lower-dimensional subspace defined by the principal co... |
def min_houses_to_deliver(m: int, n: int, houses: list[list[int]]) -> int:
# Initialize the DP table
dp = [[0 for _ in range(n)] for _ in range(m)]
# Starting point
dp[0][0] = houses[0][0]
# Fill the first row
for j in range(1, n):
dp[0][j] = dp[0][j-1] + houses[0][j]
... | simplelr_Code_Contests | [
{
"content": "Question:\nIn a certain city, there is a rectangular grid of streets represented as an m x n matrix. Each cell in the matrix represents a block of houses, and each block has some number of houses assigned to it. The number of houses in each block is given in a 2D array `houses`.\n\nYou are a mailm... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6856,
"level": 1,
"question": "In a certain city, there is a rectangular grid of streets represented as an m x n matrix. Each cell in the matrix represents a block of houses, and each block has some number of houses assigned to it. The number of houses in each block is given in a 2D... |
from collections import deque
def bfs_shortest_path(graph, start, target):
if start not in graph:
return []
if start == target:
return [start]
visited = set()
queue = deque([start])
visited.add(start)
parent = {}
while queue:
current = queue.popleft()
... | simplelr_Filter | [
{
"content": "Question:\nI'm looking for a Python code snippet to find the shortest path in a graph using the Breadth-First Search (BFS) algorithm. Could you provide one?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6857,
"level": 1,
"question": "I'm looking for a Python code snippet to find the shortest path in a graph using the Breadth-First Search (BFS) algorithm. Could you provide one?",
"split": "train"
} |
def max_column_width(s):
columns = s.split(';')
stripped_columns = [col.strip() for col in columns]
lengths = [len(col) for col in stripped_columns if col != '']
return max(lengths) if lengths else 0 | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns the maximum width of a column in a table if the string is considered as a table row. The table row is represented as a string with semicolons separating the column values. The function should also handle cases where the st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6858,
"level": 1,
"question": "Write a Python function that takes a string as input and returns the maximum width of a column in a table if the string is considered as a table row. The table row is represented as a string with semicolons separating the column values. The function sh... |
from collections import defaultdict
def smallest_substring_length(s):
unique_chars = set(s)
target_size = len(unique_chars)
if target_size == 0:
return 0
char_count = defaultdict(int)
current_chars = 0
min_len = float('inf')
left = 0
for right in range(len(s)):
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` consisting of lowercase alphabetic characters, determine the size of the smallest substring that contains all the unique characters present in `s`. \n\nFor example, if `s = \"abac\"`, the smallest substring that contains all the unique characters (`a`, `b`, and `c`) i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6859,
"level": 1,
"question": "Given a string `s` consisting of lowercase alphabetic characters, determine the size of the smallest substring that contains all the unique characters present in `s`. \n\nFor example, if `s = \"abac\"`, the smallest substring that contains all the uniq... |
def max_temperature_difference(temperatures):
if len(temperatures) < 2:
return 0
max_diff = 0
min_so_far = temperatures[0]
for temp in temperatures[1:]:
current_diff = temp - min_so_far
if current_diff > max_diff:
max_diff = current_diff
if temp < min_so_far:
... | simplelr_Apps | [
{
"content": "Question:\nGiven a list of integers representing temperatures recorded over a week, write a function to find the maximum difference between two temperatures such that the second temperature occurs after the first one. If no such pair exists, return 0.\n\nExample 1:\nInput: temperatures = [30, 20, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6860,
"level": 1,
"question": "Given a list of integers representing temperatures recorded over a week, write a function to find the maximum difference between two temperatures such that the second temperature occurs after the first one. If no such pair exists, return 0.\n\nExample ... |
import pandas as pd
import matplotlib.pyplot as plt
import os
def generate_and_save_category_ratings_chart(file_path, output_path):
# Read the CSV file into a DataFrame
df = pd.read_csv(file_path)
# Group by Category and calculate the mean rating
avg_ratings = df.groupby('Category')['Rating'].mean... | simplelr_Package | [
{
"content": "Question:\nYou are required to create a function that reads a CSV file containing information about products and their respective ratings, then generates and saves a bar chart that visualizes the average rating of each product category. The function should also display the bar chart.\n\nYou are to... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6861,
"level": 1,
"question": "You are required to create a function that reads a CSV file containing information about products and their respective ratings, then generates and saves a bar chart that visualizes the average rating of each product category. The function should also d... |
def length_of_alphabetic_characters(s):
return sum(1 for c in s if c.isalpha()) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as a parameter and returns the length of the string after removing all non-alphabetic characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6862,
"level": 1,
"question": "Create a function that takes a string as a parameter and returns the length of the string after removing all non-alphabetic characters.",
"split": "train"
} |
def sort_players_by_score(player_scores: list) -> list:
sorted_players = sorted(player_scores, key=lambda x: (-x[1], x[0]))
return [player[0] for player in sorted_players] | simplelr_Algorithm | [
{
"content": "Question:\n### Sorting Organizer\n\nAs an organizer of a sports tournament, you are responsible for sorting the players according to their scores at the end of each round. Write a function that takes a list of player scores and returns a list of player names sorted in descending order of their sco... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6863,
"level": 1,
"question": "### Sorting Organizer\n\nAs an organizer of a sports tournament, you are responsible for sorting the players according to their scores at the end of each round. Write a function that takes a list of player scores and returns a list of player names sort... |
def count_pairs_with_sum(nums, target):
pairs = set()
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
pair = tuple(sorted((nums[i], nums[j])))
pairs.add(pair)
return len(pairs) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two parameters: a list of numbers and a target sum. The function should calculate the number of unique pairs of numbers from the list that add up to the target sum. For example, given the list `[1, 5, 7, -1]` and the target sum `6`, the function should retur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6864,
"level": 1,
"question": "Create a function that takes two parameters: a list of numbers and a target sum. The function should calculate the number of unique pairs of numbers from the list that add up to the target sum. For example, given the list `[1, 5, 7, -1]` and the target... |
import fcntl
def manage_file_lock(file_path: str, data: str = None) -> str:
"""
Manages a file lock for performing read/write operations on a file.
Args:
- file_path (str): The path to the file to be locked.
- data (str): The data to be written to the file if specified. If None, the function reads... | simplelr_Docs | [
{
"content": "Question:\nFile Descriptor Operations and Lock Management\n\n**Objective:**\nTo evaluate the student's understanding of the `fcntl` module in Python, how to handle file descriptors, and manage file operations and locks.\n\n**Problem Statement:**\n\nYou've been tasked with developing a utility func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6865,
"level": 1,
"question": "File Descriptor Operations and Lock Management\n\n**Objective:**\nTo evaluate the student's understanding of the `fcntl` module in Python, how to handle file descriptors, and manage file operations and locks.\n\n**Problem Statement:**\n\nYou've been ta... |
from typing import List, Tuple
def reverse_sections(string: str, indices: List[Tuple[int, int]]) -> str:
if not string:
return ""
words = string.split()
for i, j in indices:
# Reverse the words from index i to j inclusive
words[i:j+1] = words[i:j+1][::-1]
return ' '.join(words) | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Reverse Specific Sections of Words in a String\n\n#### Scenario:\nYou are working on a text processing module where you need to adjust the order of words in specific sections of a string. Given a string and a list of tuples where each tuple contains two indices, your task ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6866,
"level": 1,
"question": "### Question: Reverse Specific Sections of Words in a String\n\n#### Scenario:\nYou are working on a text processing module where you need to adjust the order of words in specific sections of a string. Given a string and a list of tuples where each tup... |
def sort_digits_keep_letters(s):
digits = [c for c in s if c.isdigit()]
sorted_digits = sorted(digits)
result = []
digit_index = 0
for c in s:
if c.isdigit():
result.append(sorted_digits[digit_index])
digit_index += 1
else:
result.append(c)
ret... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a string containing digits and letters and returns a new string with the digits sorted in ascending order while keeping the letters in their original places.\n\nFor example, for the input string \"a3b2c1\", the function should return \"a1b2c3\".\nAnswer:\nLet... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6867,
"level": 1,
"question": "Write a function that takes a string containing digits and letters and returns a new string with the digits sorted in ascending order while keeping the letters in their original places.\n\nFor example, for the input string \"a3b2c1\", the function shou... |
def count_odd_even(numbers: list[int]) -> tuple[int, int]:
odd_count = 0
even_count = 0
for num in numbers:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
return (odd_count, even_count) | simplelr_Algorithm | [
{
"content": "Question:\n### Task: Implement a Function to Count Odd and Even Numbers\n\n#### Context\nIn data analysis and statistics, it is often useful to categorize data into different groups. One simple form of categorization for numerical data is determining the count of odd and even numbers in a dataset.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6868,
"level": 1,
"question": "### Task: Implement a Function to Count Odd and Even Numbers\n\n#### Context\nIn data analysis and statistics, it is often useful to categorize data into different groups. One simple form of categorization for numerical data is determining the count of... |
def sort_and_square_numbers(numbers):
squares = [x ** 2 for x in numbers]
return sorted(squares) | simplelr_Apps | [
{
"content": "Question:\n## Task:\nWrite a function `sort_and_square_numbers` that accepts a list of integers and returns a list of their squares in non-decreasing order.\n\n### Rules/Note:\n* If the input list is empty, the function should return an empty list.\n* Any integer, positive or negative, can be pres... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6869,
"level": 1,
"question": "## Task:\nWrite a function `sort_and_square_numbers` that accepts a list of integers and returns a list of their squares in non-decreasing order.\n\n### Rules/Note:\n* If the input list is empty, the function should return an empty list.\n* Any integer... |
from typing import List
def longest_increasing_subsequence(prices: List[int]) -> int:
if not prices:
return 0
n = len(prices)
dp = [1] * n
for i in range(1, n):
for j in range(i):
if prices[j] < prices[i]:
if dp[j] + 1 > dp[i]:
dp[i] = dp[... | simplelr_Algorithm | [
{
"content": "Question:\n### Longest Increasing Subsequence - Stock Price Analysis\n\nYou are working as a financial analyst and need to analyze the stock prices over a series of days. Your task is to determine the length of the longest increasing subsequence of stock prices. This will help to understand the ma... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6870,
"level": 1,
"question": "### Longest Increasing Subsequence - Stock Price Analysis\n\nYou are working as a financial analyst and need to analyze the stock prices over a series of days. Your task is to determine the length of the longest increasing subsequence of stock prices. ... |
import csv
def count_csv_rows(filename):
with open(filename, 'r') as csvfile:
csvreader = csv.reader(csvfile)
count = 0
for _ in csvreader:
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function that reads a CSV file and returns the number of rows in the file? How can I use this function to count the number of rows in a specific CSV file?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6871,
"level": 1,
"question": "Can you provide a Python function that reads a CSV file and returns the number of rows in the file? How can I use this function to count the number of rows in a specific CSV file?",
"split": "train"
} |
def celsius_to_fahrenheit(c):
scaled = c * 9
converted = scaled / 5
fahrenheit = converted + 32
return round(fahrenheit) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert Celsius to Fahrenheit without using the formula directly. You can only use the standard arithmetic operations and type conversions. Your function should handle floating-point inputs and scale the result to the nearest integer.\nAnswer:\nLet's think ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6872,
"level": 1,
"question": "Write a python function to convert Celsius to Fahrenheit without using the formula directly. You can only use the standard arithmetic operations and type conversions. Your function should handle floating-point inputs and scale the result to the nearest... |
def length_of_longest_substring(s):
last_seen = {}
max_len = 0
start = 0
for end in range(len(s)):
char = s[end]
if char in last_seen:
start = max(start, last_seen[char] + 1)
last_seen[char] = end
current_len = end - start + 1
if current_len > max_len:... | simplelr_Taco | [
{
"content": "Question:\nGiven a string containing only uppercase English letters, write a function to determine the length of the longest substring without repeating characters. \n\nFor example, the string \"ABCABCBB\" has the longest substring \"ABC\", which has a length of 3. For the string \"BBBB\" the long... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6873,
"level": 1,
"question": "Given a string containing only uppercase English letters, write a function to determine the length of the longest substring without repeating characters. \n\nFor example, the string \"ABCABCBB\" has the longest substring \"ABC\", which has a length of ... |
def find_nth_digit(n: int) -> int:
digits = 1
count = 9
start = 1
while n > digits * count:
n -= digits * count
digits += 1
count *= 10
start *= 10
number = start + (n - 1) // digits
digit_index = (n - 1) % digits
return int(str(number)[digit_index]) | simplelr_Data_Structure | [
{
"content": "Question:\n### Coding Challenge: Find the Nth Digit\n\nYou are given an infinite sequence of digits formed by concatenating positive integers in ascending order starting from 1:\n`123456789101112131415...`\n\nWrite a function `find_nth_digit(n)` to find the nth digit (1-indexed) in this infinite s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6874,
"level": 1,
"question": "### Coding Challenge: Find the Nth Digit\n\nYou are given an infinite sequence of digits formed by concatenating positive integers in ascending order starting from 1:\n`123456789101112131415...`\n\nWrite a function `find_nth_digit(n)` to find the nth d... |
def max_sum_subarray(arr, window_size):
if not arr or window_size <= 0 or window_size > len(arr):
return None # Handle invalid input cases
n = len(arr)
current_sum = sum(arr[:window_size])
max_sum = current_sum
for i in range(1, n - window_size + 1):
current_sum = current_... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code snippet that demonstrates how to use a sliding window algorithm to find the maximum sum of a contiguous subarray of a fixed size within a given array?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6875,
"level": 1,
"question": "Can you provide a Python code snippet that demonstrates how to use a sliding window algorithm to find the maximum sum of a contiguous subarray of a fixed size within a given array?",
"split": "train"
} |
import pandas as pd
import matplotlib.pyplot as plt
from pandas.plotting import parallel_coordinates, andrews_curves, scatter_matrix
def plot_data_trends(file_path: str):
'''
This function reads a CSV file, converts the 'Date' column to a numerical format,
and generates three different plots: Parallel Coor... | simplelr_Docs | [
{
"content": "Question:\n**Objective**: Thoroughly assess the student's understanding of the `pandas.plotting` module along with data manipulation capabilities of `pandas`.\n\n### Coding Assessment Question\n\nYou are provided with a CSV file `data.csv`, which contains the following columns:\n- `Date`: The date... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6876,
"level": 1,
"question": "**Objective**: Thoroughly assess the student's understanding of the `pandas.plotting` module along with data manipulation capabilities of `pandas`.\n\n### Coding Assessment Question\n\nYou are provided with a CSV file `data.csv`, which contains the fol... |
def most_frequent_word(words):
if not words:
return ''
# Create a frequency dictionary
freq = {}
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
# Find the maximum frequency
max_freq = max(freq.values())
... | simplelr_Package | [
{
"content": "Question:\nIn this exercise, you need to create a function that determines the most frequent word in a list of words. If multiple words have the same highest frequency, the function should return the lexicographically smallest word.\n\n### Detailed Requirements:\n\n- You need to define a function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6877,
"level": 1,
"question": "In this exercise, you need to create a function that determines the most frequent word in a list of words. If multiple words have the same highest frequency, the function should return the lexicographically smallest word.\n\n### Detailed Requirements:\... |
import pandas as pd
def analyze_sales(sales_data):
# Create DataFrame from the sales data
df = pd.DataFrame(sales_data)
# Convert the 'date' column to datetime format
df['date'] = pd.to_datetime(df['date'])
# Group by 'customer_id' and compute the required metrics
grouped = df.groupby... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nThis question will assess your ability to manipulate and analyze data using pandas DataFrame functionalities, including creation, indexing, grouping, and statistical analysis.\n\n#### Problem Statement:\nYou are given a sales dataset in the form of a list of dictionarie... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6878,
"level": 1,
"question": "#### Objective:\nThis question will assess your ability to manipulate and analyze data using pandas DataFrame functionalities, including creation, indexing, grouping, and statistical analysis.\n\n#### Problem Statement:\nYou are given a sales dataset i... |
import sys
import tty
import termios
import os
def read_key():
if os.name == 'ntp': # For Windows
import msvcrt
print("Press any key, then press Enter...")
return msvcrt.getch().decode().strip()
else: # For Linux/Unix
fd = sys.stdin.fileno()
old_settings = termios.tcge... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code snippet to read key presses in real-time from the user input.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6879,
"level": 1,
"question": "Write a Python code snippet to read key presses in real-time from the user input.",
"split": "train"
} |
def zigzag_traversal(matrix: list[list[int]]) -> list[int]:
if not matrix:
return []
m = len(matrix)
n = len(matrix[0])
result = []
max_s = m + n - 2
for s in range(max_s + 1):
temp = []
start_i = max(0, s - (n - 1))
end_i = min(m, s + 1)
for i in range(st... | simplelr_Algorithm | [
{
"content": "Question:\n**Coding Question: Zigzag (Diagonal) Traverse a Matrix**\n\nYou are given a 2D matrix (a list of lists) containing integers. Your task is to implement a function that traverses and returns the elements of the matrix in a diagonal (zigzag) order. The traversal should start from the top-l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6880,
"level": 1,
"question": "**Coding Question: Zigzag (Diagonal) Traverse a Matrix**\n\nYou are given a 2D matrix (a list of lists) containing integers. Your task is to implement a function that traverses and returns the elements of the matrix in a diagonal (zigzag) order. The tr... |
def remove_duplicates(nums):
if not nums:
return 0
write_pointer = 1
for i in range(1, len(nums)):
if nums[i] != nums[i-1]:
nums[write_pointer] = nums[i]
write_pointer += 1
return write_pointer | simplelr_Filter | [
{
"content": "Question:\nGiven a sorted array of integers, write a function to remove the duplicates in place such that each element appears only once and returns the new length. The function should modify the input array in place with O(1) extra memory. For example, given the input array [1, 1, 2], the functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6881,
"level": 1,
"question": "Given a sorted array of integers, write a function to remove the duplicates in place such that each element appears only once and returns the new length. The function should modify the input array in place with O(1) extra memory. For example, given the... |
def find_nth_prime(n):
if n < 1:
return None
primes = [2]
if n == 1:
return primes[0]
m = 3
while len(primes) < n:
is_prime = True
sqrt_m = m ** 0.5
for p in primes:
if p > sqrt_m:
break
if m % p == 0:
is... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the nth prime number. The function should be named `find_nth_prime`, which takes an integer `n` as an argument. The function should return the nth prime number.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6882,
"level": 1,
"question": "Write a function to find the nth prime number. The function should be named `find_nth_prime`, which takes an integer `n` as an argument. The function should return the nth prime number.",
"split": "train"
} |
def transpose(matrix):
if not matrix:
return []
rows = len(matrix)
cols = len(matrix[0])
transposed = []
for i in range(cols):
new_row = []
for j in range(rows):
new_row.append(matrix[j][i])
transposed.append(new_row)
return transposed | simplelr_Apps | [
{
"content": "Question:\nWrite a function that performs matrix transposition without using any built-in or external libraries. The input to the function will be a 2D list representing a matrix. Transpose the given matrix and return the resulting matrix. Transposition involves flipping rows and columns, so each ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6883,
"level": 1,
"question": "Write a function that performs matrix transposition without using any built-in or external libraries. The input to the function will be a 2D list representing a matrix. Transpose the given matrix and return the resulting matrix. Transposition involves ... |
def find_maximum(arr):
if not arr:
return -1
return max(arr) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the maximum number in an array of integers. If the array is empty, return `-1`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6884,
"level": 1,
"question": "Write a function to find the maximum number in an array of integers. If the array is empty, return `-1`.",
"split": "train"
} |
def max_packages_in_subgrid(n, k, packages):
if k > n:
return 0
# Initialize the grid with 1s for package locations
grid = [[0] * (n + 2) for _ in range(n + 2)]
for x, y in packages:
grid[x][y] = 1
# Compute the prefix sum array
prefix = [[0] * (n + 2) for _ in range(n ... | simplelr_Code_Contests | [
{
"content": "Question:\nA delivery company is planning to optimize their package delivery routes. Each package has a destination, and the destinations are spread across a city represented as a grid. The company wants to group the packages in such a way that each group’s destinations form a square subgrid. The ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6885,
"level": 1,
"question": "A delivery company is planning to optimize their package delivery routes. Each package has a destination, and the destinations are spread across a city represented as a grid. The company wants to group the packages in such a way that each group’s desti... |
def gcd(a, b):
if b == 0:
return a
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that returns the greatest common divisor (GCD) of two numbers `a` and `b`. The function should work for both positive and negative integers, and should handle the case where `b` is zero, which should return `a`.\nAnswer:\nLet's think step by step.\n",
"role": "user... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6886,
"level": 1,
"question": "Create a function that returns the greatest common divisor (GCD) of two numbers `a` and `b`. The function should work for both positive and negative integers, and should handle the case where `b` is zero, which should return `a`.",
"split": "train"
} |
def custom_string_manipulation(s: str, operation_code: int) -> str:
if operation_code == 1:
return s[::-1]
elif operation_code == 2:
return s.upper()
elif operation_code == 3:
return s.lower()
elif operation_code == 4:
return s.replace(' ', '_')
else:
raise Va... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\n**Custom String Manipulation**\n\nYou are given a function template `custom_string_manipulation(s: str, operation_code: int) -> str`. This function performs string manipulations based on the provided operation code. The function should:\n\n1. Reverse the string ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6887,
"level": 1,
"question": "### Problem Statement\n\n**Custom String Manipulation**\n\nYou are given a function template `custom_string_manipulation(s: str, operation_code: int) -> str`. This function performs string manipulations based on the provided operation code. The functio... |
def filter_divisible_by_3_not_5(nums):
return [num for num in nums if num % 3 == 0 and num % 5 != 0] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns a new list containing only the integers that are divisible by 3 but not divisible by 5. Test your function with the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]. The expected output is [3, 6, 9, 12].\nAnswer:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6888,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns a new list containing only the integers that are divisible by 3 but not divisible by 5. Test your function with the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]. The expected... |
def find_largest_product(digits: str, k: int) -> int:
# Check if all characters are digits
if not digits.isdigit():
raise ValueError("Input string contains non-digit characters")
# Convert the string to a list of integers
digits_list = [int(c) for c in digits]
n = len(digits_list)
... | simplelr_Evol | [
{
"content": "Question:\nWrite a function called `find_largest_product` that takes a string of digits and an integer `k` as input. The function should compute the largest product of `k` consecutive digits within the string. If the string contains non-digit characters, the function should raise a `ValueError` ex... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6889,
"level": 1,
"question": "Write a function called `find_largest_product` that takes a string of digits and an integer `k` as input. The function should compute the largest product of `k` consecutive digits within the string. If the string contains non-digit characters, the func... |
import math
def is_prime(num):
if num < 2:
return False
sqrt_num = int(math.sqrt(num))
for i in range(2, sqrt_num + 1):
if num % i == 0:
return False
return True | simplelr_Filter | [
{
"content": "Question:\nHow would you implement a function to determine if a number is a prime number in Python, using a for loop?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6890,
"level": 1,
"question": "How would you implement a function to determine if a number is a prime number in Python, using a for loop?",
"split": "train"
} |
def replace_and_estimate(numbers: list[int], target: int) -> list[float]:
new_numbers = []
for i in range(len(numbers)):
if numbers[i] == target:
if i == 0:
replacement = numbers[i + 1]
elif i == len(numbers) - 1:
replacement = numbers[i - 1]
... | simplelr_Package | [
{
"content": "Question:\nWrite a function called `replace_and_estimate` that takes two arguments: a list of integers `numbers` and an integer `target`. The function should replace each occurrence of the `target` in the list with the mean (average) of its immediate neighbors. If the target is at the beginning or... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6891,
"level": 1,
"question": "Write a function called `replace_and_estimate` that takes two arguments: a list of integers `numbers` and an integer `target`. The function should replace each occurrence of the `target` in the list with the mean (average) of its immediate neighbors. I... |
def max_rectangle_area(base, height):
return (base * height) / 4 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the maximum area of a rectangle that can be formed within a right-angled triangle with given base and height. The side of the rectangle parallel to the base of the triangle must be along the base of the triangle, and its opposite corner must be along... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6892,
"level": 1,
"question": "Write a python function to calculate the maximum area of a rectangle that can be formed within a right-angled triangle with given base and height. The side of the rectangle parallel to the base of the triangle must be along the base of the triangle, an... |
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr
# Example u... | simplelr_Filter | [
{
"content": "Question:\nCan you provide an example of how to create a bubble sort algorithm in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6893,
"level": 1,
"question": "Can you provide an example of how to create a bubble sort algorithm in Python?",
"split": "train"
} |
from collections import deque
def walls_and_gates(grid):
if not grid:
return
m = len(grid)
n = len(grid[0]) if m > 0 else 0
INF = 2147483647
queue = deque()
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# Enqueue all gates
for i in range(m):
for j in range(n):
... | simplelr_Data_Structure | [
{
"content": "Question:\nShortest Distance to Gates Using Breadth-First Search\n\n**Context**: You are an engineer working on a grid-based maze game prototype. The game contains multiple gates and rooms, and your task is to calculate the shortest distance from each room to the nearest gate. The grid has walls t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6894,
"level": 1,
"question": "Shortest Distance to Gates Using Breadth-First Search\n\n**Context**: You are an engineer working on a grid-based maze game prototype. The game contains multiple gates and rooms, and your task is to calculate the shortest distance from each room to the... |
def sum_of_odds(n):
"""
Calculate the sum of all odd numbers from 1 to n.
Args:
n (int): The upper limit of the range.
Returns:
int: The sum of all odd numbers up to n.
"""
total = 0
for number in range(1, n + 1):
if number % 2 != 0:
total += num... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the sum of all odd numbers from 1 to n.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6895,
"level": 1,
"question": "Write a function to find the sum of all odd numbers from 1 to n.",
"split": "train"
} |
import os
def get_absolute_path(file: str) -> str:
if not file:
return os.path.abspath('')
expanded = os.path.expanduser(file)
return os.path.abspath(expanded) | simplelr_Data_Structure | [
{
"content": "Question:\n### Absolute Path Resolution\n\n#### Context\nYou are building a file management application where you need to manage various files from different locations on a user's machine. To ensure your application consistently manages files regardless of the current working directory or user-spe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6896,
"level": 1,
"question": "### Absolute Path Resolution\n\n#### Context\nYou are building a file management application where you need to manage various files from different locations on a user's machine. To ensure your application consistently manages files regardless of the cu... |
def shortest_path(matrix, src):
n = len(matrix)
INF = float('inf')
dist = [INF] * n
dist[src] = 0
visited = [False] * n
for _ in range(n):
# Find the unvisited node with the smallest distance
u = -1
min_dist = INF
for v in range(n):
if not visited[v] ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question:\nIn a transportation logistics company, you have been tasked to build a system to find the shortest travel route between different warehouses. The city map is modeled as a weighted directed graph where nodes represent warehouses, and edges represent direct travel routes wi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6897,
"level": 1,
"question": "### Question:\nIn a transportation logistics company, you have been tasked to build a system to find the shortest travel route between different warehouses. The city map is modeled as a weighted directed graph where nodes represent warehouses, and edge... |
def cardGame(deck):
john_score = 0
sarah_score = 0
points = {'H': 4, 'D': 3, 'C': 2, 'S': 1}
for i in range(len(deck)):
suit = deck[i]
point = points[suit]
if i % 2 == 0:
john_score += point
else:
sarah_score += point
if john_score > sarah_scor... | simplelr_Apps | [
{
"content": "Question:\nJohn and Sarah are playing a card game using a standard 52-card deck. They take turns drawing cards from the top of the deck. John always draws first. Each drawing action consists of drawing one card, and the suit of that card determines their score based on the following rules:\n\n- He... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6898,
"level": 1,
"question": "John and Sarah are playing a card game using a standard 52-card deck. They take turns drawing cards from the top of the deck. John always draws first. Each drawing action consists of drawing one card, and the suit of that card determines their score ba... |
def cumulative_sum(numbers):
current_sum = 0
result = []
for num in numbers:
current_sum += num
result.append(current_sum)
return result | simplelr_Filter | [
{
"content": "Question:\n### Incrementing a Variable in a Loop\n# Incrementing a variable in a loop is a common operation in computer programming. \n# It's often used in control structures, such as for loops and while loops.\n# The following Python script demonstrates how to increment a variable named `i` insid... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6899,
"level": 1,
"question": "### Incrementing a Variable in a Loop\n# Incrementing a variable in a loop is a common operation in computer programming. \n# It's often used in control structures, such as for loops and while loops.\n# The following Python script demonstrates how to i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.