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 csv
def csv_to_dict(filename):
data = {}
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
if row: # Ensure we don't add empty rows
key = row[0]
data[key] = row[1:]
return data | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that can convert a CSV file to a dictionary using Python. Each row in the CSV file should be a key in the dictionary, and the values should be the list of items in that row (except the first item, which is the key).\nAnswer:\nLet's think step by step.\n",
"role": "... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2900,
"level": 1,
"question": "Create a function that can convert a CSV file to a dictionary using Python. Each row in the CSV file should be a key in the dictionary, and the values should be the list of items in that row (except the first item, which is the key).",
"split": "trai... |
def findTripletSum(arr, N, K):
if N < 3:
return "NO"
arr.sort()
for i in range(N - 2):
left = i + 1
right = N - 1
while left < right:
current_sum = arr[i] + arr[left] + arr[right]
if current_sum == K:
return "YES"
elif curre... | simplelr_Taco | [
{
"content": "Question:\nYou are given an array of integers `arr` of size `N`, and a target integer `K`. Your task is to determine whether there exists three distinct elements `a`, `b`, and `c` in the array such that `a + b + c = K`.\n\nFormally, if you chose elements at indices `i`, `j`, and `k` of the array `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2901,
"level": 1,
"question": "You are given an array of integers `arr` of size `N`, and a target integer `K`. Your task is to determine whether there exists three distinct elements `a`, `b`, and `c` in the array such that `a + b + c = K`.\n\nFormally, if you chose elements at indic... |
def evaluate_equations(equations):
variables_order = []
values = {}
for equation in equations:
var_part, num_part = equation.split('=')
var = var_part.strip()
num = int(num_part.strip())
if var not in values:
variables_order.append(var)
values[var] = num
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of strings representing equations that each contain exactly one letter (`a-z`) on the left-hand side and an integer on the right-hand side. Each string is formatted as \"variable = integer\". Your task is to evaluate the equations and return a list of strings where ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2902,
"level": 1,
"question": "You are given a list of strings representing equations that each contain exactly one letter (`a-z`) on the left-hand side and an integer on the right-hand side. Each string is formatted as \"variable = integer\". Your task is to evaluate the equations ... |
def reverse_list(lst):
if lst is None or len(lst) <= 1:
return lst
start = 0
end = len(lst) - 1
while start < end:
lst[start], lst[end] = lst[end], lst[start]
start += 1
end -= 1
return lst | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse a list without using inbuilt functions such as slicing or reversed(). Write the function to handle an empty list and lists with a single element.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2903,
"level": 1,
"question": "Write a python function to reverse a list without using inbuilt functions such as slicing or reversed(). Write the function to handle an empty list and lists with a single element.",
"split": "train"
} |
def find_top_earner(employees):
top_earners = {}
for employee in employees:
department = employee['department']
current = {
'id': employee['id'],
'name': employee['name'],
'salary': employee['salary']
}
if department not in top_earners:
... | simplelr_Package | [
{
"content": "Question:\nYou're given a list of dictionaries representing multiple employees. Each dictionary contains the employee's unique `id`, their `name`, the `department` they work in, and their `salary`. Your task is to write a function named `find_top_earner` that identifies the employee with the highe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2904,
"level": 1,
"question": "You're given a list of dictionaries representing multiple employees. Each dictionary contains the employee's unique `id`, their `name`, the `department` they work in, and their `salary`. Your task is to write a function named `find_top_earner` that ide... |
def sum_elements(lst):
return sum(lst) | simplelr_Filter | [
{
"content": "Question:\nCan you write a Python function that calculates the sum of all elements in a given list of integers? The function should be named `sum_elements` and should take a single argument, which is a list of integers. If the list is empty, the function should return 0.\nAnswer:\nLet's think step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2905,
"level": 1,
"question": "Can you write a Python function that calculates the sum of all elements in a given list of integers? The function should be named `sum_elements` and should take a single argument, which is a list of integers. If the list is empty, the function should r... |
def find_diagonal_order(matrix: list[list[int]]) -> list[int]:
if not matrix or not matrix[0]:
return []
M = len(matrix)
N = len(matrix[0])
max_sum = (M - 1) + (N - 1)
result = []
for s in range(max_sum + 1):
diagonal = []
for r in range(s + 1):
c = ... | simplelr_Algorithm | [
{
"content": "Question:\n### Matrix Diagonal Traverse\n\n**Context**:\nGiven an `MxN` matrix, the goal is to return all elements of the matrix in a diagonal order. The diagonal order starts from the top-left corner of the matrix and alternates between moving upwards and downwards along the diagonals.\n\n**Objec... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2906,
"level": 1,
"question": "### Matrix Diagonal Traverse\n\n**Context**:\nGiven an `MxN` matrix, the goal is to return all elements of the matrix in a diagonal order. The diagonal order starts from the top-left corner of the matrix and alternates between moving upwards and downwa... |
def frequency_of_numbers(lst):
freq = {}
for num in lst:
freq[num] = freq.get(num, 0) + 1
return freq | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the frequency of a number in a given list. The function should return a dictionary where the key is the number and the value is the number of times it appears in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2907,
"level": 1,
"question": "Write a python function to find the frequency of a number in a given list. The function should return a dictionary where the key is the number and the value is the number of times it appears in the list.",
"split": "train"
} |
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif target < arr[mid]:
high = mid - 1
else:
low = mid + 1
return -1 # Target not found
# Exampl... | simplelr_Filter | [
{
"content": "Question:\nExplain the time complexity of a binary search algorithm and how it compares to linear search. Also, write a code snippet for binary search algorithm to search for an element in a sorted array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2908,
"level": 1,
"question": "Explain the time complexity of a binary search algorithm and how it compares to linear search. Also, write a code snippet for binary search algorithm to search for an element in a sorted array.",
"split": "train"
} |
import heapq
def dijkstra(graph, start_node):
"""
This function implements Dijkstra's algorithm to find the shortest paths from a given start node to all other nodes in a weighted, directed graph.
Args:
graph (dict): A dictionary representing the graph where keys are node names and values are dictiona... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\n**Context:**\nYou are required to implement a simplified version of the Dijkstra's shortest path algorithm. The algorithm should find the shortest paths from a given source vertex to all other vertices in a weighted, directed graph. Handle various edge cases lik... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2909,
"level": 1,
"question": "### Problem Statement\n\n**Context:**\nYou are required to implement a simplified version of the Dijkstra's shortest path algorithm. The algorithm should find the shortest paths from a given source vertex to all other vertices in a weighted, directed g... |
def letters_to_numbers(letters):
result = []
for letter in letters:
lower_letter = letter.lower()
pos = ord(lower_letter) - ord('a') + 1
result.append((letter, pos))
return result | simplelr_Filter | [
{
"content": "Question:\nGiven the input-output pair, where the input is a list of letters and the output is a list of tuples, each tuple containing a letter and its corresponding numerical value based on its position in the alphabet (1-indexed), write a Python function to solve this problem.\nAnswer:\nLet's th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2910,
"level": 1,
"question": "Given the input-output pair, where the input is a list of letters and the output is a list of tuples, each tuple containing a letter and its corresponding numerical value based on its position in the alphabet (1-indexed), write a Python function to sol... |
def balance_plants(S: str) -> int:
return len(set(S)) if S else 0 | simplelr_Apps | [
{
"content": "Question:\nYou've started a garden and planted seeds of various types of fruits and vegetables. Each plant in your garden is represented by a character indicating its type. Your goal is to determine the minimal number of unique plant types that must be present to ensure a balanced diversity in you... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2911,
"level": 1,
"question": "You've started a garden and planted seeds of various types of fruits and vegetables. Each plant in your garden is represented by a character indicating its type. Your goal is to determine the minimal number of unique plant types that must be present to... |
from typing import List
def max_average_subarray(nums: List[int], k: int) -> float:
current_sum = sum(nums[:k])
max_sum = current_sum
for i in range(k, len(nums)):
current_sum += nums[i] - nums[i - k]
if current_sum > max_sum:
max_sum = current_sum
return max_sum / k | simplelr_Package | [
{
"content": "Question:\n**Title**: Find Maximum Average Subarray of Length k\n\n**Objective**: Implement a Python function to find the contiguous subarray of given length `k` that has the maximum average value within an array of integers.\n\n**Function Name**: `max_average_subarray`\n\n**Function Signature**:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2912,
"level": 1,
"question": "**Title**: Find Maximum Average Subarray of Length k\n\n**Objective**: Implement a Python function to find the contiguous subarray of given length `k` that has the maximum average value within an array of integers.\n\n**Function Name**: `max_average_su... |
from collections import Counter
def leastInterval(tasks, k):
count = Counter(tasks)
max_count = max(count.values())
num_max = sum(1 for v in count.values() if v == max_count)
formula = (max_count - 1) * (k + 1) + num_max
return max(formula, len(tasks)) | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of `n` tasks represented by strings `tasks` and a positive integer `k`, representing the cooldown period between two same tasks, return the least number of intervals the CPU will take to finish all the given tasks. Each interval can either be occupied by executing any one t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2913,
"level": 1,
"question": "Given a list of `n` tasks represented by strings `tasks` and a positive integer `k`, representing the cooldown period between two same tasks, return the least number of intervals the CPU will take to finish all the given tasks. Each interval can either... |
import itertools
from typing import List
def sorted_string_permutations(s: str) -> List[str]:
unique_perms = set()
for p in itertools.permutations(s):
unique_perms.add(''.join(p))
return sorted(unique_perms) | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nYou are creating a library for string manipulation and need a set of utility functions that can be used to process and analyze text data. To challenge students' comprehension, you decide to assess their ability to implement a function tha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2914,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario\nYou are creating a library for string manipulation and need a set of utility functions that can be used to process and analyze text data. To challenge students' comprehension, you decide to assess their ... |
def extract_substrings(s, indices):
result = []
for i in indices:
result.append(s[i:i+3])
return result | simplelr_Filter | [
{
"content": "Question:\nYou can use string slicing to extract a subset of characters from a string. For example, `word[:3]` would give you the first three characters of the string `word`. Write a Python function that takes a string and a list of positive integers as input and returns a list of substrings where... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2915,
"level": 1,
"question": "You can use string slicing to extract a subset of characters from a string. For example, `word[:3]` would give you the first three characters of the string `word`. Write a Python function that takes a string and a list of positive integers as input and... |
def product_of_odds(lst):
product = 1
for num in lst:
if num % 2 != 0:
product *= num
return product | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that calculates the product of all odd numbers in a given list. The function should be able to handle a list of integers and return the product of all the odd numbers. If the list does not contain any odd numbers, the function should return 1, indicating the pro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2916,
"level": 1,
"question": "Create a Python function that calculates the product of all odd numbers in a given list. The function should be able to handle a list of integers and return the product of all the odd numbers. If the list does not contain any odd numbers, the function ... |
def filter_even_numbers(input_list):
return [num for num in input_list if num % 2 == 0] | simplelr_Filter | [
{
"content": "Question:\nCreate a python script to filter an input list and return only the even numbers from the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2917,
"level": 1,
"question": "Create a python script to filter an input list and return only the even numbers from the list.",
"split": "train"
} |
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1) | simplelr_Filter | [
{
"content": "Question:\nExplain the concept of recursion in computer science, and provide an example in a programming language of your choice.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2918,
"level": 1,
"question": "Explain the concept of recursion in computer science, and provide an example in a programming language of your choice.",
"split": "train"
} |
from collections import deque
def topological_sort(tasks: list, dependencies: list) -> list:
"""
Compute and return a list representing a valid topological order of tasks.
:param tasks: list, a list of tasks
:param dependencies: list, a list of tuples where each tuple (u, v) represents a dependency u ... | simplelr_Algorithm | [
{
"content": "Question:\n**Context**:\nYou are tasked with developing a software module within a project management application that helps users manage dependencies between tasks. The task dependencies are represented as a directed acyclic graph (DAG), where nodes represent tasks and directed edges represent de... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2919,
"level": 1,
"question": "**Context**:\nYou are tasked with developing a software module within a project management application that helps users manage dependencies between tasks. The task dependencies are represented as a directed acyclic graph (DAG), where nodes represent ta... |
from sklearn import datasets
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
def iris_classification() -> float:
# Load the Iris dataset
iris = datasets.load_iris()
X =... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nYou are required to implement a machine learning pipeline using scikit-learn to predict the type of iris flower from the well-known Iris dataset. This task will assess your ability to apply and understand various concepts of scikit-learn, including model selection, hype... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2920,
"level": 1,
"question": "#### Objective:\nYou are required to implement a machine learning pipeline using scikit-learn to predict the type of iris flower from the well-known Iris dataset. This task will assess your ability to apply and understand various concepts of scikit-lea... |
def product_except_self(nums):
n = len(nums)
if n == 0:
return []
result = []
left = [1] * n
right = [1] * n
# Compute left products
for i in range(1, n):
left[i] = left[i-1] * nums[i-1]
# Compute right products
for i in range(n-2, -1, -1):
right[i] ... | simplelr_Taco | [
{
"content": "Question:\nImplement a function that takes a list of integers and returns a new list where each element is replaced by the product of all other elements in the original list except the element at that position.\n\nAlgorithm steps:\n\n* Initialize an empty result list.\n* Iterate through the origin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2921,
"level": 1,
"question": "Implement a function that takes a list of integers and returns a new list where each element is replaced by the product of all other elements in the original list except the element at that position.\n\nAlgorithm steps:\n\n* Initialize an empty result ... |
def max_subarray_sum(arr, k):
if not arr or k == 0:
return 0 # assuming k is a positive integer as per problem constraints
n = len(arr)
if k > n:
return 0 # adjust according to problem constraints, maybe handle as per the problem's error handling
current_sum = sum(arr[:k])
max_sum... | simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers and an integer k, return the maximum sum of a subarray of length k.\n\nFormally the function should:\nReturn the maximum sum of a contiguous subarray of length k.\n\nExamples:\nGiven [1, 4, 2, 10, 23, 3, 1, 0, 20], k = 4,\nreturn 39 because the maximum sum sub... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2922,
"level": 1,
"question": "Given an array of integers and an integer k, return the maximum sum of a subarray of length k.\n\nFormally the function should:\nReturn the maximum sum of a contiguous subarray of length k.\n\nExamples:\nGiven [1, 4, 2, 10, 23, 3, 1, 0, 20], k = 4,\nre... |
def max_binary(s: str, k: int) -> str:
s_list = list(s)
for i in range(len(s_list)):
if k == 0:
break
if s_list[i] == '0':
s_list[i] = '1'
k -= 1
return ''.join(s_list)
| simplelr_Taco | [
{
"content": "Question:\n### Task\nWrite a function that accepts a string `s` representing a binary number and an integer `k`. The task is to find and return the maximum binary number you can obtain by performing at most `k` bit flips from '0' to '1'. If flipping `k` bits is not possible due to the number of '0... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2923,
"level": 1,
"question": "### Task\nWrite a function that accepts a string `s` representing a binary number and an integer `k`. The task is to find and return the maximum binary number you can obtain by performing at most `k` bit flips from '0' to '1'. If flipping `k` bits is n... |
import math
from typing import List
def primes_upto_n(N: int) -> List[int]:
if N < 2:
return []
sieve = [True] * (N + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(math.sqrt(N)) + 1):
if sieve[i]:
sieve[i*i : N+1 : i] = [False] * len(sieve[i*i : N+1 : i])
primes =... | simplelr_Data_Structure | [
{
"content": "Question:\nImplement a function to find all prime numbers up to a given integer \\( N \\). Given an integer \\( N \\), return a list containing all prime numbers less than or equal to \\( N \\).\n\n**Function Signature**:\n```python\ndef primes_upto_n(N: int) -> List[int]:\n```\n\n### Input:\n* `N... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2924,
"level": 1,
"question": "Implement a function to find all prime numbers up to a given integer \\( N \\). Given an integer \\( N \\), return a list containing all prime numbers less than or equal to \\( N \\).\n\n**Function Signature**:\n```python\ndef primes_upto_n(N: int) -> ... |
from typing import List, Tuple
def minimize_overlaps(events: List[Tuple[int, int]]) -> int:
events_list = []
for start, end in events:
events_list.append((start, 1))
events_list.append((end, -1))
events_list.sort()
current_rooms = 0
max_rooms = 0
for time, delta i... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\n#### Context:\nYou are given a list of events, and you want to organize them in such a way that the number of overlapping events is minimized. An event is represented by a start time and an end time. Two events are considered overlapping if one event starts before the ot... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2925,
"level": 1,
"question": "### Question\n\n#### Context:\nYou are given a list of events, and you want to organize them in such a way that the number of overlapping events is minimized. An event is represented by a start time and an end time. Two events are considered overlappin... |
def max_submatrix_sum(matrix, k):
n = len(matrix)
if k > n or k == 0:
return -1
# Initialize prefix sum matrix with an extra row and column of zeros
prefix = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n):
for j in range(n):
prefix[i+1][j+1] = matrix[i]... | simplelr_Taco | [
{
"content": "Question:\nYou are given a square matrix of integers `matrix` where the dimensions of the matrix are `n x n` and an integer `k`. Your task is to find the maximum sum of any submatrix of size `k x k` within the given matrix. \n\nA submatrix is defined as a contiguous block of cells in the matrix. T... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2926,
"level": 1,
"question": "You are given a square matrix of integers `matrix` where the dimensions of the matrix are `n x n` and an integer `k`. Your task is to find the maximum sum of any submatrix of size `k x k` within the given matrix. \n\nA submatrix is defined as a contigu... |
def normalize_string(input_str):
if not isinstance(input_str, str):
raise TypeError("Input must be a string.")
return input_str.strip().lower() | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function named \"normalize_string\" that takes a string as input and returns the string with all characters in lower case and all leading and trailing white spaces removed. Additionally, if the input is not a string, throw a TypeError. The function should handle empty str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2927,
"level": 1,
"question": "Write a Python function named \"normalize_string\" that takes a string as input and returns the string with all characters in lower case and all leading and trailing white spaces removed. Additionally, if the input is not a string, throw a TypeError. T... |
def three_sum_zero(nums):
nums.sort()
n = len(nums)
triplets = []
for i in range(n - 2):
# Skip duplicate a's
if i > 0 and nums[i] == nums[i - 1]:
continue
left = i + 1
right = n - 1
while left < right:
total = nums[i] + nums[left] + nums[r... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to print all unique triples of numbers in a list where the sum of the three numbers is zero. The list can contain duplicate numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2928,
"level": 1,
"question": "Write a python function to print all unique triples of numbers in a list where the sum of the three numbers is zero. The list can contain duplicate numbers.",
"split": "train"
} |
def count_decompositions(n: int) -> int:
if n == 0:
return 1
# Initialize DP table with (n+1)x(n+1) elements
arr = [[0] * (n + 1) for _ in range(n + 1)]
# Base case: arr[0][j] = 1 for any j
for j in range(n + 1):
arr[0][j] = 1
for i in range(1, n + 1):
for j in ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Coding Challenge: Integer Decomposition\nYou are tasked with writing a function that finds the number of ways a given positive integer can be decomposed into the sum of smaller positive integers. This problem explores advanced dynamic programming concepts.\n\n#### Function Signature... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2929,
"level": 1,
"question": "### Coding Challenge: Integer Decomposition\nYou are tasked with writing a function that finds the number of ways a given positive integer can be decomposed into the sum of smaller positive integers. This problem explores advanced dynamic programming c... |
import math
def transform_list(numbers):
result = []
for num in numbers:
if num < 0:
transformed = math.sqrt(abs(num))
else:
transformed = num ** 2
result.append(transformed)
return result | simplelr_Filter | [
{
"content": "Question:\nGiven a list of numbers, create a function in Python that returns a new list with each element being the square of the original element. If the original element is negative, the function should return the square root of the absolute value of that element instead. Ensure your function ha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2930,
"level": 1,
"question": "Given a list of numbers, create a function in Python that returns a new list with each element being the square of the original element. If the original element is negative, the function should return the square root of the absolute value of that eleme... |
def detect_fraud(transactions, time_frame, limit):
# Group transactions by account ID
accounts = {}
for trans in transactions:
acc_id, amt, ts = trans
if acc_id not in accounts:
accounts[acc_id] = []
accounts[acc_id].append((amt, ts))
fraudulent_accounts = set()
... | simplelr_Apps | [
{
"content": "Question:\nYou have just been hired by a bank to work on their new fraud detection system. One critical task is to identify if a series of transactions contains any fraudulent activity. A transaction is deemed fraudulent if it satisfies the following conditions:\n\n1. Any transaction amount is neg... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2931,
"level": 1,
"question": "You have just been hired by a bank to work on their new fraud detection system. One critical task is to identify if a series of transactions contains any fraudulent activity. A transaction is deemed fraudulent if it satisfies the following conditions:\... |
from typing import List
def find_pattern_indices(pattern: str, text: str) -> List[int]:
m = len(pattern)
n = len(text)
if m == 0 or m > n:
return []
# Compute LPS array for the pattern
lps = [0] * m
length = 0 # Length of the previous longest prefix suffix
for i in range(... | simplelr_Taco | [
{
"content": "Question:\n### The problem\n\nYou are given two strings, `pattern` and `text`. Your task is to implement a function that returns all starting indices (0-based) of substrings in `text` that match the `pattern`. You should return the indices in a list.\n\n### Example\n\nGiven the following input:\n`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2932,
"level": 1,
"question": "### The problem\n\nYou are given two strings, `pattern` and `text`. Your task is to implement a function that returns all starting indices (0-based) of substrings in `text` that match the `pattern`. You should return the indices in a list.\n\n### Examp... |
def calculate_grade_distribution():
with open('student_grades.txt', 'r') as f:
counts = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'F': 0}
for line in f:
parts = line.strip().split()
if len(parts) < 2:
continue # Skip invalid lines
grade = int(parts[1])
... | simplelr_Package | [
{
"content": "Question:\nYou have a text file named `student_grades.txt` containing the names and grades of students. Each line in the file is formatted as \"Name Grade\" (e.g., \"Alice 85\"), separated by a space. Write a function named `calculate_grade_distribution` that:\n\n1. Reads the data from the `studen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2933,
"level": 1,
"question": "You have a text file named `student_grades.txt` containing the names and grades of students. Each line in the file is formatted as \"Name Grade\" (e.g., \"Alice 85\"), separated by a space. Write a function named `calculate_grade_distribution` that:\n\... |
def unique_characters(s):
seen = set()
result = []
for char in s:
if char not in seen:
seen.add(char)
result.append(char)
return ''.join(result) | simplelr_Filter | [
{
"content": "Question:\nIn a Python program,\n\nhow to write a function that takes a string and returns a new string\n\nthat contains only the unique characters\n\nin the input string, maintaining their original order?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2934,
"level": 1,
"question": "In a Python program,\n\nhow to write a function that takes a string and returns a new string\n\nthat contains only the unique characters\n\nin the input string, maintaining their original order?",
"split": "train"
} |
def plot_penguin_data():
import seaborn as sns
import matplotlib.pyplot as plt
# Load the penguins dataset
penguins = sns.load_dataset("penguins")
# Set appropriate Seaborn theme for visual appeal
sns.set_theme(style="whitegrid")
# Part (a) - Plot Histogram with KDE
plt.fi... | simplelr_Docs | [
{
"content": "Question:\n## Coding Assessment Question\n\n### Objective\nTo test your understanding of Seaborn's `displot` function and its customization options to create different types of visualizations.\n\n### Problem Statement\n\nYou are provided with a dataset `penguins` which contains information about p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2935,
"level": 1,
"question": "## Coding Assessment Question\n\n### Objective\nTo test your understanding of Seaborn's `displot` function and its customization options to create different types of visualizations.\n\n### Problem Statement\n\nYou are provided with a dataset `penguins`... |
from typing import List
def min_subarray_len(target: int, nums: List[int]) -> int:
left = 0
current_sum = 0
min_length = float('inf')
for right in range(len(nums)):
current_sum += nums[right]
while current_sum >= target:
current_window_length = right - left + 1... | simplelr_Apps | [
{
"content": "Question:\nGiven a list of integers `nums` and an integer `target`, return the length of the shortest contiguous subarray where the sum is greater than or equal to `target`. If there is no such subarray, return 0 instead.\n\nFor example:\n```python\nInput: nums = [2, 3, 1, 2, 4, 3], target = 7\nOu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2936,
"level": 1,
"question": "Given a list of integers `nums` and an integer `target`, return the length of the shortest contiguous subarray where the sum is greater than or equal to `target`. If there is no such subarray, return 0 instead.\n\nFor example:\n```python\nInput: nums =... |
def separate_words_and_digits(s):
words = []
digits = []
tokens = s.split()
for token in tokens:
if token.isdigit():
digits.append(token)
else:
words.append(token)
return (words, digits) | simplelr_Evol | [
{
"content": "Question:\nYou are given a string containing a mix of words and digits. Write a function that separates and returns two lists: one containing all the words in the original order, and another containing all the digits, also in their original order. Assume that the input string consists of words and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2937,
"level": 1,
"question": "You are given a string containing a mix of words and digits. Write a function that separates and returns two lists: one containing all the words in the original order, and another containing all the digits, also in their original order. Assume that the... |
def check_inclusion(s1, s2):
len1 = len(s1)
len2 = len(s2)
if len1 == 0:
return True
if len2 < len1:
return False
# Initialize count arrays for 26 lowercase letters
s1_count = [0] * 26
s2_count = [0] * 26
for i in range(len1):
s1_count[ord(s1[i]) - ... | simplelr_Filter | [
{
"content": "Question:\nCan you help me implement a sliding window technique for the \"Permutation in String\" problem?\n\nThe problem statement goes like this:\nGiven two strings `s1` and `s2`, write a function to determine if `s2` contains a permutation of `s1`.\nAnswer:\nLet's think step by step.\n",
"r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2938,
"level": 1,
"question": "Can you help me implement a sliding window technique for the \"Permutation in String\" problem?\n\nThe problem statement goes like this:\nGiven two strings `s1` and `s2`, write a function to determine if `s2` contains a permutation of `s1`.",
"split"... |
def remove_except_set(s, allowed):
allowed_set = set(allowed)
return ''.join([char for char in s if char in allowed_set]) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove all characters in a string except a specified set of characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2939,
"level": 1,
"question": "Write a python function to remove all characters in a string except a specified set of characters.",
"split": "train"
} |
def fibonacci(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
a, b = 0, 1
for _ in range(3, n + 1):
c = a + b
a = b
b = c
return b | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the nth element in the Fibonacci sequence.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2940,
"level": 1,
"question": "Write a python function to find the nth element in the Fibonacci sequence.",
"split": "train"
} |
def find_max(lst):
if len(lst) == 1:
return lst[0]
else:
return max(lst[0], find_max(lst[1:])) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum element in a list using recursion. How would you solve this problem step-by-step?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2941,
"level": 1,
"question": "Write a python function to find the maximum element in a list using recursion. How would you solve this problem step-by-step?",
"split": "train"
} |
def roman_to_int(s: str) -> int:
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
for i in range(len(s)):
current = roman_dict[s[i]]
total += current
if i < len(s) - 1:
next_val = roman_dict[s[i+1]]
if current < next_val... | simplelr_Code_Contests | [
{
"content": "Question:\nCreate a function that takes a string representing a Roman numeral and converts it to an integer. The input string will be a valid Roman numeral, within the range from 1 to 3999. Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M.\n\n**Examples:**\n- Inpu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2942,
"level": 1,
"question": "Create a function that takes a string representing a Roman numeral and converts it to an integer. The input string will be a valid Roman numeral, within the range from 1 to 3999. Roman numerals are represented by seven different symbols: I, V, X, L, C,... |
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True | simplelr_Filter | [
{
"content": "Question:\nI'm trying to learn Python, so could you provide me with a simple example of how to create a function that checks if a given number is prime.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2943,
"level": 1,
"question": "I'm trying to learn Python, so could you provide me with a simple example of how to create a function that checks if a given number is prime.",
"split": "train"
} |
from collections import Counter
import re
def find_top_n_words(text, n):
text_lower = text.lower()
words = re.findall(r"[a-z']+", text_lower)
words = [word.strip("'") for word in words]
words = [word for word in words if word]
counts = Counter(words)
sorted_words = sorted(counts.items(), key=la... | simplelr_Package | [
{
"content": "Question:\nYou are required to implement a function `find_top_n_words()` that identifies the most frequent words in a given text and returns them in the order of their frequency, from highest to lowest. The function should ignore punctuation and treat words with different capitalizations as the sa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2944,
"level": 1,
"question": "You are required to implement a function `find_top_n_words()` that identifies the most frequent words in a given text and returns them in the order of their frequency, from highest to lowest. The function should ignore punctuation and treat words with ... |
def remove_first_and_last_character(s):
return s[1:-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and returns the string with the first and last characters removed. The function must handle cases where the input string has a length of 1 or less, and both cases should return an empty string as a result.\nAnswer:\nLet's think step by step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2945,
"level": 1,
"question": "Create a function that takes a string as input and returns the string with the first and last characters removed. The function must handle cases where the input string has a length of 1 or less, and both cases should return an empty string as a result.... |
def remove_duplicates(input_list):
seen = set()
result = []
for item in input_list:
if item not in seen:
seen.add(item)
result.append(item)
return result
# Example usage:
numbers = [1, 2, 3, 1, 4, 2, 5]
unique_numbers = remove_duplicates(numbers)
print(unique_numbers) #... | simplelr_Filter | [
{
"content": "Question:\nI need some help with a programming task. I'm working on a Python script that needs to process a list of numbers. The task is to remove any duplicates from the list while preserving the original order of the numbers. How can I achieve this?\nAnswer:\nLet's think step by step.\n",
"r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2946,
"level": 1,
"question": "I need some help with a programming task. I'm working on a Python script that needs to process a list of numbers. The task is to remove any duplicates from the list while preserving the original order of the numbers. How can I achieve this?",
"split"... |
def max_consecutive_pairs(arr):
count = 0
i = 0
while i < len(arr) - 1:
if abs(arr[i+1] - arr[i]) == 1:
count += 1
i += 2
else:
i += 1
return count | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers as input and returns the maximum number of pairs that can be made from the array, where each pair is formed by two consecutive integers. A pair is considered valid if the absolute difference between the two integers in the pair is exactl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2947,
"level": 1,
"question": "Create a function that takes an array of integers as input and returns the maximum number of pairs that can be made from the array, where each pair is formed by two consecutive integers. A pair is considered valid if the absolute difference between the... |
def max_subarray_sum_less_than_k(nums, k):
max_sum = -float('inf')
n = len(nums)
for i in range(n):
current_sum = 0
for j in range(i, n):
current_sum += nums[j]
if current_sum < k:
if current_sum > max_sum:
max_sum = current_sum
... | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers `nums` and an integer `k`, return the maximum sum of a non-empty subarray of `nums` such that the sum of the subarray is less than `k`. If no such subarray exists, return `-1`.\n\nNote:\n\n- The array `nums` can contain both positive and negative integers.\n- ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2948,
"level": 1,
"question": "Given an array of integers `nums` and an integer `k`, return the maximum sum of a non-empty subarray of `nums` such that the sum of the subarray is less than `k`. If no such subarray exists, return `-1`.\n\nNote:\n\n- The array `nums` can contain both ... |
def longest_substring_k_unique(s: str, k: int) -> str:
if not s or k == 0:
return ""
freq = {}
left = 0
max_len = 0
start = 0
for right in range(len(s)):
char = s[right]
if char in freq:
freq[char] += 1
else:
freq[char] = 1
... | simplelr_Evol | [
{
"content": "Question:\nGiven a string s and an integer k, you need to perform a sliding window operation that finds the longest substring with exactly k unique characters. If there are multiple substrings with the same maximum length, return the one that appears first. If no such substring exists, return an e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2949,
"level": 1,
"question": "Given a string s and an integer k, you need to perform a sliding window operation that finds the longest substring with exactly k unique characters. If there are multiple substrings with the same maximum length, return the one that appears first. If no... |
def common_elements(list1, list2):
list2_copy = list(list2) # Create a copy to avoid modifying the original list
result = []
for num in list1:
if num in list2_copy:
result.append(num)
list2_copy.remove(num) # Remove the first occurrence to prevent reuse
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes two lists as input and returns a list of elements that are common to both input lists. The function should not use any built-in Python functions for finding common elements, such as `set.intersection()`. Instead, it should implement the logic manually ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2950,
"level": 1,
"question": "Write a Python function that takes two lists as input and returns a list of elements that are common to both input lists. The function should not use any built-in Python functions for finding common elements, such as `set.intersection()`. Instead, it s... |
def find_book_location(library, book_id):
for floor_index, floor in enumerate(library):
for shelf_index, shelf in enumerate(floor):
if book_id in shelf:
return (floor_index, shelf_index)
return (-1, -1)
| simplelr_Taco | [
{
"content": "Question:\nYour friend Alex has a large library with multiple floors, and each floor has a number of bookshelves, each filled with books. Alex needs a functionality to quickly find on which floor and which bookshelf a specific book is located. However, the books in the library are not arranged in ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2951,
"level": 1,
"question": "Your friend Alex has a large library with multiple floors, and each floor has a number of bookshelves, each filled with books. Alex needs a functionality to quickly find on which floor and which bookshelf a specific book is located. However, the books ... |
def reverse_string(s):
return s[::-1]
# Example usage:
example_string = "hello"
print(reverse_string(example_string)) # Output: "olleh" | simplelr_Filter | [
{
"content": "Question:\nCan you provide an example of a simple algorithm to reverse a string in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2952,
"level": 1,
"question": "Can you provide an example of a simple algorithm to reverse a string in Python?",
"split": "train"
} |
import calendar
def generate_custom_calendar(year: int, month: int, start_day: str) -> str:
day_map = {
"Monday": calendar.MONDAY,
"Tuesday": calendar.TUESDAY,
"Wednesday": calendar.WEDNESDAY,
"Thursday": calendar.THURSDAY,
"Friday": calendar.FRIDAY,
"Saturday": cale... | simplelr_Docs | [
{
"content": "Question:\n### Task\nYou need to implement a function `generate_custom_calendar(year: int, month: int, start_day: str) -> str` that generates a text calendar for a given month and year, and allows the specification of the starting day of the week.\n\n### Specifications:\n1. **Input:**\n - `year`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2953,
"level": 1,
"question": "### Task\nYou need to implement a function `generate_custom_calendar(year: int, month: int, start_day: str) -> str` that generates a text calendar for a given month and year, and allows the specification of the starting day of the week.\n\n### Specific... |
def is_valid_parentheses(s):
stack = []
bracket_map = {')': '(', '}': '{', ']': '['}
for char in s:
if char in bracket_map.values():
stack.append(char)
elif char in bracket_map:
if not stack:
return False
top = stack.pop()
if to... | simplelr_Leetcode | [
{
"content": "Question:\nWrite a function that takes a string containing just the characters '(', ')', '{', '}', '[' and ']', and determines if the input string is valid. An input string is valid if:\n\n1. Open brackets must be closed by the same type of brackets.\n2. Open brackets must be closed in the correct... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2954,
"level": 1,
"question": "Write a function that takes a string containing just the characters '(', ')', '{', '}', '[' and ']', and determines if the input string is valid. An input string is valid if:\n\n1. Open brackets must be closed by the same type of brackets.\n2. Open bra... |
def sort_names_by_score(tuples_list):
sorted_tuples = sorted(tuples_list, key=lambda x: (-x[1], x[0]))
return [x[0] for x in sorted_tuples] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of tuples, where each tuple contains a name and a score, and returns a list of names sorted by the highest score first. If two names have the same score, the names should be sorted alphabetically.\nAnswer:\nLet's think step by step.\n",
"rol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2955,
"level": 1,
"question": "Write a Python function that takes a list of tuples, where each tuple contains a name and a score, and returns a list of names sorted by the highest score first. If two names have the same score, the names should be sorted alphabetically.",
"split": ... |
from collections import defaultdict
def anagramPairs(n, strings):
anagram_counts = defaultdict(int)
for s in strings:
key = tuple(sorted(s))
anagram_counts[key] += 1
total = 0
for count in anagram_counts.values():
if count >= 2:
total += count * (count - 1) // 2
... | simplelr_Code_Contests | [
{
"content": "Question:\nCreate a function **anagramPairs** that, given a list of strings, returns the total number of unordered pairs of strings that are anagrams of each other.\n\n### Input\n- An integer **n** (1 ≤ n ≤ 10^4) - the length of the list.\n- A list of **n** strings, where each string has at most 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2956,
"level": 1,
"question": "Create a function **anagramPairs** that, given a list of strings, returns the total number of unordered pairs of strings that are anagrams of each other.\n\n### Input\n- An integer **n** (1 ≤ n ≤ 10^4) - the length of the list.\n- A list of **n** strin... |
def count_vowels_consonants(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
vowel_count = 0
consonant_count = 0
for char in s:
if char.isalpha():
lower_char = char.lower()
if lower_char in vowels:
vowel_count += 1
else:
consonant_count +... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to determine the number of vowels and consonants in a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2957,
"level": 1,
"question": "Write a function to determine the number of vowels and consonants in a string.",
"split": "train"
} |
import os
def delete_files(directory):
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
os.remove(file_path)
# Example usage:
directory = 'directory'
delete_files(directory) | simplelr_Filter | [
{
"content": "Question:\nYou have been provided with a directory named 'directory' containing a number of files and subdirectories. Write a Python script that deletes all the files in the directory and its subdirectories, but does not delete any subdirectories.\n\nTo accomplish this task, you will need to:\n1. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2958,
"level": 1,
"question": "You have been provided with a directory named 'directory' containing a number of files and subdirectories. Write a Python script that deletes all the files in the directory and its subdirectories, but does not delete any subdirectories.\n\nTo accomplis... |
def is_palindrome(s):
# Filter only alphanumeric characters and convert to lowercase
filtered = [c.lower() for c in s if c.isalnum()]
# Join the characters into a string
filtered_str = ''.join(filtered)
# Check if the string is equal to its reverse
return filtered_str == filtered_str[::-1]
# Ex... | simplelr_Filter | [
{
"content": "Question:\nDevelop a Python program to check if a string is a palindrome, considering only alphanumeric characters and ignoring cases.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2959,
"level": 1,
"question": "Develop a Python program to check if a string is a palindrome, considering only alphanumeric characters and ignoring cases.",
"split": "train"
} |
def apply_absolute(nums):
return [abs(num) for num in nums] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list of integers and outputs a list of the same integers but with the absolute value applied to each.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2960,
"level": 1,
"question": "Create a function that takes in a list of integers and outputs a list of the same integers but with the absolute value applied to each.",
"split": "train"
} |
def filter_strings_by_length(strings, min_length):
"""
Returns a list of strings from the input that have a length greater than the specified minimum length.
Args:
strings (list): A list of strings to filter.
min_length (int): The minimum length a string must exceed to be included.
... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of strings and returns a new list containing the strings that have a length greater than the specified length.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2961,
"level": 1,
"question": "Create a function that takes a list of strings and returns a new list containing the strings that have a length greater than the specified length.",
"split": "train"
} |
def rotate_right(arr, n, k):
if n == 0 or k == 0:
return
k = k % n
for _ in range(k):
last = arr.pop()
arr.insert(0, last) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to rotate an array to the right by k positions using a single loop. The array should remain in-place, meaning you cannot declare a new array. Your function should take the array, its size, and the number of positions to rotate as arguments.\nAnswer:\nLet's think step by... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2962,
"level": 1,
"question": "Write a function to rotate an array to the right by k positions using a single loop. The array should remain in-place, meaning you cannot declare a new array. Your function should take the array, its size, and the number of positions to rotate as argum... |
def min_operations_to_equal_piles(nums):
min_val = min(nums)
return sum(num - min_val for num in nums) | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums` where each integer represents the number of candies in a pile. You have to make all the piles equal by performing a sequence of operations. In a single operation, you can choose any pile and remove one candy from it. Determine the minimum number of oper... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2963,
"level": 1,
"question": "Given an array of integers `nums` where each integer represents the number of candies in a pile. You have to make all the piles equal by performing a sequence of operations. In a single operation, you can choose any pile and remove one candy from it. D... |
def min_path_sum(grid):
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
dp = [[0 for _ in range(n)] for _ in range(m)]
dp[0][0] = grid[0][0]
# Fill the first row
for j in range(1, n):
dp[0][j] = dp[0][j-1] + grid[0][j]
# Fill the first column
for i in ran... | simplelr_Leetcode | [
{
"content": "Question:\n**[Question 4]:** \n\nYou are provided with a matrix `grid` of integers where each element represents the cost associated with moving through that cell. You start from the top-left cell and need to reach the bottom-right cell by only moving either right or down at any given step. Your t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2964,
"level": 1,
"question": "**[Question 4]:** \n\nYou are provided with a matrix `grid` of integers where each element represents the cost associated with moving through that cell. You start from the top-left cell and need to reach the bottom-right cell by only moving either righ... |
from collections import defaultdict
def subarray_sum(arr, k):
prefix_counts = defaultdict(int)
prefix_counts[0] = 1 # Initialize with 0 to handle cases where subarray starts from index 0
current_sum = 0
count = 0
for num in arr:
current_sum += num
# Check if (current_sum - k) exis... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of `n` integers, `arr`, and an integer `k`, write a function to count the number of contiguous subarrays that have a sum equal to `k`. A subarray is defined as a contiguous non-empty sequence of elements within the array. You need to return the count of such subarrays.\nAns... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2965,
"level": 1,
"question": "Given a list of `n` integers, `arr`, and an integer `k`, write a function to count the number of contiguous subarrays that have a sum equal to `k`. A subarray is defined as a contiguous non-empty sequence of elements within the array. You need to retur... |
def trap_rainwater(nums):
if not nums:
return 0
n = len(nums)
left_max = [0] * n
right_max = [0] * n
# Compute left_max
max_so_far = nums[0]
for i in range(1, n):
left_max[i] = max_so_far
if nums[i] > max_so_far:
max_so_far = nums[i]
# Comput... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of non-negative integers `nums` which represents the amount of rainwater trapped at each elevation map where the width of each bar is 1. Compute how much water it can trap after raining.\n\nFor example:\nGiven `nums = [0,1,0,2,1,0,1,3,2,1,2,1]`, return `6`.\n\nNote:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2966,
"level": 1,
"question": "You are given a list of non-negative integers `nums` which represents the amount of rainwater trapped at each elevation map where the width of each bar is 1. Compute how much water it can trap after raining.\n\nFor example:\nGiven `nums = [0,1,0,2,1,0,... |
def fibonacci(n: int) -> int:
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b | simplelr_Data_Structure | [
{
"content": "Question:\n### Fibonacci Number Calculation\n\nWrite a function that computes the n-th Fibonacci number. You are required to implement the solution using an efficient approach to ensure optimum performance for larger values of n. Avoid using a simple recursive implementation due to its inefficienc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2967,
"level": 1,
"question": "### Fibonacci Number Calculation\n\nWrite a function that computes the n-th Fibonacci number. You are required to implement the solution using an efficient approach to ensure optimum performance for larger values of n. Avoid using a simple recursive im... |
def hasOddSumSubarray(arr):
for num in arr:
if num % 2 != 0:
return True
return False
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of non-negative integers, you are tasked to find if there exists a contiguous subarray (of size at least one) whose sum is an odd number. If such a subarray exists, return True, otherwise return False.\n\nExample 1:\nInput: arr = [2, 4, 6, 8, 5]\nOutput: True\nExplanation... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2968,
"level": 1,
"question": "Given an array of non-negative integers, you are tasked to find if there exists a contiguous subarray (of size at least one) whose sum is an odd number. If such a subarray exists, return True, otherwise return False.\n\nExample 1:\nInput: arr = [2, 4, ... |
import re
def extract_version(s):
match = re.search(r'Version\s+([0-9.]+)', s)
return match.group(1) if match else None | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function to extract the version number from a given string containing software version information in the format \"Version X.Y.Z (Release Date)\"?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2969,
"level": 1,
"question": "How can I create a Python function to extract the version number from a given string containing software version information in the format \"Version X.Y.Z (Release Date)\"?",
"split": "train"
} |
from typing import List
def search_rotated_array(nums: List[int], target: int) -> int:
if not nums:
return -1
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
if nums[low] <= nums[mid]:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Binary Search in a Rotated Sorted Array\n\nYou are building a search feature for a library catalog system. The system stores book IDs in a special format: a rotated sorted array. A rotated sorted array is an array that has been sorted in ascending order and then rotated (shifted) at... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2970,
"level": 1,
"question": "### Binary Search in a Rotated Sorted Array\n\nYou are building a search feature for a library catalog system. The system stores book IDs in a special format: a rotated sorted array. A rotated sorted array is an array that has been sorted in ascending ... |
def string_to_number(s):
"""
Converts a string to an integer or float if possible. Returns None if conversion is not possible.
Args:
s (str): The string to be converted to a number.
Returns:
int, float, or None: The converted number if successful, otherwise None.
"""
tr... | simplelr_Filter | [
{
"content": "Question:\nHow to create a Python function that converts a string to a number and handles exceptions?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2971,
"level": 1,
"question": "How to create a Python function that converts a string to a number and handles exceptions?",
"split": "train"
} |
import re
from collections import defaultdict
def word_frequency_counter(text):
"""
Processes the input text and returns a dictionary with words as keys
and their frequency counts as values.
Parameters:
text (str): The input text to process.
Returns:
dict: A dictionary of word fr... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment: Word Frequency Counter\n\n#### Problem Statement\n\nYou are tasked with implementing a word frequency counter in Python. This tool should be able to process a text input and generate a frequency count of each unique word. The word frequency counter should be case-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2972,
"level": 1,
"question": "### Coding Assessment: Word Frequency Counter\n\n#### Problem Statement\n\nYou are tasked with implementing a word frequency counter in Python. This tool should be able to process a text input and generate a frequency count of each unique word. The wor... |
def string_to_binary(s):
return ''.join(format(ord(c), '08b') for c in s) | simplelr_Filter | [
{
"content": "Question:\nGiven a string, write a Python function to generate a new string where each character in the original string is replaced by its corresponding binary representation. The binary representation should be in the form of a string, and if the binary number is less than 8 bits, it should be pa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2973,
"level": 1,
"question": "Given a string, write a Python function to generate a new string where each character in the original string is replaced by its corresponding binary representation. The binary representation should be in the form of a string, and if the binary number i... |
def remove_characters(s, chars):
return ''.join(c for c in s if c not in chars) | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes a string and a set of characters as inputs and removes all characters in the string that are in the set.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2974,
"level": 1,
"question": "Write a function in Python that takes a string and a set of characters as inputs and removes all characters in the string that are in the set.",
"split": "train"
} |
def find_substring(main_str, sub_str):
len_sub = len(sub_str)
len_main = len(main_str)
if len_sub == 0:
return 0
if len_sub > len_main:
return -1
for i in range(len_main - len_sub + 1):
if main_str[i:i+len_sub] == sub_str:
return i
return -1 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that can identify the index of the first occurrence of a substring within a string. If the substring is not found, the function should return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2975,
"level": 1,
"question": "Create a function that can identify the index of the first occurrence of a substring within a string. If the substring is not found, the function should return -1.",
"split": "train"
} |
def compress_string(s: str) -> str:
if not s:
return s
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(current_char + str(count))
current_char = char
count = 1... | simplelr_Algorithm | [
{
"content": "Question:\n### String Compression Algorithm Implementation\n\nYou are given a string `s` consisting of lowercase alphabetical characters. Your task is to implement a function `compress_string` that compresses the string using the following basic run-length encoding technique: for a sequence of rep... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2976,
"level": 1,
"question": "### String Compression Algorithm Implementation\n\nYou are given a string `s` consisting of lowercase alphabetical characters. Your task is to implement a function `compress_string` that compresses the string using the following basic run-length encodi... |
import re
from collections import defaultdict
def word_frequencies(input_string):
frequency = defaultdict(int)
input_string = input_string.lower()
words = re.findall(r"[a-z']+", input_string)
for word in words:
stripped_word = word.strip("'")
if stripped_word:
frequency[stri... | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python function that takes a string and returns a dictionary with the frequency of each word in the string, ignoring punctuation and case sensitivity?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2977,
"level": 1,
"question": "Can you help me with a Python function that takes a string and returns a dictionary with the frequency of each word in the string, ignoring punctuation and case sensitivity?",
"split": "train"
} |
def twoSum(nums, target):
hash_table = {}
for num in nums:
complement = target - num
if complement in hash_table:
return [complement, num]
hash_table[num] = num
return [] # No solution found
# Test cases
print(twoSum([2, 7, 11, 15], 9)) # Expected output: [2, 7]
print(... | simplelr_Filter | [
{
"content": "Question:\nThis problem is to find a pair of numbers in an array that add up to a target number.\n\nI would like to find the solution using a hash table.\n\nHere is a simple example to start with.\n\n**Example 1:**\nInput: `nums = [2, 7, 11, 15], target = 9`\nOutput: `[2, 7]`\n\n**Example 2:**\nIn... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2978,
"level": 1,
"question": "This problem is to find a pair of numbers in an array that add up to a target number.\n\nI would like to find the solution using a hash table.\n\nHere is a simple example to start with.\n\n**Example 1:**\nInput: `nums = [2, 7, 11, 15], target = 9`\nOut... |
def merge_dictionaries(delta, gamma, omega):
# Initialize a temporary dictionary to collect values
temp = {}
# List of dictionaries to merge
dictionaries = [delta, gamma, omega]
# Iterate through each dictionary
for d in dictionaries:
for key, value in d.items():
if... | simplelr_Filter | [
{
"content": "Question:\nAssume you are handling three python dictionary structures denoted as delta, gamma, and omega. Write a python script that merges these three dictionaries into a single dictionary called alpha while maintaining the uniqueness of the keys. Your solution should accommodate situations where... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2979,
"level": 1,
"question": "Assume you are handling three python dictionary structures denoted as delta, gamma, and omega. Write a python script that merges these three dictionaries into a single dictionary called alpha while maintaining the uniqueness of the keys. Your solution ... |
def square_sequence(sequence):
return [x ** 2 for x in sequence] | simplelr_Filter | [
{
"content": "Question:\nGiven a sequence of integers, write a Python function that returns a list of the same length where each element is the square of the corresponding element in the original sequence. For example, given the sequence [1, 2, 3], the function should return [1, 4, 9].\nAnswer:\nLet's think ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2980,
"level": 1,
"question": "Given a sequence of integers, write a Python function that returns a list of the same length where each element is the square of the corresponding element in the original sequence. For example, given the sequence [1, 2, 3], the function should return [... |
def is_anagram(s1, s2):
if len(s1) != len(s2):
return False
count1 = [0] * 26
count2 = [0] * 26
for c in s1:
index = ord(c) - ord('a')
count1[index] += 1
for c in s2:
index = ord(c) - ord('a')
count2[index] += 1
return count1 == count2 | simplelr_Apps | [
{
"content": "Question:\nGiven two strings s1 and s2, write a function to determine if s2 is an anagram of s1.\n\nNote:\n\nBoth strings consist of lower-case English letters only.\nThe length of both strings is < 10000.\nAn anagram is a word or phrase formed by rearranging the letters of another, such as \"cine... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2981,
"level": 1,
"question": "Given two strings s1 and s2, write a function to determine if s2 is an anagram of s1.\n\nNote:\n\nBoth strings consist of lower-case English letters only.\nThe length of both strings is < 10000.\nAn anagram is a word or phrase formed by rearranging the... |
def string_to_ascii_list(s):
return [ord(char) for char in s] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert a string into a list of ASCII values.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2982,
"level": 1,
"question": "Write a python function to convert a string into a list of ASCII values.",
"split": "train"
} |
def is_valid_pattern(sequence):
# Check if all numbers are between 1 and 9
for num in sequence:
if num < 1 or num > 9:
return False
# Check for duplicates
if len(sequence) != len(set(sequence)):
return False
# Grid mapping: each number to its (row, column)
g... | simplelr_Taco | [
{
"content": "Question:\nImplement a function that simulates a pattern locking mechanism on a touch screen. A 3x3 grid represents the screen, with each cell having a unique number from 1 to 9. Your task is to verify if a given sequence of numbers is a valid pattern lock sequence according to the following rules... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2983,
"level": 1,
"question": "Implement a function that simulates a pattern locking mechanism on a touch screen. A 3x3 grid represents the screen, with each cell having a unique number from 1 to 9. Your task is to verify if a given sequence of numbers is a valid pattern lock sequen... |
from typing import List
def find_unique_element(nums: List[int]) -> int:
unique = 0
for num in nums:
unique ^= num
return unique | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Find Unique Element in List\n\nGiven an array of integers where every element appears twice except for one, write a function to find that unique element. Your algorithm should have a linear runtime complexity and should be implemented without using extra memory.\n\n**Funct... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2984,
"level": 1,
"question": "### Question: Find Unique Element in List\n\nGiven an array of integers where every element appears twice except for one, write a function to find that unique element. Your algorithm should have a linear runtime complexity and should be implemented wit... |
def is_symmetric(s):
return s == s[::-1]
| simplelr_Taco | [
{
"content": "Question:\nIn Dreamland, a special type of string called a \"Symmetric String\" is celebrated. A string is considered symmetric if it reads the same forwards and backwards. For example, the string \"level\" is symmetric, whereas the string \"coding\" is not.\n\nGiven a string `s`, write a function... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2985,
"level": 1,
"question": "In Dreamland, a special type of string called a \"Symmetric String\" is celebrated. A string is considered symmetric if it reads the same forwards and backwards. For example, the string \"level\" is symmetric, whereas the string \"coding\" is not.\n\nG... |
from typing import List
def longestSubarrayWithSumK(arr: List[int], k: int) -> int:
sum_map = {0: -1}
current_sum = 0
max_length = 0
for i, num in enumerate(arr):
current_sum += num
target = current_sum - k
if target in sum_map:
length = i - sum_map[target]
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question\n\n#### Problem Statement\nGiven an array of integers, you are tasked with implementing a function `longestSubarrayWithSumK(arr: List[int], k: int) -> int` that finds the length of the longest continuous subarray with a sum equal to a given value `k`.\n\n### Input an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2986,
"level": 1,
"question": "### Coding Question\n\n#### Problem Statement\nGiven an array of integers, you are tasked with implementing a function `longestSubarrayWithSumK(arr: List[int], k: int) -> int` that finds the length of the longest continuous subarray with a sum equal to... |
def is_subset_sum(arr, x):
if x == 0:
return True
dp = [False] * (x + 1)
dp[0] = True
for num in arr:
for s in range(x, num - 1, -1):
if dp[s - num]:
dp[s] = True
return dp[x] | simplelr_Leetcode | [
{
"content": "Question:\nYou are provided with an array of positive integers `arr` and an integer `x`. Your task is to determine if there is a subset of `arr` such that the sum of the elements of the subset is equal to `x`. Return _true_ if such a subset exists, or _false_ otherwise.\nAnswer:\nLet's think step ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2987,
"level": 1,
"question": "You are provided with an array of positive integers `arr` and an integer `x`. Your task is to determine if there is a subset of `arr` such that the sum of the elements of the subset is equal to `x`. Return _true_ if such a subset exists, or _false_ oth... |
def intersection(list1, list2):
return list(set(list1) & set(list2)) | simplelr_Filter | [
{
"content": "Question:\nBuild a Python code snippet to determine the intersection of two provided lists, considering only unique elements without duplicates.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2988,
"level": 1,
"question": "Build a Python code snippet to determine the intersection of two provided lists, considering only unique elements without duplicates.",
"split": "train"
} |
def intersect(arr1, arr2):
"""This function returns the intersection of two lists.
Parameters:
arr1 (list): The first list
arr2 (list): The second list
Returns:
list: A new list containing elements common to both lists
"""
return [value for value in arr1 if value in arr2] | simplelr_Filter | [
{
"content": "Question:\ndef intersect(arr1, arr2):\n \"\"\"This function returns the intersection of two lists.\n \n Parameters:\n arr1 (list): The first list\n arr2 (list): The second list\n \n Returns:\n list: A new list containing elements common to both lists\n \"\"\"\n \n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2989,
"level": 1,
"question": "def intersect(arr1, arr2):\n \"\"\"This function returns the intersection of two lists.\n \n Parameters:\n arr1 (list): The first list\n arr2 (list): The second list\n \n Returns:\n list: A new list containing elements common to... |
import re
def isPalindrome(s):
# Remove all non-alphanumeric characters and convert to lowercase
cleaned = re.sub('[^a-zA-Z0-9]', '', s).lower()
# Check if the cleaned string is equal to its reverse
return cleaned == cleaned[::-1]
# Test cases
test_cases = [
("racecar", True),
("RaceCar", True... | simplelr_Evol | [
{
"content": "Question:\nConstruct a function called `isPalindrome` which takes a string as an input and returns a boolean indicating whether the string is a palindrome (a word, phrase, or sequence that reads the same backward as forward, ignoring spaces, punctuation, and capitalization). Provide a set of test ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2990,
"level": 1,
"question": "Construct a function called `isPalindrome` which takes a string as an input and returns a boolean indicating whether the string is a palindrome (a word, phrase, or sequence that reads the same backward as forward, ignoring spaces, punctuation, and capi... |
def bankers_rounding(x):
n = int(x)
f = x - n
if abs(f) == 0.5:
if f > 0:
if n % 2 == 0:
return n
else:
return n + 1
else:
if n % 2 == 0:
return n
else:
return n - 1
else:
... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function to round a given floating-point number to the nearest integer. If the fractional part is exactly 0.5, the function should round to the nearest even integer. This is also known as \"bankers' rounding.\" The function should not use any external libraries.\nAnswer:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2991,
"level": 1,
"question": "Create a Python function to round a given floating-point number to the nearest integer. If the fractional part is exactly 0.5, the function should round to the nearest even integer. This is also known as \"bankers' rounding.\" The function should not u... |
def sort_numbers(lst):
negatives = []
non_negatives = []
for num in lst:
if num < 0:
negatives.append(num)
else:
non_negatives.append(num)
sorted_neg = sorted(negatives)
sorted_non_neg = sorted(non_negatives)
return sorted_neg + sorted_non_neg | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes in a list of integers and returns a new list with the elements sorted in ascending order. However, any negative numbers should be placed at the beginning of the list, followed by the positive numbers including zero, all in ascending order separately within th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2992,
"level": 1,
"question": "Write a function that takes in a list of integers and returns a new list with the elements sorted in ascending order. However, any negative numbers should be placed at the beginning of the list, followed by the positive numbers including zero, all in a... |
def find_two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return [] | simplelr_Package | [
{
"content": "Question:\nCreate a function that takes a list of integers and an integer target. The function should return indices of the two numbers such that they add up to the target, using a dictionary to store and look up the needed complement values. If no such indices exist, return an empty list. The fun... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2993,
"level": 1,
"question": "Create a function that takes a list of integers and an integer target. The function should return indices of the two numbers such that they add up to the target, using a dictionary to store and look up the needed complement values. If no such indices e... |
import re
from typing import List
def transform_emails(email_list: List[str]) -> List[str]:
pattern = re.compile(r'^[a-z0-9_.-]+@[a-z]+(\.[a-z]+)+$')
transformed_emails = []
for email in email_list:
if pattern.match(email):
username = email.split('@')[0]
transformed_email = ... | simplelr_Docs | [
{
"content": "Question:\n### Regular Expression Validation and Transformation\n\nIn this coding assessment, you are required to implement a function that validates and transforms a list of email addresses using regular expressions. The function will perform the following tasks:\n\n1. **Validation**: Ensure that... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2994,
"level": 1,
"question": "### Regular Expression Validation and Transformation\n\nIn this coding assessment, you are required to implement a function that validates and transforms a list of email addresses using regular expressions. The function will perform the following tasks... |
def is_subsequence(s1, s2):
i = j = 0
while i < len(s1) and j < len(s2):
if s1[i] == s2[j]:
j += 1
i += 1
return j == len(s2)
s1 = "Greatest"
s2 = "Great"
print(is_subsequence(s1, s2)) # Output: True | simplelr_Filter | [
{
"content": "Question:\nGiven two strings s1 = \"Greatest\" and s2 = \"Great\", write a Python program to find out if s2 is a subsequence of s1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2995,
"level": 1,
"question": "Given two strings s1 = \"Greatest\" and s2 = \"Great\", write a Python program to find out if s2 is a subsequence of s1.",
"split": "train"
} |
def has_permutation_of_first_k_naturals(arr, k):
n = len(arr)
if k == 0:
return False
if k > n:
return False
s = k * (k + 1) // 2
# Precompute prefix_bad: count of elements not in [1, k]
prefix_bad = [0] * (n + 1)
for i in range(n):
if arr[i] < 1 or arr[i] > k:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` and an integer `k`. Your task is to determine if there exists a subarray of length `k` that is a permutation of the first `k` natural numbers. Return `true` if such a subarray exists and `false` otherwise.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2996,
"level": 1,
"question": "You are given an array of integers `arr` and an integer `k`. Your task is to determine if there exists a subarray of length `k` that is a permutation of the first `k` natural numbers. Return `true` if such a subarray exists and `false` otherwise.",
"... |
def is_palindrome(s):
cleaned = [char.lower() for char in s if char.isalnum()]
cleaned_str = ''.join(cleaned)
return cleaned_str == cleaned_str[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if a given string is a palindrome by ignoring case and non-alphanumeric characters. A palindrome is a string that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. For example, \"A man, a plan, a canal, Panama\" is a pal... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2997,
"level": 1,
"question": "Create a function that checks if a given string is a palindrome by ignoring case and non-alphanumeric characters. A palindrome is a string that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. For example, \"A man,... |
from typing import List
from collections import Counter
def calculate_ranks(scores: List[int]) -> List[int]:
if not scores:
return []
freq = Counter(scores)
unique_sorted = sorted(freq.keys(), reverse=True)
cumulative = []
total = 0
for s in unique_sorted:
cumulative.a... | simplelr_Taco | [
{
"content": "Question:\nA company organizes a coding competition where participants earn points based on their performance. Each participant is awarded a score between 0 and 100, inclusive.\n\nGiven an array of integers representing the scores of participants, the organizers want to determine the rank of each ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2998,
"level": 1,
"question": "A company organizes a coding competition where participants earn points based on their performance. Each participant is awarded a score between 0 and 100, inclusive.\n\nGiven an array of integers representing the scores of participants, the organizers ... |
import re
def extract_emails(input_file, output_file):
"""
Extracts emails from the input file and saves them to the output file, each on a new line.
"""
# Regular expression pattern for matching email addresses
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
try:
... | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python script that extracts emails from a text file and saves them to a new file, each email on a new line?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2999,
"level": 1,
"question": "Can you help me with a Python script that extracts emails from a text file and saves them to a new file, each email on a new line?",
"split": "train"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.