target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
import math
def num_digits(n: int) -> int:
n = abs(n)
if n == 0:
return 1
return int(math.log10(n)) + 1 | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Count the Number of Digits in an Integer\n\n#### Objective\nYou are required to implement a function that counts the number of digits in a given integer. This function should work efficiently for both positive and negative numbers, as well as for zero.\n\n#### Input and Ou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3400,
"level": 1,
"question": "### Question: Count the Number of Digits in an Integer\n\n#### Objective\nYou are required to implement a function that counts the number of digits in a given integer. This function should work efficiently for both positive and negative numbers, as wel... |
def sum_odd_numbers(arr):
total = 0
for num in arr:
if num % 2 != 0:
total += num
return total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the sum of all numbers in an array, ignoring any even numbers. Here is a Python function to help you get started.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3401,
"level": 1,
"question": "Create a function that calculates the sum of all numbers in an array, ignoring any even numbers. Here is a Python function to help you get started.",
"split": "train"
} |
def trap_rain_water(heights):
if not heights:
return 0
n = len(heights)
left_max = [0] * n
right_max = [0] * n
left_max[0] = heights[0]
for i in range(1, n):
left_max[i] = max(left_max[i-1], heights[i])
right_max[-1] = heights[-1]
for i in range(n-2, -1, -1):
... | simplelr_Apps | [
{
"content": "Question:\n# Task\n\nYou are given a list of integers representing the heights of buildings in a city, where each element represents the height of a building in a straight line. Your task is to compute the amount of water that can be trapped after a rainstorm.\n\nThe water that can be trapped is q... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3402,
"level": 1,
"question": "# Task\n\nYou are given a list of integers representing the heights of buildings in a city, where each element represents the height of a building in a straight line. Your task is to compute the amount of water that can be trapped after a rainstorm.\n\... |
def is_accepted(transitions, start, final, string):
current = start
for char in string:
current = transitions[current][char]
return current in final | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nYou are working on a text processing tool that uses pattern matching to validate input strings against predefined rules. To implement part of this tool, you need to use a Deterministic Finite Automaton (DFA) to accept or reject input strings based on their conformity to a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3403,
"level": 1,
"question": "#### Scenario\nYou are working on a text processing tool that uses pattern matching to validate input strings against predefined rules. To implement part of this tool, you need to use a Deterministic Finite Automaton (DFA) to accept or reject input str... |
def dynamic_binomial_coefficient(n, k):
"""
Calculates the binomial coefficient C(n, k) using dynamic programming.
Parameters:
n (int): Number of elements in the set (n >= 0)
k (int): Number of elements to choose (0 <= k <= n)
Returns:
int: The binomial coefficient C(n, k)
Raises:
... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with writing a function to compute the binomial coefficient using dynamic programming rather than recursion to avoid potential stack overflow issues when handling large values of `n` and `k`. This coefficient represents the number of ways to choose `k` elements from a set... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3404,
"level": 1,
"question": "You are tasked with writing a function to compute the binomial coefficient using dynamic programming rather than recursion to avoid potential stack overflow issues when handling large values of `n` and `k`. This coefficient represents the number of way... |
def analyze_string_pattern(input_string: str) -> dict:
total_characters = len(input_string)
alphabetic = 0
digits = 0
whitespace = 0
filtered_str = []
for c in input_string:
if c.isalpha():
alphabetic += 1
if c.isdigit():
digits += 1
if c.issp... | simplelr_Package | [
{
"content": "Question:\nYou are tasked to implement a function named `analyze_string_pattern` that will take a string as input and return a dictionary with specific characteristics of the string. These characteristics include:\n1. The total number of characters in the string.\n2. The number of alphabetic chara... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3405,
"level": 1,
"question": "You are tasked to implement a function named `analyze_string_pattern` that will take a string as input and return a dictionary with specific characteristics of the string. These characteristics include:\n1. The total number of characters in the string.... |
from typing import List, Union
def floyd_warshall(adjacency_matrix: List[List[int]], start_city: int, end_city: int) -> Union[int, str]:
n = len(adjacency_matrix)
distance = [row.copy() for row in adjacency_matrix]
for k in range(n):
for i in range(n):
for j in range(n):
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of integers representing the distances between pairs of cities in the form of an adjacency matrix. An entry adjacency_matrix[i][j] represents the distance between city i and city j. Your task is to write a function that computes the shortest path between two given c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3406,
"level": 1,
"question": "You are given a list of integers representing the distances between pairs of cities in the form of an adjacency matrix. An entry adjacency_matrix[i][j] represents the distance between city i and city j. Your task is to write a function that computes th... |
def customSort(nums: list[int]) -> list[int]:
return sorted(nums, key=lambda x: (x % 2, x)) | simplelr_Codeforces | [
{
"content": "Question:\nYou are organizing a company-wide coding competition where participants are asked to solve various algorithmic problems. One of the challenges involves reordering an array of integers based on a specific sorting method. However, there is a twist: the array must be sorted in such a way t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3407,
"level": 1,
"question": "You are organizing a company-wide coding competition where participants are asked to solve various algorithmic problems. One of the challenges involves reordering an array of integers based on a specific sorting method. However, there is a twist: the a... |
def find_peak_elements(arr):
peaks = []
n = len(arr)
for i in range(n):
if i == 0:
if n == 1 or arr[i] > arr[i + 1]:
peaks.append((arr[i], i))
elif i == n - 1:
if arr[i] > arr[i - 1]:
peaks.append((arr[i], i))
else:
... | simplelr_Evol | [
{
"content": "Question:\nGiven an array of integers, write a function `find_peak_elements` that identifies and returns all the \"peak\" elements in the array. A peak element is defined as an element which is greater than its neighbors. For elements at the boundaries of the array, they only need to be greater th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3408,
"level": 1,
"question": "Given an array of integers, write a function `find_peak_elements` that identifies and returns all the \"peak\" elements in the array. A peak element is defined as an element which is greater than its neighbors. For elements at the boundaries of the arr... |
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[-1]
low = []
equal = []
high = []
for x in arr:
if x < pivot:
low.append(x)
elif x == pivot:
equal.append(x)
else:
high.append(x)
return quick_sort(low) + equal +... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python program to sort the numbers in an array using the quick sort algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3409,
"level": 1,
"question": "Create a Python program to sort the numbers in an array using the quick sort algorithm.",
"split": "train"
} |
def increment_minor_version(version):
parts = version.split('.')
while len(parts) < 3:
parts.append('0')
major = int(parts[0])
minor = int(parts[1])
patch = int(parts[2])
minor += 1
patch = 0
return f"{major}.{minor}.{patch}" | simplelr_Filter | [
{
"content": "Question:\nHow can I increment a version number in Python, specifically increasing the minor version for a semantic versioning scheme?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3410,
"level": 1,
"question": "How can I increment a version number in Python, specifically increasing the minor version for a semantic versioning scheme?",
"split": "train"
} |
def max_subarray_sum(nums):
if not nums:
return 0
current_max = global_max = nums[0]
for num in nums[1:]:
current_max = max(num, current_max + num)
if current_max > global_max:
global_max = current_max
return global_max | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers as input and returns the maximum sum of a contiguous subarray. This function should implement Kadane's algorithm efficiently.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3411,
"level": 1,
"question": "Create a function that takes a list of integers as input and returns the maximum sum of a contiguous subarray. This function should implement Kadane's algorithm efficiently.",
"split": "train"
} |
from datetime import datetime
def days_between_dates(date1, date2):
dt1 = datetime.strptime(date1, '%Y-%m-%d')
dt2 = datetime.strptime(date2, '%Y-%m-%d')
delta = dt2 - dt1
return abs(delta.days) | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario:\nYou are developing a utility for date manipulation that can calculate the number of days between two dates. The dates will be provided in the format \"YYYY-MM-DD\". Additionally, you need to correctly handle leap years and ensure that the calculation is accurate even for ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3412,
"level": 1,
"question": "### Scenario:\nYou are developing a utility for date manipulation that can calculate the number of days between two dates. The dates will be provided in the format \"YYYY-MM-DD\". Additionally, you need to correctly handle leap years and ensure that th... |
from collections import defaultdict
def subarray_sum(arr, k):
prefix_counts = defaultdict(int)
prefix_counts[0] = 1 # Initialize with prefix sum 0 occurring once
current_sum = 0
result = 0
for num in arr:
current_sum += num
# Check if (current_sum - k) exists in the prefix sum... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array `arr` of integers and an integer `k`. A subarray is a contiguous part of an array. A subarray sum is the sum of elements in that subarray. Implement a function that returns the total number of subarrays whose sum equals to `k`. \n\nFor example, given the input `ar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3413,
"level": 1,
"question": "You are given an array `arr` of integers and an integer `k`. A subarray is a contiguous part of an array. A subarray sum is the sum of elements in that subarray. Implement a function that returns the total number of subarrays whose sum equals to `k`. \... |
def is_palindrome(n):
if n < 0:
return False
s = str(n)
return s == s[::-1] | simplelr_Apps | [
{
"content": "Question:\nGiven an integer `n`, return a boolean indicating whether `n` is a palindrome. A palindrome is a number that reads the same backwards as forwards.\n\nFor example:\n- For `n = 12321`, the function should return `true`.\n- For `n = -12321`, the function should return `false` since the neg... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3414,
"level": 1,
"question": "Given an integer `n`, return a boolean indicating whether `n` is a palindrome. A palindrome is a number that reads the same backwards as forwards.\n\nFor example:\n- For `n = 12321`, the function should return `true`.\n- For `n = -12321`, the function ... |
def has_pair_with_sum(arr, target):
seen = set()
for num in arr:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two parameters, an array of integers and a target sum. The function should return true if there exists a pair in the array that adds up to the target sum, and false otherwise. The function should run in O(n) time complexity, using constant space.\nAnswer:\nL... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3415,
"level": 1,
"question": "Create a function that takes two parameters, an array of integers and a target sum. The function should return true if there exists a pair in the array that adds up to the target sum, and false otherwise. The function should run in O(n) time complexity... |
import math
def translate_point(point, distance, angle):
x, y = point
angle_rad = math.radians(angle)
delta_x = distance * math.cos(angle_rad)
delta_y = distance * math.sin(angle_rad)
new_x = x + delta_x
new_y = y + delta_y
return [round(new_x, 4), round(new_y, 4)]
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `translate_point()` which, given the coordinates of a point in 2D space, a fixed distance, and a direction specified as an angle in degrees, computes the new coordinates of the point after moving it by the given distance in the specified direction.\n\nThe function shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3416,
"level": 1,
"question": "Write a function `translate_point()` which, given the coordinates of a point in 2D space, a fixed distance, and a direction specified as an angle in degrees, computes the new coordinates of the point after moving it by the given distance in the specifi... |
def tree_height(root: tuple) -> int:
if root is None:
return -1
else:
left_height = tree_height(root[1])
right_height = tree_height(root[2])
return 1 + max(left_height, right_height) | simplelr_Code_Contests | [
{
"content": "Question:\nGiven a binary tree, where each node has an integer value. Write a function that computes the height of the tree. The height of a binary tree is the number of edges from the root to the deepest leaf. An empty tree has height -1, and a tree with a single node has a height of 0.\n\nInput\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3417,
"level": 1,
"question": "Given a binary tree, where each node has an integer value. Write a function that computes the height of the tree. The height of a binary tree is the number of edges from the root to the deepest leaf. An empty tree has height -1, and a tree with a singl... |
def join_dicts(left_df, right_df):
result = {}
for key in left_df:
left_val = left_df[key]
right_val = right_df.get(key)
if right_val is not None:
# Convert both values to lists if they are not already
left_list = left_val if isinstance(left_val, list) else [left_... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that simulates a simplified version of the `DataFrame.join` method from the Pandas library. This function should join two dictionaries (representing DataFrames) based on their keys (representing the index). The function should be able to handle cases where the s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3418,
"level": 1,
"question": "Create a Python function that simulates a simplified version of the `DataFrame.join` method from the Pandas library. This function should join two dictionaries (representing DataFrames) based on their keys (representing the index). The function should ... |
import re
def extract_text(html: str) -> str:
# Extract all text segments between HTML tags
texts = re.findall(r'>([^<]+)<', html)
# Join the segments with a single space and return
return ' '.join(texts)
| simplelr_Taco | [
{
"content": "Question:\nSam is working on a basic HTML parser for a web scraping project. One of the tasks is to extract the text content from within HTML tags. The HTML documents Sam is working with are simple and do not contain any nested tags or attributes.\n\nFor example, given the HTML string \"<div>Hello... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3419,
"level": 1,
"question": "Sam is working on a basic HTML parser for a web scraping project. One of the tasks is to extract the text content from within HTML tags. The HTML documents Sam is working with are simple and do not contain any nested tags or attributes.\n\nFor example,... |
from typing import List, Generator
def data_stream_generator(data: List[int]) -> Generator[int, None, None]:
for item in data:
yield item
| simplelr_Docs | [
{
"content": "Question:\n### Generator Object Management\n\n#### Objective\nIn this exercise, you will demonstrate your understanding of Python generators by implementing a function that simulates a real-world scenario and utilizes generator functions.\n\n### Problem Statement\nWrite a function `data_stream_gen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3420,
"level": 1,
"question": "### Generator Object Management\n\n#### Objective\nIn this exercise, you will demonstrate your understanding of Python generators by implementing a function that simulates a real-world scenario and utilizes generator functions.\n\n### Problem Statement... |
def split_list(lst):
even_indexed = []
odd_indexed = []
for index, value in enumerate(lst):
if index % 2 == 0:
even_indexed.append(value)
else:
odd_indexed.append(value)
return (even_indexed, odd_indexed)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `split_list` that takes a list of integers and splits it into two lists. The first list should contain the even indexed elements (0, 2, 4, ...) and the second list should contain the odd indexed elements (1, 3, 5, ...).\n\nExamples:\n\nInput: [2, 1, 4, 3, 6, 5] \nOutpu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3421,
"level": 1,
"question": "Write a function `split_list` that takes a list of integers and splits it into two lists. The first list should contain the even indexed elements (0, 2, 4, ...) and the second list should contain the odd indexed elements (1, 3, 5, ...).\n\nExamples:\n\... |
import re
def count_matches(strings, patterns):
# Convert each pattern to the corresponding regex
regexes = []
for pattern in patterns:
regex = []
for c in pattern:
if c == '?':
regex.append('.')
elif c == '*':
regex.append('.*')
... | simplelr_Filter | [
{
"content": "Question:\nGiven a list of strings and a list of patterns, write a Python function that finds the number of strings from the list that match any of the patterns. A string matches a pattern if it follows the same wildcard format as the pattern, where '?' can represent any single character and '*' c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3422,
"level": 1,
"question": "Given a list of strings and a list of patterns, write a Python function that finds the number of strings from the list that match any of the patterns. A string matches a pattern if it follows the same wildcard format as the pattern, where '?' can repre... |
def num_decodings(s: str) -> int:
n = len(s)
dp = [0] * (n + 1)
dp[0] = 1 # Base case: one way to decode an empty string
for i in range(1, n + 1):
# Check single-digit case
if s[i-1] != '0':
dp[i] += dp[i-1]
# Check two-digit case
if i >= 2:
... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a string of integers representing an encoded message. Each integer in the string represents a letter according to the following rules:\n\n- '1' to '9' -> 'A' to 'I'\n- '10' to '26' -> 'J' to 'Z'\n\nWrite a function `num_decodings(s: str) -> int` that takes a string `s` rep... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3423,
"level": 1,
"question": "You are given a string of integers representing an encoded message. Each integer in the string represents a letter according to the following rules:\n\n- '1' to '9' -> 'A' to 'I'\n- '10' to '26' -> 'J' to 'Z'\n\nWrite a function `num_decodings(s: str) ... |
def factorial(n):
if n < 0:
raise ValueError("n must be a non-negative integer")
result = 1
for i in range(1, n + 1):
result *= i
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a single integer as an input and returns the factorial of the number. The function should handle non-negative integers and raise a ValueError for negative inputs.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3424,
"level": 1,
"question": "Create a function that takes a single integer as an input and returns the factorial of the number. The function should handle non-negative integers and raise a ValueError for negative inputs.",
"split": "train"
} |
def find_min_max(arr):
if arr is None or len(arr) == 0:
return {'error': 'Array is empty or null'}
min_val = min(arr)
max_val = max(arr)
min_index = arr.index(min_val)
max_index = arr.index(max_val)
return {
'min': [min_val, min_index],
'max': [max_val, max... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that identifies the smallest and largest numbers in an array along with their positions. Your function should return a dictionary where the keys \"min\" and \"max\" contain arrays with the minimum number, its position, the maximum number, and its position respectively.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3425,
"level": 1,
"question": "Create a function that identifies the smallest and largest numbers in an array along with their positions. Your function should return a dictionary where the keys \"min\" and \"max\" contain arrays with the minimum number, its position, the maximum num... |
def smallest_even_number(numbers):
even_numbers = [num for num in numbers if num % 2 == 0]
if not even_numbers:
return None
return min(even_numbers) | simplelr_Filter | [
{
"content": "Question:\nFormulate an effective Python-coded functional program that proficiently discerns the smallest even number from a given list of integer values. Here's a practical scenario with the list: [45, 22, 11, 90, 33]. The program should ideally also handle cases where no even number is found. Su... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3426,
"level": 1,
"question": "Formulate an effective Python-coded functional program that proficiently discerns the smallest even number from a given list of integer values. Here's a practical scenario with the list: [45, 22, 11, 90, 33]. The program should ideally also handle case... |
def triangular_numbers(n):
return [i * (i + 1) // 2 for i in range(1, n + 1)]
| simplelr_Taco | [
{
"content": "Question:\nGiven an integer `n`, create a function to generate a list of the first `n` Triangular numbers. The Triangular numbers are a sequence of numbers where each nth term is the sum of the first `n` natural numbers.\n\nTriangular number Tn is the sum of all natural numbers up to `n`. The form... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3427,
"level": 1,
"question": "Given an integer `n`, create a function to generate a list of the first `n` Triangular numbers. The Triangular numbers are a sequence of numbers where each nth term is the sum of the first `n` natural numbers.\n\nTriangular number Tn is the sum of all ... |
from collections import Counter
def find_duplicates(arr):
counts = Counter(arr)
duplicates = [num for num, count in counts.items() if count > 1]
duplicates.sort()
return duplicates | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of integers `arr`, return a list containing all the elements of `arr` that appear more than once, sorted in ascending order. Each element in the resulting list should appear only once.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3428,
"level": 1,
"question": "Given a list of integers `arr`, return a list containing all the elements of `arr` that appear more than once, sorted in ascending order. Each element in the resulting list should appear only once.",
"split": "train"
} |
import re
def summarize_paragraph(paragraph: str) -> list:
# Extract sentences ending with .!? and strip whitespace
sentences = re.findall(r'([^.!?]*[.!?])', paragraph.strip())
# Remove any empty strings and strip leading/trailing whitespace from each sentence
sentences = [s.strip() for s in sentences ... | simplelr_Package | [
{
"content": "Question:\n**Objective**: The goal of this problem is to deepen your understanding of string manipulation and basic list operations in Python.\n\nYou are required to write a function named `summarize_paragraph` that performs the following steps:\n\n1. Takes a paragraph as input, which is a string ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3429,
"level": 1,
"question": "**Objective**: The goal of this problem is to deepen your understanding of string manipulation and basic list operations in Python.\n\nYou are required to write a function named `summarize_paragraph` that performs the following steps:\n\n1. Takes a par... |
def longest_distinct_substring_length(s):
left = 0
max_len = 0
char_dict = {}
for right in range(len(s)):
char = s[right]
if char in char_dict and char_dict[char] >= left:
left = char_dict[char] + 1
char_dict[char] = right
current_length = right - left + 1
... | simplelr_Code_Contests | [
{
"content": "Question:\nCreate a function that takes a string consisting of lowercase English letters and returns the length of the longest substring with all distinct characters.\n\nInput\n\nThe input is a single string s (1 ≤ length of s ≤ 10,000).\n\nOutput\n\nThe output is a single integer representing the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3430,
"level": 1,
"question": "Create a function that takes a string consisting of lowercase English letters and returns the length of the longest substring with all distinct characters.\n\nInput\n\nThe input is a single string s (1 ≤ length of s ≤ 10,000).\n\nOutput\n\nThe output i... |
import re
def version_to_hex(version: str) -> str:
# Parse the version string into components
match = re.match(r'^(\d+)\.(\d+)\.(\d+)(.*)$', version)
x_str, y_str, z_str, suffix = match.groups()
# Convert to integers and validate
x = int(x_str)
y = int(y_str)
z = int(z_str)
fo... | simplelr_Docs | [
{
"content": "Question:\n**Python Version Encoding**\n\nIn this exercise, you will write a function that parses a version string and outputs its hexadecimal representation according to the CPython versioning scheme as described.\n\n### Task\n\nCreate a function `version_to_hex(version: str) -> str` that takes a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3431,
"level": 1,
"question": "**Python Version Encoding**\n\nIn this exercise, you will write a function that parses a version string and outputs its hexadecimal representation according to the CPython versioning scheme as described.\n\n### Task\n\nCreate a function `version_to_hex... |
def is_valid_triangle(a, b, c):
if a <= 0 or b <= 0 or c <= 0:
return False
sides = sorted([a, b, c])
return sides[0] + sides[1] > sides[2] | simplelr_Leetcode | [
{
"content": "Question:\nYou are given three integers `a`, `b`, and `c`, representing the sides of a triangle. Determine if the given sides form a valid triangle. A triangle is valid if the sum of any two sides is greater than the third side. Return `true` if the triangle is valid, and `false` otherwise.\nAnswe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3432,
"level": 1,
"question": "You are given three integers `a`, `b`, and `c`, representing the sides of a triangle. Determine if the given sides form a valid triangle. A triangle is valid if the sum of any two sides is greater than the third side. Return `true` if the triangle is v... |
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n - 1) | simplelr_Filter | [
{
"content": "Question:\nI'm a beginner programmer struggling to understand recursion.\n\nCan you help me understand recursion with a simple example?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3433,
"level": 1,
"question": "I'm a beginner programmer struggling to understand recursion.\n\nCan you help me understand recursion with a simple example?",
"split": "train"
} |
def sum_of_digits(n):
num = abs(n)
sum_digits = 0
while num > 0:
sum_digits += num % 10
num = num // 10
return sum_digits | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts a single integer and returns the sum of its digits.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3434,
"level": 1,
"question": "Create a function that accepts a single integer and returns the sum of its digits.",
"split": "train"
} |
def find_unique_triples(arr, target):
arr.sort()
result = []
n = len(arr)
for i in range(n - 2):
# Skip duplicates for the first element
if i > 0 and arr[i] == arr[i-1]:
continue
left = i + 1
right = n - 1
while left < right:
current_sum = ... | simplelr_Filter | [
{
"content": "Question:\nI have an array of integers, and I want to generate all possible triples from the array such that the sum of the three elements is equal to a given target value. For example, if my array is [1, 2, 3, 4, 5] and the target value is 6, the triples would be [(1, 2, 3), (1, 3, 2), (2, 1, 3),... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3435,
"level": 1,
"question": "I have an array of integers, and I want to generate all possible triples from the array such that the sum of the three elements is equal to a given target value. For example, if my array is [1, 2, 3, 4, 5] and the target value is 6, the triples would b... |
def find_palindromes(lst):
return [s for s in lst if s == s[::-1]] | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a list of strings and returns a new list containing only the strings that are palindromes. A palindrome is a word that reads the same backward as forward, e.g., 'madam' or 'racecar'. Ensure your function is efficient and concise. Additionally, include... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3436,
"level": 1,
"question": "Create a Python function that takes a list of strings and returns a new list containing only the strings that are palindromes. A palindrome is a word that reads the same backward as forward, e.g., 'madam' or 'racecar'. Ensure your function is efficient... |
def findPairWithDifference(arr, K):
if K == 0:
seen = set()
for num in arr:
if num in seen:
return True
seen.add(num)
return False
else:
s = set(arr)
for x in arr:
if (x - K) in s or (x + K) in s:
return ... | simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers and a target integer 'K'. The task is to find whether there are two distinct indices i and j in the array such that the absolute difference between the elements at those indices is exactly K. If such a pair exists, return true; otherwise, return false.\n\nExam... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3437,
"level": 1,
"question": "Given an array of integers and a target integer 'K'. The task is to find whether there are two distinct indices i and j in the array such that the absolute difference between the elements at those indices is exactly K. If such a pair exists, return tru... |
def group_characters(s, k=3):
return '-'.join([s[i:i+k] for i in range(0, len(s), k)]) | simplelr_Filter | [
{
"content": "Question:\nImplement a function `group_characters` that accepts a string and an integer `k` and returns a list of substrings. Each substring should consist of `k` consecutive characters from the original string, with the exception of the last substring, which may be shorter if the string length is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3438,
"level": 1,
"question": "Implement a function `group_characters` that accepts a string and an integer `k` and returns a list of substrings. Each substring should consist of `k` consecutive characters from the original string, with the exception of the last substring, which may... |
from typing import List
def count_distinct_integers(arr: List[int]) -> int:
return len(set(arr)) | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\n\nA company needs an efficient way to evaluate the number of distinct integers present in a list of numbers. This helps them in analyzing data redundancy and creating unique identifiers.\n\n### Problem Statement\n\nWrite a function `count_distinct_integers(arr: List[int]) ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3439,
"level": 1,
"question": "### Scenario\n\nA company needs an efficient way to evaluate the number of distinct integers present in a list of numbers. This helps them in analyzing data redundancy and creating unique identifiers.\n\n### Problem Statement\n\nWrite a function `count... |
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_Code_Contests | [
{
"content": "Question:\n**Problem**\n\nYou are given an integer array `nums` sorted in non-decreasing order. Write a function that removes the duplicates in-place such that each element appears only once and returns the new length of the array. Do not allocate extra space for another array; you must modify the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3440,
"level": 1,
"question": "**Problem**\n\nYou are given an integer array `nums` sorted in non-decreasing order. Write a function that removes the duplicates in-place such that each element appears only once and returns the new length of the array. Do not allocate extra space for... |
def ackermann(m, n):
if m == 0:
return n + 1
elif m > 0 and n == 0:
return ackermann(m - 1, 1)
else:
return ackermann(m - 1, ackermann(m, n - 1)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to implement the Ackermann function in Python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3441,
"level": 1,
"question": "Write a function to implement the Ackermann function in Python.",
"split": "train"
} |
def max_priority_tasks(T, tasks):
# Filter all tasks that can't be completed within T
filtered_tasks = [(s, d, p) for (s, d, p) in tasks if s + d <= T]
# Sort the filtered tasks by their end time (s + d)
filtered_tasks.sort(key=lambda x: x[0] + x[1])
m = len(filtered_tasks)
if m == 0:
... | simplelr_Codeforces | [
{
"content": "Question:\nImagine you are designing a new operating system for a computer that prioritizes the execution of tasks based on their importance. Each task is defined by a start time, a duration, and a priority level. The operating system must select and execute tasks in such a way that maximizes the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3442,
"level": 1,
"question": "Imagine you are designing a new operating system for a computer that prioritizes the execution of tasks based on their importance. Each task is defined by a start time, a duration, and a priority level. The operating system must select and execute task... |
def totalGoalAchieved(transactions):
return round(sum(percentage for price, percentage in transactions), 2) | simplelr_Apps | [
{
"content": "Question:\n## Story\n\nSarah likes to organize charity events, where she sells baked goods to raise funds. She keeps track of these events using lists of transactions. Each transaction is represented as a pair, where the first element is the price of a baked good, and the second element indicates ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3443,
"level": 1,
"question": "## Story\n\nSarah likes to organize charity events, where she sells baked goods to raise funds. She keeps track of these events using lists of transactions. Each transaction is represented as a pair, where the first element is the price of a baked good... |
def min_path_sum(grid):
n = len(grid)
if n == 0:
return 0
# Initialize the previous DP array with the first row's cumulative sum
prev_dp = [0] * n
prev_dp[0] = grid[0][0]
for j in range(1, n):
prev_dp[j] = prev_dp[j-1] + grid[0][j]
# Iterate through each row starting fro... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a square matrix `grid` of size `n x n` consisting of non-negative integers. You initially start at the top-left corner of the matrix (i.e., `grid[0][0]`). Your goal is to move to the bottom-right corner of the matrix (i.e., `grid[n-1][n-1]`). You can only move either right... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3444,
"level": 1,
"question": "You are given a square matrix `grid` of size `n x n` consisting of non-negative integers. You initially start at the top-left corner of the matrix (i.e., `grid[0][0]`). Your goal is to move to the bottom-right corner of the matrix (i.e., `grid[n-1][n-1... |
def to_uppercase(input_string):
return input_string.upper() | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert all the lowercase letters in a string to uppercase.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3445,
"level": 1,
"question": "Write a python function to convert all the lowercase letters in a string to uppercase.",
"split": "train"
} |
from typing import List, Tuple
def process_strings(strings: List[str]) -> Tuple[List[str], int, int]:
processed_strings = []
for s in strings:
reversed_s = s[::-1]
if 'a' not in reversed_s:
processed_strings.append(reversed_s)
concatenated = ''.join(processed_strings)
length... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\nImplement a function that processes a list of strings and performs various operations based on predefined rules.\n\n#### Problem Statement\nYou are given a list of strings. Your task is to implement a function `process_strings(strings: List[str]) -> Tuple[List[str], int,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3446,
"level": 1,
"question": "#### Objective\nImplement a function that processes a list of strings and performs various operations based on predefined rules.\n\n#### Problem Statement\nYou are given a list of strings. Your task is to implement a function `process_strings(strings: ... |
import torch
def tensor_attribute_manipulation(x: torch.Tensor, dtype_str: str, device_str: str = "cpu") -> tuple:
# Define allowed data types and check validity
allowed_dtypes = {'float32', 'float64', 'int32', 'int64', 'bool'}
if dtype_str not in allowed_dtypes:
raise ValueError(f"Invalid dtype_st... | simplelr_Docs | [
{
"content": "Question:\n**PyTorch Tensor Attribute Manipulation**\n\n**Problem Statement:**\n\nIn this task, you will implement a function in PyTorch that manipulates the attributes of Tensors. Specifically, you need to write a function `tensor_attribute_manipulation` that does the following:\n\n* Takes in thr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3447,
"level": 1,
"question": "**PyTorch Tensor Attribute Manipulation**\n\n**Problem Statement:**\n\nIn this task, you will implement a function in PyTorch that manipulates the attributes of Tensors. Specifically, you need to write a function `tensor_attribute_manipulation` that do... |
def reverse_and_count_vowels(s):
reversed_str = s[::-1]
vowel_count = 0
vowels = {'a', 'e', 'i', 'o', 'u'}
for char in s:
if char.lower() in vowels:
vowel_count += 1
return (reversed_str, vowel_count) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and returns a tuple containing the string in reverse order and a count of the number of vowels in the string. The function should consider both uppercase and lowercase vowels.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3448,
"level": 1,
"question": "Create a function that takes a string as input and returns a tuple containing the string in reverse order and a count of the number of vowels in the string. The function should consider both uppercase and lowercase vowels.",
"split": "train"
} |
def sumMiddle(B, n):
return B[(n//2 - 1)] + B[n//2]
| simplelr_Taco | [
{
"content": "Question:\nGiven an array B[] of n integers where n is even. The task is to find sum of the middle two elements of the array.\n\nExample 1:\nInput:\nn = 6\nB[] = {1, 2, 3, 4, 5, 6}\nOutput:\n7\nExplanation:\nThe middle two elements are 3 and 4, and their sum is 7.\n\nExample 2:\nInput:\nn = 4\nB[]... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3449,
"level": 1,
"question": "Given an array B[] of n integers where n is even. The task is to find sum of the middle two elements of the array.\n\nExample 1:\nInput:\nn = 6\nB[] = {1, 2, 3, 4, 5, 6}\nOutput:\n7\nExplanation:\nThe middle two elements are 3 and 4, and their sum is 7... |
def longest_balanced_subsequence(s):
count0 = s.count('0')
count1 = s.count('1')
return 2 * min(count0, count1) | simplelr_Leetcode | [
{
"content": "Question:\nA binary string is a string that only contains `0`s and `1`s. You are given a binary string `s` consisting of `n` characters. A subsequence is derived by deleting some or no characters of `s` without changing the order of the remaining characters. The binary string `s` is **balanced** i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3450,
"level": 1,
"question": "A binary string is a string that only contains `0`s and `1`s. You are given a binary string `s` consisting of `n` characters. A subsequence is derived by deleting some or no characters of `s` without changing the order of the remaining characters. The ... |
from typing import List, Tuple
def merge_intervals_and_find_gaps(intervals: List[Tuple[int, int]]) -> Tuple[List[Tuple[int, int]], List[Tuple[int, int]]]:
if not intervals:
return [], []
# Sort intervals by the starting point
intervals.sort(key=lambda x: x[0])
merged_intervals = [interval... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n**Title**: Merge Intervals and Find Gaps\n\n**Task**:\nUsing the provided dataset of intervals, implement a function to merge overlapping intervals and then find the gaps between these intervals. The function should return a list of the merged intervals... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3451,
"level": 1,
"question": "### Coding Assessment Question\n\n**Title**: Merge Intervals and Find Gaps\n\n**Task**:\nUsing the provided dataset of intervals, implement a function to merge overlapping intervals and then find the gaps between these intervals. The function should re... |
import bisect
def first_negative_in_window(arr, k):
n = len(arr)
result = []
negative_indices = [i for i, x in enumerate(arr) if x < 0]
for start in range(n - k + 1):
L = start
R = L + k - 1
# Find the first negative index in the current window
pos = bisect.bisect_left(n... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program to find the first negative integer in each window of size `k` in an array `arr`. If there is no negative integer in the current window, return 0 for that window.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3452,
"level": 1,
"question": "Write a Python program to find the first negative integer in each window of size `k` in an array `arr`. If there is no negative integer in the current window, return 0 for that window.",
"split": "train"
} |
def count_vowels_and_consonants(s):
vowels = 0
consonants = 0
for char in s:
if char.isalpha():
lower_char = char.lower()
if lower_char in {'a', 'e', 'i', 'o', 'u'}:
vowels += 1
else:
consonants += 1
return {'vowels': vowels, 'c... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the number of vowels in a given string, and the number of consonants. Return the result as a dictionary where the keys are 'vowels' and 'consonants'.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3453,
"level": 1,
"question": "Create a function that calculates the number of vowels in a given string, and the number of consonants. Return the result as a dictionary where the keys are 'vowels' and 'consonants'.",
"split": "train"
} |
def is_balanced(expression: str) -> bool:
stack = []
bracket_map = {')': '(', ']': '['}
for char in expression:
if char in ['(', '[']:
stack.append(char)
elif char in [')', ']']:
if not stack:
return False
top = stack.pop()
if b... | simplelr_Apps | [
{
"content": "Question:\nImplement a function that solves the following problem:\n\nYou are given a string containing a mathematical expression that consists of only two types of brackets: square brackets `[]` and round brackets `()`. Your task is to determine if the expression is balanced. An expression is bal... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3454,
"level": 1,
"question": "Implement a function that solves the following problem:\n\nYou are given a string containing a mathematical expression that consists of only two types of brackets: square brackets `[]` and round brackets `()`. Your task is to determine if the expressio... |
import re
import compileall
def custom_compile(dir_path, max_depth, exclude_pattern, optimize, force, quiet):
if optimize not in [0, 1, 2]:
if quiet != 2:
print("Error: Invalid optimization level!")
raise ValueError("Invalid optimization level! Must be 0, 1, or 2.")
try:
... | simplelr_Docs | [
{
"content": "Question:\n### Question: Compiling Python Files with Custom Rules\n\n#### Background\n\nYou are provided with a directory containing several Python source files and sub-directories. Your task is to compile these files into byte-code using custom rules. The \"compileall\" module will help you accom... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3455,
"level": 1,
"question": "### Question: Compiling Python Files with Custom Rules\n\n#### Background\n\nYou are provided with a directory containing several Python source files and sub-directories. Your task is to compile these files into byte-code using custom rules. The \"comp... |
def longest_consecutive_char(s):
if not s:
return ""
max_length = 1
max_char = s[0]
current_length = 1
current_char = s[0]
for c in s[1:]:
if c == current_char:
current_length += 1
else:
if current_length > max_length:
max... | simplelr_Filter | [
{
"content": "Question:\nReceive as input a sequence of characters and output the longest consecutive set of identical characters found in the string. Additionally, if there's a tie between multiple characters, return the one that appeared first in the string. You need to calculate the longest streak, by proces... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3456,
"level": 1,
"question": "Receive as input a sequence of characters and output the longest consecutive set of identical characters found in the string. Additionally, if there's a tie between multiple characters, return the one that appeared first in the string. You need to calc... |
from collections import Counter
def k_most_frequent_elements(nums, k):
count = Counter(nums)
elements = list(count.keys())
elements.sort(key=lambda x: (-count[x], x))
return elements[:k] | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function to find the k most frequent elements in a given list of integers. The function should return the elements in descending order of their frequency. If two elements have the same frequency, return them in ascending order. The function should optimize for time comple... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3457,
"level": 1,
"question": "Write a Python function to find the k most frequent elements in a given list of integers. The function should return the elements in descending order of their frequency. If two elements have the same frequency, return them in ascending order. The funct... |
from typing import List, Tuple
def search_in_sorted_matrix(mat: List[List[int]], target: int) -> Tuple[int, int]:
if not mat or not mat[0]:
return (-1, -1)
rows = len(mat)
cols = len(mat[0])
i, j = 0, cols - 1
while i < rows and j >= 0:
current = mat[i][j]
if current == targ... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Objective:\nGiven a matrix that is sorted in non-decreasing order both row-wise and column-wise, write a function to locate a target key within the matrix.\n\n#### Task:\nImplement the function `search_in_sorted_matrix(mat, target)`. \n\n#### Function Signature:\n```python\ndef sea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3458,
"level": 1,
"question": "#### Objective:\nGiven a matrix that is sorted in non-decreasing order both row-wise and column-wise, write a function to locate a target key within the matrix.\n\n#### Task:\nImplement the function `search_in_sorted_matrix(mat, target)`. \n\n#### Func... |
def sum_of_cubes(start, end):
if not isinstance(start, int) or not isinstance(end, int):
return "Both start and end parameters must be integers"
if start > end:
return "Start number cannot be greater than end number"
sum_cubes = 0
for num in range(start, end + 1):
sum_cubes += nu... | simplelr_Filter | [
{
"content": "Question:\nCreate a function in Python that takes two parameters, start and end, and returns the sum of the cubes of all numbers between them. If the start parameter is greater than the end parameter, return an error message stating \"Start number cannot be greater than end number\". If any of the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3459,
"level": 1,
"question": "Create a function in Python that takes two parameters, start and end, and returns the sum of the cubes of all numbers between them. If the start parameter is greater than the end parameter, return an error message stating \"Start number cannot be great... |
def deep_reverse(collection):
if isinstance(collection, (list, tuple)):
reversed_collection = []
for i in range(len(collection)-1, -1, -1):
element = collection[i]
if isinstance(element, (list, tuple, set)):
reversed_element = deep_reverse(element)
... | simplelr_Filter | [
{
"content": "Question:\nCreate a function to deeply reverse an input list, meaning that it reverses the order of the elements in the list, as well as reversing the order of the elements in any nested lists within it. Additionally, modify the function to handle tuples and sets within the input list by reversing... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3460,
"level": 1,
"question": "Create a function to deeply reverse an input list, meaning that it reverses the order of the elements in the list, as well as reversing the order of the elements in any nested lists within it. Additionally, modify the function to handle tuples and sets... |
def manage_inventory(operations: list) -> list:
"""
Manage the inventory of a bookstore based on the operations provided.
Parameters:
operations (list): List of operations to perform on the inventory
Returns:
list: List of books matching search criteria when a search operation is requested
... | simplelr_Package | [
{
"content": "Question:\nYou are given a task to implement a system that handles the inventory management of a bookstore. The primary function of this system should be to add new books, update the inventory for existing books, and search for books based on different criteria.\n\nYour function should be called `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3461,
"level": 1,
"question": "You are given a task to implement a system that handles the inventory management of a bookstore. The primary function of this system should be to add new books, update the inventory for existing books, and search for books based on different criteria.\... |
def can_form_palindrome(s: str) -> bool:
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
odd_count = 0
for count in freq.values():
if count % 2 != 0:
odd_count += 1
if len(s) % 2 == 0:
return... | simplelr_Taco | [
{
"content": "Question:\nGiven a string consisting of lowercase English letters, determine if it can be permuted to form a palindrome. \n\nA string is said to be a palindrome if it reads the same backward as forward. For example, `\"madam\"` and `\"racecar\"` are palindromes, while `\"hello\"` is not.\n\nWrite ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3462,
"level": 1,
"question": "Given a string consisting of lowercase English letters, determine if it can be permuted to form a palindrome. \n\nA string is said to be a palindrome if it reads the same backward as forward. For example, `\"madam\"` and `\"racecar\"` are palindromes, ... |
def group_and_sort_sums(numbers):
if not numbers:
return []
groups = []
current_group = [numbers[0]]
for num in numbers[1:]:
if num == current_group[-1] + 1:
current_group.append(num)
else:
groups.append(current_group)
current_group =... | simplelr_Package | [
{
"content": "Question:\nYou are developing a function to process a list of integers by grouping consecutive numbers into sublists. Consecutive numbers are numbers that appear one right after the other in the sequence. After grouping, you need to find all unique sums of these groups and return them in a sorted ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3463,
"level": 1,
"question": "You are developing a function to process a list of integers by grouping consecutive numbers into sublists. Consecutive numbers are numbers that appear one right after the other in the sequence. After grouping, you need to find all unique sums of these ... |
import re
def reverse_string(s):
tokens = re.findall(r'\S+', s)
words = [t for t in tokens if any(c.isalnum() for c in t)]
reversed_words = words[::-1]
return ' '.join(reversed_words)
| simplelr_Taco | [
{
"content": "Question:\nGiven a string containing a mixture of letters, digits, and punctuation marks, write a function that formats the string as follows:\n\nRequirements:\n1) Reverse the order of the words in the string while maintaining the original word order of characters within each word.\n2) Punctuation... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3464,
"level": 1,
"question": "Given a string containing a mixture of letters, digits, and punctuation marks, write a function that formats the string as follows:\n\nRequirements:\n1) Reverse the order of the words in the string while maintaining the original word order of character... |
def is_balanced(sequence):
stack = []
bracket_map = {')': '(', '}': '{', ']': '['}
for char in sequence:
if char in ['(', '{', '[']:
stack.append(char)
elif char in bracket_map:
if not stack:
return False
top = stack.pop()
if to... | simplelr_Taco | [
{
"content": "Question:\nYou are given a string that contains a sequence of characters. Your task is to write a function that determines whether the sequence of characters contains balanced brackets. The brackets considered in this problem are `()`, `{}`, and `[]`. The sequence is said to be balanced if every o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3465,
"level": 1,
"question": "You are given a string that contains a sequence of characters. Your task is to write a function that determines whether the sequence of characters contains balanced brackets. The brackets considered in this problem are `()`, `{}`, and `[]`. The sequenc... |
def count_pairs_with_sum(arr, target):
count = 0
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
if arr[i] + arr[j] == target:
count += 1
return count | simplelr_Apps | [
{
"content": "Question:\n# Task\nGiven an array of integers and a target sum, find the number of pairs of integers in the array that add up to the target sum. Each pair must be made of two different elements, but elements may be repeated in different pairs.\n\n# Example\n\nFor `arr = [1, 2, 3, 4, 3]` and `targe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3466,
"level": 1,
"question": "# Task\nGiven an array of integers and a target sum, find the number of pairs of integers in the array that add up to the target sum. Each pair must be made of two different elements, but elements may be repeated in different pairs.\n\n# Example\n\nFor... |
def rle_compress(s: str) -> str:
if not s:
return s
current_char = s[0]
count = 1
result = []
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(current_char + str(count))
current_char = char
co... | simplelr_Algorithm | [
{
"content": "Question:\n### String Compression Algorithm Implementation\n\nYou are tasked with implementing a simple lossless string compression algorithm that takes a string and encodes it using the Run-Length Encoding (RLE) technique. The RLE algorithm compresses repetitive sequences of characters by storing... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3467,
"level": 1,
"question": "### String Compression Algorithm Implementation\n\nYou are tasked with implementing a simple lossless string compression algorithm that takes a string and encodes it using the Run-Length Encoding (RLE) technique. The RLE algorithm compresses repetitive... |
import heapq
def min_path_cost(grid):
if not grid or not grid[0]:
return 0
n = len(grid)
m = len(grid[0])
INF = float('inf')
dist = [[INF for _ in range(m)] for _ in range(n)]
dist[0][0] = grid[0][0]
heap = []
heapq.heappush(heap, (grid[0][0], 0, 0))
direction... | simplelr_Apps | [
{
"content": "Question:\n# Task\nYou are given a grid of numbers where each cell contains a non-negative integer. You can move from one cell to another if they are adjacent horizontally or vertically. Each move to an adjacent cell adds the cell's value to your total cost of the path. Your goal is to find the mi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3468,
"level": 1,
"question": "# Task\nYou are given a grid of numbers where each cell contains a non-negative integer. You can move from one cell to another if they are adjacent horizontally or vertically. Each move to an adjacent cell adds the cell's value to your total cost of th... |
def are_parentheses_balanced(s):
stack = []
closing_to_opening = {')': '(', '}': '{', ']': '['}
for char in s:
if char in closing_to_opening.values():
stack.append(char)
elif char in closing_to_opening:
if not stack:
return False
top = stac... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that checks if the parentheses in a given string are balanced. The function should return `True` if the string is balanced (every opening parenthesis has a corresponding closing parenthesis in the correct order) and `False` otherwise. The function should be able ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3469,
"level": 1,
"question": "Write a Python function that checks if the parentheses in a given string are balanced. The function should return `True` if the string is balanced (every opening parenthesis has a corresponding closing parenthesis in the correct order) and `False` othe... |
def find_odd_number(numbers):
for num in numbers:
if num % 2 != 0:
return num
return None | simplelr_Filter | [
{
"content": "Question:\ndef find_odd_number(numbers):\n for num in numbers:\n if num % 2 != 0:\n return num\n return None\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3470,
"level": 1,
"question": "def find_odd_number(numbers):\n for num in numbers:\n if num % 2 != 0:\n return num\n return None",
"split": "train"
} |
def maxVisibleStudents(heights):
max_height = 0
count = 0
for h in heights:
if h > max_height:
count += 1
max_height = h
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array `heights` representing the heights of students in a class, where `heights[i]` is the height of the `i-th` student. Implement the function `maxVisibleStudents(height)` that returns the maximum number of students visible from the front of the class. A student at ind... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3471,
"level": 1,
"question": "You are given an array `heights` representing the heights of students in a class, where `heights[i]` is the height of the `i-th` student. Implement the function `maxVisibleStudents(height)` that returns the maximum number of students visible from the f... |
def square_list(number_list):
return list(map(lambda x: x ** 2, number_list)) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of numbers and returns a new list where each element is the square of the original element. The function should be named `square_list` and should not use any loops or list comprehensions. Instead, it should utilize the `map` function along with ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3472,
"level": 1,
"question": "Write a Python function that takes a list of numbers and returns a new list where each element is the square of the original element. The function should be named `square_list` and should not use any loops or list comprehensions. Instead, it should uti... |
def compute_totients(nums):
if not nums:
return []
max_n = max(nums)
if max_n < 2:
return [1] * len(nums)
max_sieve = max_n
spf = list(range(max_sieve + 1))
for i in range(2, int(max_sieve ** 0.5) + 1):
if spf[i] == i: # i is a prime number
for... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Compute Totient Function for an Array of Numbers\n\nYou have been given an array of integers. Your task is to implement a function that calculates Euler's Totient function (ϕ-function) for each number in the array.\n\n### Function Specification\n\n#### Function Name\n`comp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3473,
"level": 1,
"question": "### Question: Compute Totient Function for an Array of Numbers\n\nYou have been given an array of integers. Your task is to implement a function that calculates Euler's Totient function (ϕ-function) for each number in the array.\n\n### Function Specifi... |
def has_vowel(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
return any(c in vowels for c in s.lower()) | simplelr_Filter | [
{
"content": "Question:\nHere is the python code that takes a string as input and returns True if there is at least one vowel present, otherwise it returns False.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3474,
"level": 1,
"question": "Here is the python code that takes a string as input and returns True if there is at least one vowel present, otherwise it returns False.",
"split": "train"
} |
def poker_hand_rank(cards):
rank_map = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,
'8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}
ranks = []
suits = []
for card in cards:
r = card[0]
s = card[1]
ranks.append(rank_map[r])
suits.appe... | simplelr_Apps | [
{
"content": "Question:\nCreate a function `poker_hand_rank` that takes a list of 5 cards represented as strings and returns a string indicating the rank of the poker hand.\n\nEach card string will be in the format \"RS\", where:\n- R is the rank of the card, from \"2\" to \"9\" for numbered cards, and \"T\", \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3475,
"level": 1,
"question": "Create a function `poker_hand_rank` that takes a list of 5 cards represented as strings and returns a string indicating the rank of the poker hand.\n\nEach card string will be in the format \"RS\", where:\n- R is the rank of the card, from \"2\" to \"9... |
def check_binary_ones(x, y):
count_x = bin(x).count('1')
count_y = bin(y).count('1')
if count_x == count_y:
return min(x, y)
else:
return -1 | simplelr_Filter | [
{
"content": "Question:\nComplete the code segment provided below. In doing so, you are to take two positive integers, represented as x and y, as inputs. The goal is to figure out whether the binary representation of these integers contains an equal number of 1's. If it does, you should return the number which ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3476,
"level": 1,
"question": "Complete the code segment provided below. In doing so, you are to take two positive integers, represented as x and y, as inputs. The goal is to figure out whether the binary representation of these integers contains an equal number of 1's. If it does, ... |
def multiply(num1: str, num2: str) -> str:
if num1 == "0" or num2 == "0":
return "0"
# Reverse the numbers to process from least significant digit
num1_reversed = num1[::-1]
num2_reversed = num2[::-1]
n1, n2 = len(num1_reversed), len(num2_reversed)
res = [0] * (n1 + n2)
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Large Integer Multiplication\n\nGiven two non-negative integers `num1` and `num2` represented as strings, write a function `multiply(num1: str, num2: str) -> str` that returns the product of `num1` and `num2` as a string.\n\n**Constraints**:\n- The length of both `num1` and `num2` i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3477,
"level": 1,
"question": "### Large Integer Multiplication\n\nGiven two non-negative integers `num1` and `num2` represented as strings, write a function `multiply(num1: str, num2: str) -> str` that returns the product of `num1` and `num2` as a string.\n\n**Constraints**:\n- The... |
def count_max_occurrences(lst):
if not lst:
return 0
max_val = max(lst)
return lst.count(max_val) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns the number of times the maximum value appears in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3478,
"level": 1,
"question": "Create a function that takes a list of integers and returns the number of times the maximum value appears in the list.",
"split": "train"
} |
def check_string(main_str, other_str, ignore_case=False):
# Strip leading and trailing whitespace from both strings
stripped_main = main_str.strip()
stripped_other = other_str.strip()
# Convert to lowercase if case should be ignored
if ignore_case:
stripped_main = stripped_main.lower()
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes two strings and an optional language parameter. The function should return True if the first string starts with the second or if the first string ends with the second, after potentially removing leading and trailing white spaces and casing differences.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3479,
"level": 1,
"question": "Write a Python function that takes two strings and an optional language parameter. The function should return True if the first string starts with the second or if the first string ends with the second, after potentially removing leading and trailing w... |
def sum_of_products(array1: list[int], array2: list[int]) -> int:
return sum(a * b for a, b in zip(array1, array2)) | simplelr_Algorithm | [
{
"content": "Question:\n### Parallel Array Traversal\n\n**Scenario**: Imagine you are given two parallel arrays of equal length containing numerical data. Your task is to write a function that traverses these arrays simultaneously and calculates the sum of products of their corresponding elements. Additionally... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3480,
"level": 1,
"question": "### Parallel Array Traversal\n\n**Scenario**: Imagine you are given two parallel arrays of equal length containing numerical data. Your task is to write a function that traverses these arrays simultaneously and calculates the sum of products of their c... |
def longest_overlap(timeSeries1, timeSeries2):
# Compute the intersection of the two time series
i = j = 0
intersection = []
while i < len(timeSeries1) and j < len(timeSeries2):
if timeSeries1[i] == timeSeries2[j]:
intersection.append(timeSeries1[i])
i += 1
j ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two **0-indexed** integer arrays `timeSeries1` and `timeSeries2` representing the time series data of two sensors. The sensors record data points at non-negative integer times and the arrays are sorted in non-decreasing order. Each element in `timeSeries1` and `timeSeries2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3481,
"level": 1,
"question": "You are given two **0-indexed** integer arrays `timeSeries1` and `timeSeries2` representing the time series data of two sensors. The sensors record data points at non-negative integer times and the arrays are sorted in non-decreasing order. Each elemen... |
def longest_palindrome(s):
if not s:
return ""
max_length = 0
start = 0
n = len(s)
for i in range(n):
# Check for odd length palindromes
l, r = i, i
while l >= 0 and r < n and s[l] == s[r]:
l -= 1
r += 1
current_length = r - l... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the longest palindrome in a given string. If there are multiple palindromes of the same maximum length, return the first one found. If no palindrome exists, return an empty string. The function should handle any string input, including those with special ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3482,
"level": 1,
"question": "Write a Python function to find the longest palindrome in a given string. If there are multiple palindromes of the same maximum length, return the first one found. If no palindrome exists, return an empty string. The function should handle any string i... |
def is_valid_parentheses(s):
if not s:
return True
if len(s) % 2 != 0:
return False
stack = []
for char in s:
if char == '(':
stack.append(char)
else:
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Apps | [
{
"content": "Question:\n## Valid Parentheses String\n\nA string containing only the characters `(` and `)` is considered valid if it meets the following criteria:\n1. Every opening parenthesis `(` has a corresponding closing parenthesis `)` and vice versa.\n2. An opening parenthesis must appear before its corr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3483,
"level": 1,
"question": "## Valid Parentheses String\n\nA string containing only the characters `(` and `)` is considered valid if it meets the following criteria:\n1. Every opening parenthesis `(` has a corresponding closing parenthesis `)` and vice versa.\n2. An opening pare... |
def sum_2d_array(arr):
return sum(sum(row) for row in arr) | simplelr_Filter | [
{
"content": "Question:\nwrite a function that takes in a 2D array and returns the sum of all the elements in the array. Ensure your function can handle arrays of varying sizes.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3484,
"level": 1,
"question": "write a function that takes in a 2D array and returns the sum of all the elements in the array. Ensure your function can handle arrays of varying sizes.",
"split": "train"
} |
def longest_consecutive_sequence(arr):
pos_set = {x for x in arr if x > 0}
max_length = 0
for x in pos_set:
if (x - 1) not in pos_set:
current = x
current_length = 1
while (current + 1) in pos_set:
current += 1
current_length += 1
... | simplelr_Filter | [
{
"content": "Question:\nWrite a code to find the maximum length of the longest consecutive sequence of integers in an array. The sequence must be strictly increasing and consist of positive integers only.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3485,
"level": 1,
"question": "Write a code to find the maximum length of the longest consecutive sequence of integers in an array. The sequence must be strictly increasing and consist of positive integers only.",
"split": "train"
} |
def rotate_matrix(matrix: list[list[int]]) -> None:
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse() | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Matrix Rotation\n\nYou are given an `n x n` 2D matrix representing an image. Rotate the image by 90 degrees (clockwise).\n\n### Implementation Details:\n\n- **Function Signature**: `def rotate_matrix(matrix: list[list[int]]) -> None:`\n- **Input**:\n - `matrix`: A list of... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3486,
"level": 1,
"question": "### Question: Matrix Rotation\n\nYou are given an `n x n` 2D matrix representing an image. Rotate the image by 90 degrees (clockwise).\n\n### Implementation Details:\n\n- **Function Signature**: `def rotate_matrix(matrix: list[list[int]]) -> None:`\n- ... |
def get_consecutive_differences(input_list):
return [y - x for x, y in zip(input_list, input_list[1:])] | simplelr_Evol | [
{
"content": "Question:\nCreate a Python function that takes a numerical list as input and returns a new list where each element is the difference between the consecutive elements of the original list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3487,
"level": 1,
"question": "Create a Python function that takes a numerical list as input and returns a new list where each element is the difference between the consecutive elements of the original list.",
"split": "train"
} |
def sum_of_squares(numbers):
total = 0
for number in numbers:
total += number ** 2
return total | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum of the squares of the elements in a given list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3488,
"level": 1,
"question": "Write a function to calculate the sum of the squares of the elements in a given list.",
"split": "train"
} |
import operator
def perform_calculations(operations: list) -> list:
mapping = {
'PyNumber_Add': operator.add,
'PyNumber_Subtract': operator.sub,
'PyNumber_Multiply': operator.mul,
'PyNumber_TrueDivide': operator.truediv,
'PyNumber_FloorDivide': operator.floordiv,
'Py... | simplelr_Docs | [
{
"content": "Question:\n### Python 310 PyNumber API Usage\n\n#### Background\n\nYou have been introduced to the \"PyNumber\" API in Python, which provides a set of functions to perform arithmetic and bitwise operations on objects that support numeric protocols, closely mimicking Python’s built-in operators and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3489,
"level": 1,
"question": "### Python 310 PyNumber API Usage\n\n#### Background\n\nYou have been introduced to the \"PyNumber\" API in Python, which provides a set of functions to perform arithmetic and bitwise operations on objects that support numeric protocols, closely mimick... |
def is_one_edit_away(s1: str, s2: str) -> bool:
len1, len2 = len(s1), len(s2)
if abs(len1 - len2) > 1:
return False
elif len1 == len2:
diff_count = 0
for i in range(len1):
if s1[i] != s2[i]:
diff_count += 1
if diff_count > 1:
... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that determines whether it is possible to transform one string into another string with a specific set of operations. The allowed operations are:\n\n1. Remove a character\n2. Add a character\n3. Replace a character\n\nGiven two strings, the function should return `True`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3490,
"level": 1,
"question": "Write a function that determines whether it is possible to transform one string into another string with a specific set of operations. The allowed operations are:\n\n1. Remove a character\n2. Add a character\n3. Replace a character\n\nGiven two strings... |
def maximum_profit(prices):
if not prices:
return 0 # Though the problem states the list has at least one element
max_profit = 0
min_price = prices[0]
for price in prices[1:]:
current_profit = price - min_price
if current_profit > max_profit:
max_profit = c... | simplelr_Taco | [
{
"content": "Question:\nImplement a function `maximum_profit(prices)` that takes as input a list of daily stock prices and returns the maximum profit that can be obtained from a single buy and sell transaction. The function should ensure the purchase happens before the sale.\n\nThe input list `prices` contains... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3491,
"level": 1,
"question": "Implement a function `maximum_profit(prices)` that takes as input a list of daily stock prices and returns the maximum profit that can be obtained from a single buy and sell transaction. The function should ensure the purchase happens before the sale.\... |
def find_maximum(numbers):
if not numbers:
return None
current_max = numbers[0]
for num in numbers[1:]:
if num > current_max:
current_max = num
return current_max | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the maximum element in a list of numbers. The function should be able to handle both positive and negative integers, including zero. The function should also handle cases where the list is empty, returning `None` in such cases. Additionally, ensure that t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3492,
"level": 1,
"question": "Write a Python function to find the maximum element in a list of numbers. The function should be able to handle both positive and negative integers, including zero. The function should also handle cases where the list is empty, returning `None` in such... |
def linear_search(lst, x):
comparisons = 0
for i in range(len(lst)):
comparisons += 1
if lst[i] == x:
return (i, comparisons)
return (-1, comparisons) | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function that takes a list of integers and an integer `x`, and returns the index of the first occurrence of `x` in the list using a linear search. If `x` is not found, the function should return -1. Additionally, ensure your function counts and returns the number of comp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3493,
"level": 1,
"question": "Design a Python function that takes a list of integers and an integer `x`, and returns the index of the first occurrence of `x` in the list using a linear search. If `x` is not found, the function should return -1. Additionally, ensure your function co... |
import keyword
def is_valid_identifier(identifier: str) -> bool:
if not identifier:
return False
if identifier[0].isdigit():
return False
for c in identifier:
if not (c.isalnum() or c == '_'):
return False
if keyword.iskeyword(identifier):
return False
re... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that checks if a given string is a valid identifier in Python.\n\nIn Python, a valid identifier must:\n1. Only contain alphanumeric characters (a-z, A-Z, 0-9) or underscores (_).\n2. Not start with a digit.\n3. Not be a reserved keyword.\n\nYour task is to implement the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3494,
"level": 1,
"question": "Write a function that checks if a given string is a valid identifier in Python.\n\nIn Python, a valid identifier must:\n1. Only contain alphanumeric characters (a-z, A-Z, 0-9) or underscores (_).\n2. Not start with a digit.\n3. Not be a reserved keywor... |
def limit_occurrences(lst, n):
counts = {}
result = []
for num in lst:
if num in counts:
if counts[num] < n:
result.append(num)
counts[num] += 1
else:
if n > 0:
result.append(num)
counts[num] = 1
retu... | simplelr_Data_Structure | [
{
"content": "Question:\n**Scenario**: You are working with a data stream where each element can appear at most a certain number of times. Your task is to write a function that processes this stream and ensures no element appears more than the specified number of times while preserving the order of elements.\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3495,
"level": 1,
"question": "**Scenario**: You are working with a data stream where each element can appear at most a certain number of times. Your task is to write a function that processes this stream and ensures no element appears more than the specified number of times while p... |
from typing import List
def interpolation_search(array: List[int], search_key: int) -> int:
low = 0
high = len(array) - 1
while low <= high:
# Check if all elements are the same
if array[low] == array[high]:
if array[low] == search_key:
return low
el... | simplelr_Data_Structure | [
{
"content": "Question:\n**Context**: \n\nYou are tasked to enhance a data retrieval system for a large e-commerce platform. The platform's product catalog is vast and involves searching within a sorted array of product IDs. To improve search efficiency, implement the Interpolation Search algorithm which is tai... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3496,
"level": 1,
"question": "**Context**: \n\nYou are tasked to enhance a data retrieval system for a large e-commerce platform. The platform's product catalog is vast and involves searching within a sorted array of product IDs. To improve search efficiency, implement the Interpol... |
def climb_stairs_optimized(steps: int) -> int:
"""
Determines the number of distinct ways to reach the top of the staircase using an optimized approach for space complexity.
:param steps: A positive integer representing the total number of steps in the staircase.
:return: An integer representing the nu... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Context:\nYou have been given the task of designing an exercise for a physical education class. This exercise involves climbing a staircase with a specific number of steps (a positive integer `steps`). Each time you move, you can choose to either climb 1 step or 2 steps. Your goal ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3497,
"level": 1,
"question": "#### Context:\nYou have been given the task of designing an exercise for a physical education class. This exercise involves climbing a staircase with a specific number of steps (a positive integer `steps`). Each time you move, you can choose to either ... |
def insertion_sort(arr: list[int]) -> list[int]:
"""
Sorts a list of ISBN numbers in non-decreasing order using the Insertion Sort algorithm.
Args:
arr (list[int]): The list to be sorted.
Returns:
list[int]: The sorted list.
"""
# Loop through each element starting from... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\n\nThe local library maintains a list of books ordered by their ISBN numbers, which is a unique identifier. To keep the bookshelves tidy, you need to sort this list periodically. The list may sometimes be nearly sorted, only requiring minimal adjustments. You decide to use ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3498,
"level": 1,
"question": "### Scenario\n\nThe local library maintains a list of books ordered by their ISBN numbers, which is a unique identifier. To keep the bookshelves tidy, you need to sort this list periodically. The list may sometimes be nearly sorted, only requiring mini... |
def remove_zeros(lst):
result = []
for element in lst:
if type(element) is int and element == 0:
continue
result.append(element)
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list as an argument and returns a new list with all zeros removed. If the input list is empty, the function should return an empty list. Consider a list can contain different types of elements, but only integer zeros should be removed.\nAnswer:\nLet'... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3499,
"level": 1,
"question": "Write a Python function that takes a list as an argument and returns a new list with all zeros removed. If the input list is empty, the function should return an empty list. Consider a list can contain different types of elements, but only integer zero... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.