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 heapq
from typing import List
def merge_sorted_arrays(sorted_arrays: List[List[int]]) -> List[int]:
heap = []
for i, arr in enumerate(sorted_arrays):
if len(arr) > 0:
heapq.heappush(heap, (arr[0], i, 0))
result = []
while heap:
val, arr_idx, elem_idx = heapq.heap... | simplelr_Package | [
{
"content": "Question:\nYou are assigned to create a function named `merge_sorted_arrays` which merges multiple sorted arrays into a single sorted array. The function should take a list of sorted arrays and return a single sorted array containing all the elements from the input arrays.\n\nThe function `merge_s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 500,
"level": 1,
"question": "You are assigned to create a function named `merge_sorted_arrays` which merges multiple sorted arrays into a single sorted array. The function should take a list of sorted arrays and return a single sorted array containing all the elements from the inpu... |
def min_max_difference(arr):
if not arr:
return 0
return max(arr) - min(arr) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers as input and returns the difference between the largest and smallest numbers in the array. If the array is empty, return 0.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 501,
"level": 1,
"question": "Create a function that takes an array of integers as input and returns the difference between the largest and smallest numbers in the array. If the array is empty, return 0.",
"split": "train"
} |
def filter_dict_by_keys(d, lst):
return {key: d[key] for key in lst if key in d} | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that takes a dictionary and a list as input, and returns a new dictionary that contains only the key-value pairs found in the list? For instance, if I have a dictionary {'color1':'red', 'color2':'blue', 'color3':'green'} and a list ['color1', 'color3']... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 502,
"level": 1,
"question": "How can I create a Python function that takes a dictionary and a list as input, and returns a new dictionary that contains only the key-value pairs found in the list? For instance, if I have a dictionary {'color1':'red', 'color2':'blue', 'color3':'green... |
def sum_of_squares_of_odds(nums):
return sum(num ** 2 for num in nums if num % 2 == 1) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a list of integers as input and returns the sum of the squares of all the odd numbers in the list. Use list comprehension for this task. The function should be efficient and concise.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 503,
"level": 1,
"question": "Create a Python function that takes a list of integers as input and returns the sum of the squares of all the odd numbers in the list. Use list comprehension for this task. The function should be efficient and concise.",
"split": "train"
} |
def productExceptSelf(nums):
n = len(nums)
prefix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]
result = [1] * n
suffix_product = 1
for i in range(n-1, -1, -1):
result[i] = prefix[i] * suffix_product
suffix_product *= nums[i]
return res... | simplelr_Codeforces | [
{
"content": "Question:\nImagine that you have an array of integers, and you want to transform it such that the element at each index becomes the product of all the elements in the array except the one at that index. However, you must do this without using division.\n\nWrite a function `productExceptSelf(nums)`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 504,
"level": 1,
"question": "Imagine that you have an array of integers, and you want to transform it such that the element at each index becomes the product of all the elements in the array except the one at that index. However, you must do this without using division.\n\nWrite a ... |
def findDiagonalOrder(matrix):
if not matrix or not matrix[0]:
return []
result = []
m = len(matrix)
n = len(matrix[0])
max_s = (m - 1) + (n - 1)
for s in range(0, max_s + 1):
group = []
start_i = max(0, s - (n - 1))
end_i = min(m - 1, s)
for i in range(st... | simplelr_Algorithm | [
{
"content": "Question:\n### Matrix Diagonal Traverse\n\n#### Problem Description\nGiven an m x n matrix, return an array of all the elements of the matrix in a diagonal order. The diagonal order is defined such that for each diagonal, elements are accessed starting from the right to the left and top to the bot... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 505,
"level": 1,
"question": "### Matrix Diagonal Traverse\n\n#### Problem Description\nGiven an m x n matrix, return an array of all the elements of the matrix in a diagonal order. The diagonal order is defined such that for each diagonal, elements are accessed starting from the ri... |
from typing import List
def rotate_image(matrix: List[List[int]]) -> None:
if not matrix:
return
n = len(matrix)
# Transpose the matrix in place
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 in ... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given an n x n 2D `matrix` that represents an image. Write a function `rotate_image(matrix)` that rotates the image by 90 degrees clockwise in-place.\n\n### Input:\n* `matrix`: A list of lists where each inner list has `n` integers, representing an n x n grid of image pixel valu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 506,
"level": 1,
"question": "You are given an n x n 2D `matrix` that represents an image. Write a function `rotate_image(matrix)` that rotates the image by 90 degrees clockwise in-place.\n\n### Input:\n* `matrix`: A list of lists where each inner list has `n` integers, representing... |
def count_distinct_substrings(s):
sa = [{'trans': {}, 'link': -1, 'len': 0}]
size = 1
last = 0
for c in s:
curr = size
sa.append({'trans': {}, 'link': -1, 'len': sa[last]['len'] + 1})
size += 1
p = last
while p != -1 and c not in sa[p]['trans']:
sa[p... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` consisting of lowercase English letters, we need to calculate the number of distinct substrings (consecutive characters) that can be formed from the string. A substring is defined as any sequence of consecutive characters of `s`. Return the total number of distinct su... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 507,
"level": 1,
"question": "Given a string `s` consisting of lowercase English letters, we need to calculate the number of distinct substrings (consecutive characters) that can be formed from the string. A substring is defined as any sequence of consecutive characters of `s`. Retu... |
def find_highest_balance_account(transactions):
balances = {}
account_order = []
for trans in transactions:
account = trans[0]
t_type = trans[1]
amount = trans[2]
if account not in balances:
balances[account] = 0
account_order.append(account)
i... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of bank account transactions represented as a 2D array `transactions` where each `transactions[i] = [accountNumberi, transactionTypei, amounti]`. `accountNumberi` is a string representing a unique account number, `transactionTypei` is a string that can either be `\"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 508,
"level": 1,
"question": "You are given a list of bank account transactions represented as a 2D array `transactions` where each `transactions[i] = [accountNumberi, transactionTypei, amounti]`. `accountNumberi` is a string representing a unique account number, `transactionTypei` ... |
def max_items_within_budget(costs, budget):
sorted_costs = sorted(costs)
total = 0
count = 0
for cost in sorted_costs:
if total + cost > budget:
break
total += cost
count += 1
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `costs` where `costs[i]` represents the cost of the `i-th` item for a shopping list. You are also given an integer `budget` that represents the maximum amount of money you can spend. You are allowed to pick any number of items from the array such that thei... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 509,
"level": 1,
"question": "You are given an integer array `costs` where `costs[i]` represents the cost of the `i-th` item for a shopping list. You are also given an integer `budget` that represents the maximum amount of money you can spend. You are allowed to pick any number of i... |
def add_bitwise(a: int, b: int) -> int:
while b != 0:
sum_without_carry = a ^ b
carry = (a & b) << 1
a = sum_without_carry
b = carry
return a | simplelr_Data_Structure | [
{
"content": "Question:\n## Problem Statement\n\nYou are given two positive integers, `a` and `b`. Your task is to implement a function that adds these two integers without using the `+` operator. Instead, you need to use bitwise operations to achieve the result.\n\n### Function Signature\n```python\ndef add_bi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 510,
"level": 1,
"question": "## Problem Statement\n\nYou are given two positive integers, `a` and `b`. Your task is to implement a function that adds these two integers without using the `+` operator. Instead, you need to use bitwise operations to achieve the result.\n\n### Functio... |
def row_with_max_1s(matrix):
# Check if the input is a non-empty list
if not isinstance(matrix, list) or len(matrix) == 0:
return None
# Iterate through each row to check validity
for row in matrix:
# Check if the row is a list
if not isinstance(row, list):
return Non... | simplelr_Taco | [
{
"content": "Question:\nA binary matrix is a matrix consisting of only 0s and 1s. You are given a binary matrix and are asked to find the row with the maximum number of 1s. If there are multiple rows with the same maximum number of 1s, return the index (0 based) of the first such row.\n\nTo make the task more ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 511,
"level": 1,
"question": "A binary matrix is a matrix consisting of only 0s and 1s. You are given a binary matrix and are asked to find the row with the maximum number of 1s. If there are multiple rows with the same maximum number of 1s, return the index (0 based) of the first s... |
def format_text(text, line_width):
words = text.split()
lines = []
current_line = []
current_length = 0
for word in words:
if len(word) > line_width:
if current_line:
lines.append(' '.join(current_line))
lines.append(word)
current_line = [... | simplelr_Apps | [
{
"content": "Question:\nYou are working on a word processing application and need to implement a feature that automatically formats a block of text into a specified line width. This feature should ensure that no words are broken between lines (i.e., words should not be split to fit into the line width) and sho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 512,
"level": 1,
"question": "You are working on a word processing application and need to implement a feature that automatically formats a block of text into a specified line width. This feature should ensure that no words are broken between lines (i.e., words should not be split t... |
def maxSubarraySum(arr, k):
if k <= 0 or len(arr) < k:
return 0
current_sum = sum(arr[:k])
max_sum = current_sum
for i in range(k, len(arr)):
current_sum += arr[i] - arr[i - k]
if current_sum > max_sum:
max_sum = current_sum
return max_sum | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of integers `arr`, return the maximum sum of any contiguous subarray of length `k`. If the list contains fewer than `k` elements, return 0. Implement the function `maxSubarraySum(arr, k)` which takes in a list of integers `arr` and an integer `k` and returns an integer repr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 513,
"level": 1,
"question": "Given a list of integers `arr`, return the maximum sum of any contiguous subarray of length `k`. If the list contains fewer than `k` elements, return 0. Implement the function `maxSubarraySum(arr, k)` which takes in a list of integers `arr` and an integ... |
def max_non_conflicting_events(events):
if not events:
return 0
# Sort events by end time
events.sort(key=lambda x: x[1])
count = 1
last_end = events[0][1]
for event in events[1:]:
if event[0] >= last_end:
count += 1
last_end = event[1]
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of events, where each event is represented as a list `[start, end]` with `start` as the start time and `end` as the end time. Two events are considered to be conflicting if they overlap. Your task is to find and return _the maximum number of non-conflicting events t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 514,
"level": 1,
"question": "You are given a list of events, where each event is represented as a list `[start, end]` with `start` as the start time and `end` as the end time. Two events are considered to be conflicting if they overlap. Your task is to find and return _the maximum ... |
import math
def exponential_quantile(p, lambda_):
"""
Computes the quantile function of an exponential distribution.
Parameters:
p (float): The probability, must be between 0 and 1.
lambda_ (float): The rate parameter, must be positive.
Returns:
float: The quantile value correspon... | simplelr_Filter | [
{
"content": "Question:\nDetermine the quantile function of an exponential distribution and write a Python function to implement this. Furthermore debug the following erroneous code used to generate quantile from an exponential distribution.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 515,
"level": 1,
"question": "Determine the quantile function of an exponential distribution and write a Python function to implement this. Furthermore debug the following erroneous code used to generate quantile from an exponential distribution.",
"split": "train"
} |
def sieve_of_eratosthenes(limit):
if limit < 2:
return []
sieve = [True] * (limit + 1)
sieve[0], sieve[1] = False, False
for p in range(2, int(limit ** 0.5) + 1):
if sieve[p]:
for multiple in range(p * p, limit + 1, p):
sieve[multiple] = False
primes = [i ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to generate a list of all prime numbers up to a given limit using the Sieve of Eratosthenes algorithm. The function should be efficient and handle large ranges effectively.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 516,
"level": 1,
"question": "Write a function to generate a list of all prime numbers up to a given limit using the Sieve of Eratosthenes algorithm. The function should be efficient and handle large ranges effectively.",
"split": "train"
} |
def divide_even_odd(numbers):
evens = [num for num in numbers if num % 2 == 0]
odds = [num for num in numbers if num % 2 != 0]
return (evens, odds) | simplelr_Filter | [
{
"content": "Question:\nYou have been tasked with creating a function that will divide a list of integers into two separate lists: one for even numbers and one for odd numbers. The function should take a list of integers as input and return a tuple containing two lists.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 517,
"level": 1,
"question": "You have been tasked with creating a function that will divide a list of integers into two separate lists: one for even numbers and one for odd numbers. The function should take a list of integers as input and return a tuple containing two lists.",
"s... |
def find_sessions_with_items(sessions: list[set[str]], shopping_list: set[str]) -> list[int]:
result = []
if not shopping_list:
return list(range(len(sessions)))
required = len(shopping_list)
for index, session in enumerate(sessions):
if len(session) >= required and shopping_list.issubse... | simplelr_Algorithm | [
{
"content": "Question:\n### Programming Assessment Question\n\n**Context**: You are developing an e-commerce platform, and as part of your user analytics, you need to identify patterns in user browsing behavior. One of the tasks is to find which user sessions contain all the items from a given shopping list.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 518,
"level": 1,
"question": "### Programming Assessment Question\n\n**Context**: You are developing an e-commerce platform, and as part of your user analytics, you need to identify patterns in user browsing behavior. One of the tasks is to find which user sessions contain all the i... |
def find_longest_word(text):
text = text.strip()
if not text:
return ""
words = text.split()
max_length = len(words[0])
longest = words[0]
for word in words[1:]:
current_length = len(word)
if current_length > max_length:
max_length = current_length
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the longest word in a given text.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 519,
"level": 1,
"question": "Write a python function to find the longest word in a given text.",
"split": "train"
} |
def contains_sequence(main_string, sequence):
return sequence in main_string | simplelr_Filter | [
{
"content": "Question:\nYou have been tasked with writing a function that determines whether a given string contains a certain sequence of characters. The function should take in two parameters: the string to be searched and the sequence to be found. It should return True if the sequence is found in the string... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 520,
"level": 1,
"question": "You have been tasked with writing a function that determines whether a given string contains a certain sequence of characters. The function should take in two parameters: the string to be searched and the sequence to be found. It should return True if t... |
from collections import deque
from typing import List, Tuple
def transitive_closure(n: int, edges: List[Tuple[int, int]]) -> List[List[bool]]:
# Build the adjacency list
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
# Initialize the closure matrix with False
closure ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Graph Transitive Closure\n\nYou are given a directed graph represented using adjacency lists. Your task is to find the transitive closure of this graph. The transitive closure of a graph is a reachability matrix where `closure[i][j]` is `True` if there is a path from vertex `i` to v... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 521,
"level": 1,
"question": "### Graph Transitive Closure\n\nYou are given a directed graph represented using adjacency lists. Your task is to find the transitive closure of this graph. The transitive closure of a graph is a reachability matrix where `closure[i][j]` is `True` if th... |
from typing import List
def min_path_sum(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
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]
for i in range(1, m):
curr... | simplelr_Algorithm | [
{
"content": "Question:\n**Graph Traversal Challenge: Minimum Path Sum**\n\n### Problem Statement:\nGiven a 2D grid of size `m x n` where each cell contains a non-negative integer representing the cost to traverse through that cell, find a path from the top-left corner to the bottom-right corner which minimizes... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 522,
"level": 1,
"question": "**Graph Traversal Challenge: Minimum Path Sum**\n\n### Problem Statement:\nGiven a 2D grid of size `m x n` where each cell contains a non-negative integer representing the cost to traverse through that cell, find a path from the top-left corner to the b... |
import math
def sieve_of_eratosthenes(n):
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0], sieve[1] = False, 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 = [i for i, is_prime in enume... | simplelr_Filter | [
{
"content": "Question:\nProvide a Python function that generates a list of all prime numbers up to a given number `n` using the Sieve of Eratosthenes algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 523,
"level": 1,
"question": "Provide a Python function that generates a list of all prime numbers up to a given number `n` using the Sieve of Eratosthenes algorithm.",
"split": "train"
} |
def shift_chars(s: str) -> str:
result = []
for c in s:
shifted_ord = ((ord(c) - ord('a') + 2) % 26) + ord('a')
result.append(chr(shifted_ord))
return ''.join(result) | simplelr_Codeforces | [
{
"content": "Question:\nCreate a function that takes a string consisting of lowercase letters and returns a new string where each character is replaced by the character two positions ahead in the alphabet (wrapping from 'z' to 'a' if necessary). For example, 'a' should be replaced by 'c', 'y' should be replace... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 524,
"level": 1,
"question": "Create a function that takes a string consisting of lowercase letters and returns a new string where each character is replaced by the character two positions ahead in the alphabet (wrapping from 'z' to 'a' if necessary). For example, 'a' should be repl... |
import bisect
def count_subarrays_with_sum_less_than_k(nums: list, K: int) -> int:
prefix = [0]
for num in nums:
prefix.append(prefix[-1] + num)
count = 0
for i in range(len(nums)):
target = prefix[i] + K
m = bisect.bisect_left(prefix, target, i + 1, len(prefix))
count +... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem: Counting Subarrays with Sum Less Than K\n\nYou are tasked with determining the number of contiguous subarrays within an array of positive integers such that the sum of the elements in the subarray is strictly less than a given integer `K`.\n\n**Objective**:\nWrite a functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 525,
"level": 1,
"question": "### Problem: Counting Subarrays with Sum Less Than K\n\nYou are tasked with determining the number of contiguous subarrays within an array of positive integers such that the sum of the elements in the subarray is strictly less than a given integer `K`.\... |
def special_flatten(input_arr: list) -> list:
result = []
stack = [input_arr]
while stack:
current = stack.pop()
if current is None:
continue
if isinstance(current, list):
for elem in reversed(current):
stack.append(elem)
else:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Flatten Array and Manage Special Cases\n\n#### Context:\nYou are developing a utility for data preprocessing. One of its functionalities is to transform nested arrays into a flat structure. However, you are aware that strings should not be split into characters, and deeply... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 526,
"level": 1,
"question": "### Question: Flatten Array and Manage Special Cases\n\n#### Context:\nYou are developing a utility for data preprocessing. One of its functionalities is to transform nested arrays into a flat structure. However, you are aware that strings should not be... |
from typing import List
def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
This function takes a 2D list (matrix) as input and returns its transpose.
The transpose of a matrix is formed by swapping the rows and columns.
"""
return [list(row) for row in zip(*matrix)] | simplelr_Package | [
{
"content": "Question:\nYou need to implement a function named `transpose_matrix` that takes a 2-dimensional list (matrix) and returns its transpose. The transpose of a matrix is formed by swapping the rows and columns.\n\n**Function Signature:**\n```python\ndef transpose_matrix(matrix: List[List[int]]) -> Lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 527,
"level": 1,
"question": "You need to implement a function named `transpose_matrix` that takes a 2-dimensional list (matrix) and returns its transpose. The transpose of a matrix is formed by swapping the rows and columns.\n\n**Function Signature:**\n```python\ndef transpose_matr... |
def num_digits(n):
if n == 0:
return 1
return len(str(abs(n))) | simplelr_Data_Structure | [
{
"content": "Question:\n### Num Digits Function Implementation\n\nImplement a function `num_digits(n)` that computes the number of digits in a given integer number `n`. Your function should handle both positive and negative integers as well as zero. The implementation must be efficient, with a constant time co... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 528,
"level": 1,
"question": "### Num Digits Function Implementation\n\nImplement a function `num_digits(n)` that computes the number of digits in a given integer number `n`. Your function should handle both positive and negative integers as well as zero. The implementation must be ... |
def reverse_alpha_words(strings):
result = []
for string in strings:
words = string.split()
transformed = []
for word in words:
if word.isalpha():
transformed.append(word[::-1])
else:
transformed.append(word)
result.append('... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of strings where each string can contain words separated by spaces. We want to transform each string such that any word in the string that consists of only alphabetic characters is reversed. If the word contains any non-alphabetic characters, it remains unchanged. \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 529,
"level": 1,
"question": "You are given a list of strings where each string can contain words separated by spaces. We want to transform each string such that any word in the string that consists of only alphabetic characters is reversed. If the word contains any non-alphabetic c... |
def calculate_discount(price, discount_percent):
return price * (1 - discount_percent / 100) | simplelr_Filter | [
{
"content": "Question:\nImplement a Python function called calculate_discount that takes a price and a discount percentage as input and returns the discounted price.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 530,
"level": 1,
"question": "Implement a Python function called calculate_discount that takes a price and a discount percentage as input and returns the discounted price.",
"split": "train"
} |
import heapq
from collections import defaultdict
def get_skyline(buildings):
if not buildings:
return []
# Create events
events = []
for L, R, H in buildings:
events.append((L, 1, H))
events.append((R, 0, H))
# Sort events by x, then by type (end events before star... | simplelr_Data_Structure | [
{
"content": "Question:\n### Task: Compute the Skyline of a City\n\nYou are given a list of buildings in a city, where each building is represented by a triplet of integers `[Li, Ri, Hi]`, where `Li` and `Ri` are the x coordinates of the left and right edge of the i-th building, respectively, and `Hi` is its he... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 531,
"level": 1,
"question": "### Task: Compute the Skyline of a City\n\nYou are given a list of buildings in a city, where each building is represented by a triplet of integers `[Li, Ri, Hi]`, where `Li` and `Ri` are the x coordinates of the left and right edge of the i-th building... |
def custom_find(string: str, substring: str) -> int:
if not substring:
return 0
if len(substring) > len(string):
return -1
m = len(substring)
lps = [0] * m
length = 0 # Length of the previous longest prefix suffix
# Preprocess the substring to create the LPS array
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are tasked with implementing a custom made string search function to mimic the behavior of Python's built-in `str.find` method. The function should locate the lowest index of the substring within a given string. \n\n### Requirements:\n- Implement the functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 532,
"level": 1,
"question": "### Problem Statement\n\nYou are tasked with implementing a custom made string search function to mimic the behavior of Python's built-in `str.find` method. The function should locate the lowest index of the substring within a given string. \n\n### Requ... |
def reverse_string(s):
s = list(s)
left = 0
right = len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
return ''.join(s) | simplelr_Filter | [
{
"content": "Question:\nComplete the following function to output a reversed string, but you are not allowed to use any built-in string reversal functions or create any new string variables. You can only modify the given string in-place and return it.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 533,
"level": 1,
"question": "Complete the following function to output a reversed string, but you are not allowed to use any built-in string reversal functions or create any new string variables. You can only modify the given string in-place and return it.",
"split": "train"
} |
def hex_to_binary(hex_str):
decimal = int(hex_str, 16)
return bin(decimal)[2:] | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function that converts a hexadecimal number to its binary representation?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 534,
"level": 1,
"question": "Can you provide a Python function that converts a hexadecimal number to its binary representation?",
"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 arr[mid] > target:
high = mid - 1
else:
low = mid + 1
return -1
example_usage = binary_searc... | simplelr_Filter | [
{
"content": "Question:\nHere is a code snippet for a simple implementation of a binary search algorithm in Python. Can you please help me by explaining what the binary search algorithm is and providing an example use case for the given code?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 535,
"level": 1,
"question": "Here is a code snippet for a simple implementation of a binary search algorithm in Python. Can you please help me by explaining what the binary search algorithm is and providing an example use case for the given code?",
"split": "train"
} |
import re
from collections import defaultdict
from typing import List, Dict
def generate_word_cloud(text: str, stopwords: List[str]) -> Dict[str, int]:
text_lower = text.lower()
words = re.findall(r"[a-z']+", text_lower)
stopword_set = {word.lower() for word in stopwords}
frequency = defaultdict(int)
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nImplement a function that generates a \"word cloud\" from a given text. This word cloud should ignore common English stopwords and represent the frequency of each word proportionally.\n\n### Function Signature\n```python\ndef generate_word_cloud(text: str, stopw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 536,
"level": 1,
"question": "### Problem Statement\n\nImplement a function that generates a \"word cloud\" from a given text. This word cloud should ignore common English stopwords and represent the frequency of each word proportionally.\n\n### Function Signature\n```python\ndef ge... |
def remove_duplicates(nums):
if not nums:
return 0
write_pointer = 0
for i in range(1, len(nums)):
if nums[i] != nums[write_pointer]:
write_pointer += 1
nums[write_pointer] = nums[i]
return write_pointer + 1 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove duplicates from a sorted array and return the new length. The order of elements should be maintained.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 537,
"level": 1,
"question": "Write a python function to remove duplicates from a sorted array and return the new length. The order of elements should be maintained.",
"split": "train"
} |
from typing import List
def sort_names(names: List[str]) -> List[str]:
return sorted(names, key=lambda x: (x.split()[1], x.split()[0])) | simplelr_Algorithm | [
{
"content": "Question:\n### Sorting Names by Last Name\n\nSuppose you are given a list of names and you need to sort them by their last name. If two people have the same last name, sort by their first name.\n\n### Your Task\nWrite a Python function, `sort_names`, which will:\n1. Take a list of names as input. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 538,
"level": 1,
"question": "### Sorting Names by Last Name\n\nSuppose you are given a list of names and you need to sort them by their last name. If two people have the same last name, sort by their first name.\n\n### Your Task\nWrite a Python function, `sort_names`, which will:\n... |
def num_ones_in_submatrix(grid, queries):
if not grid:
return []
m = len(grid)
n = len(grid[0])
# Initialize prefix sum matrix with an additional row and column of zeros
prefix = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** binary matrix `grid` of size `m x n` where each cell has a value `0` or `1`. You are also given a **0-indexed** integer `queries` consisting of integer pairs `(r1, c1, r2, c2)` which represent the top-left and bottom-right coordinates of a submatrix. For ea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 539,
"level": 1,
"question": "You are given a **0-indexed** binary matrix `grid` of size `m x n` where each cell has a value `0` or `1`. You are also given a **0-indexed** integer `queries` consisting of integer pairs `(r1, c1, r2, c2)` which represent the top-left and bottom-right ... |
from collections import deque
from typing import Dict, List, Optional
def find_shortest_path(graph: Dict[int, List[int]], start: int, end: int) -> Optional[List[int]]:
if start not in graph or end not in graph:
return None
if start == end:
return [start]
visited = set()
visited.add... | simplelr_Evol | [
{
"content": "Question:\nImplement a function that finds the shortest path between two nodes in an unweighted graph represented by an adjacency list. The function should handle disconnected graphs and return None if there is no path between the nodes.\n\nYour function should be able to handle graphs with cycles... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 540,
"level": 1,
"question": "Implement a function that finds the shortest path between two nodes in an unweighted graph represented by an adjacency list. The function should handle disconnected graphs and return None if there is no path between the nodes.\n\nYour function should be... |
def minRewards(scores: list[int]) -> int:
if not scores:
return 0
n = len(scores)
rewards = [1] * n # Initialize all rewards to 1
# Left to right pass
for i in range(1, n):
if scores[i] > scores[i-1]:
if rewards[i] <= rewards[i-1]:
rewards[i] = rewards[i... | simplelr_Taco | [
{
"content": "Question:\nYou are given an array of integers representing the scores of students in a class. A round of class competition awards a reward to students based on their scores following this distribution rule:\n\nEach student gets a reward of 1 point initially. For each student i (0 <= i < n):\n1. If... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 541,
"level": 1,
"question": "You are given an array of integers representing the scores of students in a class. A round of class competition awards a reward to students based on their scores following this distribution rule:\n\nEach student gets a reward of 1 point initially. For e... |
def count_words(s):
return len(s.split())
# Example usage:
print(count_words("Hello world")) # Output: 2 | simplelr_Filter | [
{
"content": "Question:\nHow can I determine the total number of words in a string using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 542,
"level": 1,
"question": "How can I determine the total number of words in a string using Python?",
"split": "train"
} |
def evaluate_expression(s):
terms = s.split('+')
total = 0
for term in terms:
factors = term.split('*')
product = 1
for f in factors:
product *= int(f)
total += product
return total
| simplelr_Taco | [
{
"content": "Question:\nImplement a function that takes a string containing a mathematical expression containing additions (+) and multiplications (*) and evaluates it, respecting the standard order of operations (multiplication before addition). The function should return the result as an integer. You can ass... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 543,
"level": 1,
"question": "Implement a function that takes a string containing a mathematical expression containing additions (+) and multiplications (*) and evaluates it, respecting the standard order of operations (multiplication before addition). The function should return the... |
def is_balanced_parentheses(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Filter | [
{
"content": "Question:\nDesign an algorithm to verify the parentheses in a given string. The string can contain characters other than parentheses, which should be ignored. The algorithm should ensure that every opening parenthesis has a corresponding closing parenthesis in the correct order and return `True` i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 544,
"level": 1,
"question": "Design an algorithm to verify the parentheses in a given string. The string can contain characters other than parentheses, which should be ignored. The algorithm should ensure that every opening parenthesis has a corresponding closing parenthesis in the... |
from typing import List
def custom_sort(numbers: List[int]) -> List[int]:
evens = []
odds = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens + odds | simplelr_Package | [
{
"content": "Question:\nYou are tasked to implement a function for a sorting challenge that modifies a traditional sorting algorithm to meet certain criteria. The goal of the function is to sort a list of integers such that all even numbers come before all odd numbers while maintaining the relative order of bo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 545,
"level": 1,
"question": "You are tasked to implement a function for a sorting challenge that modifies a traditional sorting algorithm to meet certain criteria. The goal of the function is to sort a list of integers such that all even numbers come before all odd numbers while ma... |
import bisect
def min_moves_to_sort_heights(heights):
tails = []
for h in heights:
idx = bisect.bisect_right(tails, h)
if idx == len(tails):
tails.append(h)
else:
tails[idx] = h
return len(heights) - len(tails) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `heights` representing the height of students standing in a line. A group photo can only be taken when the students stand in **non-decreasing** order of their heights. Your task is to determine the minimum number of students that need to be moved to ac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 546,
"level": 1,
"question": "You are given an array of integers `heights` representing the height of students standing in a line. A group photo can only be taken when the students stand in **non-decreasing** order of their heights. Your task is to determine the minimum number of st... |
def has_all_unique_chars(s: str) -> bool:
seen = [False] * 26
for c in s:
idx = ord(c) - ord('a')
if seen[idx]:
return False
seen[idx] = True
return True | simplelr_Algorithm | [
{
"content": "Question:\nAnalyze String with Unique Characters\n\n#### Context\nYou are given a string, and you need to determine if all characters in the string are unique. This is a common task in various applications, such as ensuring that a userID only contains unique characters.\n\n#### Function Signature\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 547,
"level": 1,
"question": "Analyze String with Unique Characters\n\n#### Context\nYou are given a string, and you need to determine if all characters in the string are unique. This is a common task in various applications, such as ensuring that a userID only contains unique chara... |
import re
def extract_words(s):
return re.findall(r'[A-Za-z0-9]+', s) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns a list of all the words in the string. Words are defined as sequences of alphanumeric characters separated by non-alphanumeric characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 548,
"level": 1,
"question": "Write a Python function that takes a string as input and returns a list of all the words in the string. Words are defined as sequences of alphanumeric characters separated by non-alphanumeric characters.",
"split": "train"
} |
from typing import List
def sort_by_length(words: List[str]) -> List[str]:
return sorted(words, key=len) | simplelr_Algorithm | [
{
"content": "Question:\n### Sort Words by Length\n\n#### Problem Statement\nYou are given a function `sort_by_length` that sorts a list of words by their length in ascending order. Your task is to implement this function.\n\n#### Function Signature\n```python\ndef sort_by_length(words: List[str]) -> List[str]:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 549,
"level": 1,
"question": "### Sort Words by Length\n\n#### Problem Statement\nYou are given a function `sort_by_length` that sorts a list of words by their length in ascending order. Your task is to implement this function.\n\n#### Function Signature\n```python\ndef sort_by_leng... |
def combine_lists(list1, list2):
combined_dict = {}
# Add all items from list1 to the dictionary
for item in list1:
item_id = item['id']
if item_id not in combined_dict:
combined_dict[item_id] = item.copy()
# Update with items from list2, merging where ids match
... | simplelr_Filter | [
{
"content": "Question:\nI have two lists of dictionaries in python where each dictionary represents an entity with some attributes. For example: \n\n```python\nlist1 = [\n {'id': 1, 'name': 'John', 'age': 25},\n {'id': 2, 'name': 'Jane', 'age': 30},\n {'id': 3, 'name': 'Bob', 'age': 25}\n]\n\nlist2 = ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 550,
"level": 1,
"question": "I have two lists of dictionaries in python where each dictionary represents an entity with some attributes. For example: \n\n```python\nlist1 = [\n {'id': 1, 'name': 'John', 'age': 25},\n {'id': 2, 'name': 'Jane', 'age': 30},\n {'id': 3, 'name'... |
def most_frequent_substring(s: str, length: int) -> str:
if length == 0 or length > len(s):
return ""
if len(s) == 0:
return ""
# Define two different base and mod pairs for double hashing
base1 = 911382629
mod1 = 10**18 + 3
base2 = 3571428571
mod2 = 10**9 + 7 # A large... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Problem Statement\n\nYou are tasked with analyzing a set of strings to determine the most frequent substring of a given length. If there are multiple substrings with the same frequency, return the lexicographically smallest one.\n\n#### Detailed De... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 551,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Problem Statement\n\nYou are tasked with analyzing a set of strings to determine the most frequent substring of a given length. If there are multiple substrings with the same frequency, return the lexicographically... |
def calculate_sum(lst):
total_sum = 0
for number in lst:
total_sum += number
return total_sum
# Test the function
test_list = [1, 2, 3, -1, 0]
print(calculate_sum(test_list)) # Expected output: 5 | simplelr_Filter | [
{
"content": "Question:\nwrite a python function to calculate the sum of all elements in a list without using the built-in `sum` function. Test your function with a list of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 552,
"level": 1,
"question": "write a python function to calculate the sum of all elements in a list without using the built-in `sum` function. Test your function with a list of integers.",
"split": "train"
} |
def find_odd_squares(nums: list[int]) -> list[int]:
squares = [x**2 for x in nums if x % 2 != 0]
squares.sort()
return squares | simplelr_Package | [
{
"content": "Question:\nYou need to write a function `find_odd_squares(nums: List[int]) -> List[int]` that takes a list of integers and returns a list of the squares of the odd numbers from the original list, sorted in ascending order.\n\nThis function should:\n1. Use list comprehension to filter out even numb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 553,
"level": 1,
"question": "You need to write a function `find_odd_squares(nums: List[int]) -> List[int]` that takes a list of integers and returns a list of the squares of the odd numbers from the original list, sorted in ascending order.\n\nThis function should:\n1. Use list com... |
def is_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
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `is_balanced` that checks if a string of parentheses (including {}, [], and ()) is balanced. A string is considered balanced if all types of parentheses are properly closed and opened in the correct order. The function should return `True` if the string is balanc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 554,
"level": 1,
"question": "Write a Python function `is_balanced` that checks if a string of parentheses (including {}, [], and ()) is balanced. A string is considered balanced if all types of parentheses are properly closed and opened in the correct order. The function should ret... |
def find_palindromes(words):
return [word for word in words if word == word[::-1]] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes as an argument a list of words and returns a new list of words that are palindromes.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 555,
"level": 1,
"question": "Create a function that takes as an argument a list of words and returns a new list of words that are palindromes.",
"split": "train"
} |
def find_index(nums, target):
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 | simplelr_Filter | [
{
"content": "Question:\nThis is a question about finding a specific element in a sorted list.\n\n**Given a sorted list of integers and a target integer, return the index of the target integer if it exists in the list, otherwise return -1.**\n\n**Example:**\n\n```python\ndef find_index(nums, target):\n # You... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 556,
"level": 1,
"question": "This is a question about finding a specific element in a sorted list.\n\n**Given a sorted list of integers and a target integer, return the index of the target integer if it exists in the list, otherwise return -1.**\n\n**Example:**\n\n```python\ndef fi... |
from collections import Counter
def is_anagram(s1, s2):
if len(s1) != len(s2):
return False
return Counter(s1) == Counter(s2) | simplelr_Filter | [
{
"content": "Question:\nGiven two strings s1 and s2, write a function in Python to determine if s2 is an anagram of s1. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For extra challenge, ensure the code can... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 557,
"level": 1,
"question": "Given two strings s1 and s2, write a function in Python to determine if s2 is an anagram of s1. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For ex... |
def find_missing_number(arr):
n = len(arr) + 1
expected_sum = n * (n + 1) // 2
actual_sum = sum(arr)
return expected_sum - actual_sum
| simplelr_Taco | [
{
"content": "Question:\n# Find Missing Number\n\nYou are given an array of unique integers that is supposed to contain all the numbers from 1 to `n`, but one number is missing. Write a function that finds and returns the missing number. The array will have a length of `n-1` and contain distinct integers in the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 558,
"level": 1,
"question": "# Find Missing Number\n\nYou are given an array of unique integers that is supposed to contain all the numbers from 1 to `n`, but one number is missing. Write a function that finds and returns the missing number. The array will have a length of `n-1` an... |
def shortest_common_supersequence(a: str, b: str) -> str:
m = len(a)
n = len(b)
# Create a DP table with (m+1) rows and (n+1) columns
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Initialize the first row and column
for i in range(m + 1):
dp[i][0] = a[:i]
for j in range(n + 1):
... | simplelr_Package | [
{
"content": "Question:\n### Shortest Common Supersequence\n\nYou are required to implement a function `shortest_common_supersequence(a: str, b: str) -> str` that finds the shortest common supersequence of two input strings `a` and `b`. A shortest common supersequence is a string that contains both `a` and `b` ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 559,
"level": 1,
"question": "### Shortest Common Supersequence\n\nYou are required to implement a function `shortest_common_supersequence(a: str, b: str) -> str` that finds the shortest common supersequence of two input strings `a` and `b`. A shortest common supersequence is a stri... |
def shiftString(s, k):
result = []
for c in s:
pos = ord(c) - ord('a')
new_pos = (pos + k) % 26
result.append(chr(new_pos + ord('a')))
return ''.join(result)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a string `s` and an integer `k` and returns a new string where each character in the original string is shifted `k` positions to the right in the alphabet. If `k` is negative, shift to the left. The shifting should wrap around the alphabet, meaning that after... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 560,
"level": 1,
"question": "Write a function that takes a string `s` and an integer `k` and returns a new string where each character in the original string is shifted `k` positions to the right in the alphabet. If `k` is negative, shift to the left. The shifting should wrap aroun... |
def median_arrival_time(arrival_times: list[int]) -> float:
if not arrival_times:
raise ValueError("List is empty")
sorted_times = sorted(arrival_times)
n = len(sorted_times)
if n % 2 == 1:
median = sorted_times[n // 2]
else:
left = (n // 2) - 1
right = n //... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\nA logistic company is integrating a feature to efficiently manage its delivery schedule by calculating the **Median Arrival Time** of its shipments. As the shipments come from various origins and have different travel times, you need to accurately deter... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 561,
"level": 1,
"question": "### Coding Assessment Question\n\nA logistic company is integrating a feature to efficiently manage its delivery schedule by calculating the **Median Arrival Time** of its shipments. As the shipments come from various origins and have different travel t... |
from typing import List, Union
def fizz_buzz_transform(numbers: List[int]) -> List[Union[int, str]]:
result = []
for num in numbers:
if num % 15 == 0:
result.append("FizzBuzz")
elif num % 3 == 0:
result.append("Fizz")
elif num % 5 == 0:
result.append(... | simplelr_Taco | [
{
"content": "Question:\nImplement a function that takes a list of positive integers and returns a list where each integer transformation is done according to the following rules:\n\n1. If the integer is divisible by 3, replace it with the string \"Fizz\".\n2. If the integer is divisible by 5, replace it with t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 562,
"level": 1,
"question": "Implement a function that takes a list of positive integers and returns a list where each integer transformation is done according to the following rules:\n\n1. If the integer is divisible by 3, replace it with the string \"Fizz\".\n2. If the integer is... |
def factorial(n):
"""Calculate the factorial of a non-negative integer using recursion.
Parameters:
n (int): The non-negative integer.
Returns:
int: The factorial of n.
Raises:
ValueError: If n is a negative integer or not an integer.
"""
if type(n) is not int or n < 0... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function to find the factorial of a number using recursion. Ensure that your function handles non-integer and negative inputs by raising a ValueError. Additionally, include a brief docstring that explains the function's purpose, parameters, and what it returns.\nAnswer:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 563,
"level": 1,
"question": "Create a Python function to find the factorial of a number using recursion. Ensure that your function handles non-integer and negative inputs by raising a ValueError. Additionally, include a brief docstring that explains the function's purpose, paramete... |
import itertools
def distance(city1, city2):
# For simplicity, the distance between city1 and city2 is
# calculated as the Euclidean distance.
return ((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) ** 0.5
# 1. Generate all city coordinates
cities = []
for x in range(0, 10, 2):
cities.append(... | simplelr_Filter | [
{
"content": "Question:\n### INTRODUCTION\nAt the university, we have a traveling salesman problem (TSP) that works with shortest paths. The output of this problem is a routing for the salesman and a table of distances travelled. However, the city numbers go from 1 to N and our current output is only showing ci... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 564,
"level": 1,
"question": "### INTRODUCTION\nAt the university, we have a traveling salesman problem (TSP) that works with shortest paths. The output of this problem is a routing for the salesman and a table of distances travelled. However, the city numbers go from 1 to N and our... |
def count_occurrences(s, char):
"""
Returns the number of occurrences of a given character in a string.
Parameters:
s (str): The input string.
char (str): The character to count.
Returns:
int: The number of times the character appears in the string.
"""
return s.count(char) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to get the number of occurrences of a given character in a string. For example, for the string \"Hello World\" and the character 'o', the function should return 2.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 565,
"level": 1,
"question": "Write a function to get the number of occurrences of a given character in a string. For example, for the string \"Hello World\" and the character 'o', the function should return 2.",
"split": "train"
} |
def sort_books(books):
return sorted(books, key=lambda x: (x['year'], x['author'], x['title'])) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of dictionaries, each representing a book with keys \"title\", \"author\", and \"year\", and returns a new list of dictionaries sorted by the \"year\" key in ascending order. If two books have the same publication year, they should be sorted by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 566,
"level": 1,
"question": "Write a Python function that takes a list of dictionaries, each representing a book with keys \"title\", \"author\", and \"year\", and returns a new list of dictionaries sorted by the \"year\" key in ascending order. If two books have the same publicati... |
def is_anagram(s1, s2):
# Process each string to remove non-alphabetic characters and convert to lowercase
processed1 = ''.join([c.lower() for c in s1 if c.isalpha()])
processed2 = ''.join([c.lower() for c in s2 if c.isalpha()])
# Check if both processed strings are anagrams by comparing their sort... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that checks if a given string is an anagram of another string. The function should ignore spaces, punctuation, and capitalization. The two input strings will contain only alphabetic characters, spaces, and basic punctuation marks. Ensure the function handles edge cases ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 567,
"level": 1,
"question": "Write a function that checks if a given string is an anagram of another string. The function should ignore spaces, punctuation, and capitalization. The two input strings will contain only alphabetic characters, spaces, and basic punctuation marks. Ensur... |
def run_length_encode(input_string: str) -> str:
if not input_string:
return ""
result = []
current_char = input_string[0]
count = 1
for char in input_string[1:]:
if char == current_char:
count += 1
else:
result.append(f"{current_char}{count}")
... | simplelr_Algorithm | [
{
"content": "Question:\n### Context:\nData compression is a vital technique used to reduce the size of files, making them easier to store and transmit. One simple and commonly used method is run-length encoding (RLE), particularly effective for data with many repeating characters. Implementing this technique w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 568,
"level": 1,
"question": "### Context:\nData compression is a vital technique used to reduce the size of files, making them easier to store and transmit. One simple and commonly used method is run-length encoding (RLE), particularly effective for data with many repeating charact... |
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
# Inner loop runs from 0 to n-i-2 (inclusive) because range is exclusive
for j in range(n - i - 1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
... | simplelr_Filter | [
{
"content": "Question:\nWrite your own version of bubble sort for an array of integers. Additionally, detect if the array is already sorted to avoid unnecessary passes.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 569,
"level": 1,
"question": "Write your own version of bubble sort for an array of integers. Additionally, detect if the array is already sorted to avoid unnecessary passes.",
"split": "train"
} |
def length_of_longest_subarray(arr):
last_seen = {}
max_len = 0
left = 0
for right in range(len(arr)):
current = arr[right]
if current in last_seen and last_seen[current] >= left:
left = last_seen[current] + 1
last_seen[current] = right
current_len = right - l... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr`, find the length of the longest contiguous subarray such that every element in the subarray is unique. The array may contain both positive and negative integers. The algorithm should run in linear time and use constant extra space.\nAnswer:\nLet's think ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 570,
"level": 1,
"question": "Given an array of integers `arr`, find the length of the longest contiguous subarray such that every element in the subarray is unique. The array may contain both positive and negative integers. The algorithm should run in linear time and use constant e... |
def sum_of_unique_characters(s):
return sum(ord(c) - 96 for c in set(s)) | simplelr_Filter | [
{
"content": "Question:\nGiven a string `s`, return the sum of all unique characters in the string.\n\nFor example,\n\nInput:\n\n```\ns = \"leetcode\"\n```\n\nOutput:\n\n```\n10\n```\n\nExplanation: \n\nThe unique characters in the string are 'l', 'e', 't', 'c', 'o', 'd'.\n\nSum of these characters: 12 + 5 + 20... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 571,
"level": 1,
"question": "Given a string `s`, return the sum of all unique characters in the string.\n\nFor example,\n\nInput:\n\n```\ns = \"leetcode\"\n```\n\nOutput:\n\n```\n10\n```\n\nExplanation: \n\nThe unique characters in the string are 'l', 'e', 't', 'c', 'o', 'd'.\n\nSu... |
import csv
from csv import DictReader, DictWriter
def process_csv_files(employees_csv: str, departments_csv: str, output_csv: str) -> None:
try:
# Read departments CSV and create a dictionary mapping department_id to (name, location)
with open(departments_csv, 'r') as dept_file:
dept_re... | simplelr_Docs | [
{
"content": "Question:\n### CSV File Manipulation with Python's csv Module\n\nYou are given two CSV files: `employees.csv` and `departments.csv`. Each row in the `employees.csv` file contains information about an employee, and each row in the `departments.csv` file contains information about a department. You ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 572,
"level": 1,
"question": "### CSV File Manipulation with Python's csv Module\n\nYou are given two CSV files: `employees.csv` and `departments.csv`. Each row in the `employees.csv` file contains information about an employee, and each row in the `departments.csv` file contains in... |
def sum_above_threshold(lst, threshold):
return sum(num for row in lst for num in row if num > threshold) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the sum of all elements in a 2D list that are greater than a given threshold.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 573,
"level": 1,
"question": "Write a python function to calculate the sum of all elements in a 2D list that are greater than a given threshold.",
"split": "train"
} |
def trap(heights):
if not heights:
return 0
n = len(heights)
if n < 3:
return 0
left = 0
right = n - 1
left_max = right_max = 0
result = 0
while left <= right:
if heights[left] <= heights[right]:
if heights[left] >= left_max:
left_max =... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `heights` that represents the heights of buildings in a city, where each height is an integer. You need to calculate the amount of water that can be trapped between the buildings after it rains. Implement a function that returns the total volume of water t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 574,
"level": 1,
"question": "You are given an integer array `heights` that represents the heights of buildings in a city, where each height is an integer. You need to calculate the amount of water that can be trapped between the buildings after it rains. Implement a function that r... |
def distinct_ways_to_climb(n):
if n == 1:
return 1
elif n == 2:
return 2
a, b = 1, 2 # Represents F(3) and F(4)
for _ in range(3, n + 1):
c = a + b
a = b
b = c
return b | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem\nYou are hired to develop a mobile game where a player climbs stairs to score points. The number of steps the player can climb at a time are constrained to either 1 or 2 steps. Each level in the game consists of a different number of steps, and you need to implement a functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 575,
"level": 1,
"question": "### Problem\nYou are hired to develop a mobile game where a player climbs stairs to score points. The number of steps the player can climb at a time are constrained to either 1 or 2 steps. Each level in the game consists of a different number of steps, ... |
def is_pangram(input_string: str) -> bool:
letters = set()
for char in input_string:
lower_char = char.lower()
if 'a' <= lower_char <= 'z':
letters.add(lower_char)
return len(letters) == 26 | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are working on a system that needs to analyze text sequences and perform various operations based on specific requirements. One critical feature is to check whether a given string contains all the letters of the alphabet at least once, making it a \"pangram\".... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 576,
"level": 1,
"question": "### Problem Statement\nYou are working on a system that needs to analyze text sequences and perform various operations based on specific requirements. One critical feature is to check whether a given string contains all the letters of the alphabet at le... |
def can_form_palindrome(s):
freq = {}
for c in s:
if c.isalpha(): # Only consider letters
freq[c] = freq.get(c, 0) + 1
odd_count = 0
for count in freq.values():
if count % 2 != 0:
odd_count += 1
if odd_count > 1:
return False
retur... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters and integers from 0 to 9. Write a function to determine if `s` can be rearranged to form a palindrome ignoring the numeric characters. The function should return `True` if it is possible, otherwise `False`. A **Palindrom... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 577,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters and integers from 0 to 9. Write a function to determine if `s` can be rearranged to form a palindrome ignoring the numeric characters. The function should return `True` if it is possible... |
def max_subarray_sum(nums):
if not nums:
return 0
current_sum = max_sum = nums[0]
for num in nums[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum | simplelr_Filter | [
{
"content": "Question:\nI've been trying to solve this problem:\nGiven an array of integers, find the maximum subarray sum using Kadane's algorithm.\n\nAssuming I have the following code:\n```python\ndef max_subarray_sum(nums):\n if not nums:\n return 0\n\n current_sum = max_sum = nums[0]\n\n f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 578,
"level": 1,
"question": "I've been trying to solve this problem:\nGiven an array of integers, find the maximum subarray sum using Kadane's algorithm.\n\nAssuming I have the following code:\n```python\ndef max_subarray_sum(nums):\n if not nums:\n return 0\n\n curren... |
def house_robber(houses):
if not houses:
return 0
n = len(houses)
if n == 1:
return houses[0]
a = houses[0]
b = max(houses[0], houses[1])
for i in range(2, n):
current = max(b, a + houses[i])
a, b = b, current
return b | simplelr_Data_Structure | [
{
"content": "Question:\nYou are an experienced security consultant tasked with improving the performance of a robbery simulation system. Your goal is to enhance the \"house robber\" algorithm to determine the maximum amount of money that can be robbed from a series of houses arranged sequentially. Each house h... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 579,
"level": 1,
"question": "You are an experienced security consultant tasked with improving the performance of a robbery simulation system. Your goal is to enhance the \"house robber\" algorithm to determine the maximum amount of money that can be robbed from a series of houses a... |
def power(a, b):
if b == 0:
return 1
elif b < 0:
return 1 / power(a, -b)
else:
return a * power(a, b - 1) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to compute the nth power of a number using recursion. The function should handle both positive and negative exponents.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 580,
"level": 1,
"question": "Write a function to compute the nth power of a number using recursion. The function should handle both positive and negative exponents.",
"split": "train"
} |
def primes_up_to_n(n):
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0], sieve[1] = False, False
for p in range(2, int(n ** 0.5) + 1):
if sieve[p]:
for multiple in range(p * p, n + 1, p):
sieve[multiple] = False
primes = [p for p in range(2, n + 1) if... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes an integer N and returns a list of prime numbers up to N (inclusive).\n\nExample:\nInput:\n10\nOutput:\n[2, 3, 5, 7]\nExplanation:\nThe prime numbers up to 10 are 2, 3, 5, and 7.\n\nYour Task:\nYou don't need to read input or print anything. Your task is to c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 581,
"level": 1,
"question": "Write a function that takes an integer N and returns a list of prime numbers up to N (inclusive).\n\nExample:\nInput:\n10\nOutput:\n[2, 3, 5, 7]\nExplanation:\nThe prime numbers up to 10 are 2, 3, 5, and 7.\n\nYour Task:\nYou don't need to read input or... |
def get_histogram(input_list: list) -> dict:
histogram = {}
for num in input_list:
if num in histogram:
histogram[num] += 1
else:
histogram[num] = 1
return histogram | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Histogram Representation with Constraints\n\n#### Description\nYou are given a list of integers. Your task is to implement a function to generate a histogram (a frequency dictionary) representing the number of occurrences of each integer in the list.\n\n#### Function Signa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 582,
"level": 1,
"question": "### Question: Histogram Representation with Constraints\n\n#### Description\nYou are given a list of integers. Your task is to implement a function to generate a histogram (a frequency dictionary) representing the number of occurrences of each integer i... |
def threeSum(nums: list[int]) -> list[list[int]]:
"""
Finds all unique triplets in the given list of integers that sum to zero.
The function uses a two-pointer approach, which is efficient and handles
duplicates by skipping over them to avoid redundant triplets.
Args:
nums (list[i... | simplelr_Filter | [
{
"content": "Question:\nYou are given an array of integers. Find all unique triplets in the array which give the sum of\n\n**zero **.\n\n\n**Example:**\n\n Given an array nums = [-1, 0, 1, 2, -1, -4]\n\n A solution set is:\n [\n [-1, -1, 2],\n [-1, 0, 1]\n ]\n**Note:**\n The solution set must not contain dup... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 583,
"level": 1,
"question": "You are given an array of integers. Find all unique triplets in the array which give the sum of\n\n**zero **.\n\n\n**Example:**\n\n Given an array nums = [-1, 0, 1, 2, -1, -4]\n\n A solution set is:\n [\n [-1, -1, 2],\n [-1, 0, 1]\n ]\n**Note:**\n The... |
def find_pairs(nums, target):
seen = set()
result = []
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
a, b = nums[i], nums[j]
if a + b == target:
pair = tuple(sorted((a, b)))
if pair not in seen:
seen.add(pai... | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function that takes an array of integers and a target sum, and returns all unique pairs of elements that add up to the target sum. Each pair in the output should be sorted in ascending order, and the pairs themselves should also be sorted in ascending order based on their first ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 584,
"level": 1,
"question": "Write a function that takes an array of integers and a target sum, and returns all unique pairs of elements that add up to the target sum. Each pair in the output should be sorted in ascending order, and the pairs themselves should also be sorted in asc... |
import pandas as pd
import numpy as np
def pass_or_fail(df):
# Create a mask identifying students who passed all subjects
passed_mask = (df['Mathematics'] >= 40) & (df['Science'] >= 40) & (df['English'] >= 40)
# Determine the result based on the mask
result = np.where(passed_mask, 'Passed', 'Failed')
... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function using the Pandas library that determines if each student in a group has passed or failed based on their exam scores. Each student's information is provided as a dictionary with their name and scores in three subjects—Mathematics, Science, and English... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 585,
"level": 1,
"question": "You are required to write a function using the Pandas library that determines if each student in a group has passed or failed based on their exam scores. Each student's information is provided as a dictionary with their name and scores in three subjects... |
def min_possible_length(s):
stack = []
for c in s:
if stack and stack[-1] == c:
stack.pop()
else:
stack.append(c)
return len(stack) | simplelr_Leetcode | [
{
"content": "Question:\nSuppose you have a string `s` of lowercase English letters. You need to perform the following operation repeatedly until the string becomes empty: Choose any two adjacent characters that are the same and delete them. You need to determine the minimum possible length of the string after ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 586,
"level": 1,
"question": "Suppose you have a string `s` of lowercase English letters. You need to perform the following operation repeatedly until the string becomes empty: Choose any two adjacent characters that are the same and delete them. You need to determine the minimum po... |
def sort_students_by_grades(students):
return sorted(students, key=lambda x: (-x[1], x[0])) | simplelr_Evol | [
{
"content": "Question:\nWrite a function `sort_students_by_grades` that takes a list of student-grade pairs (tuples) and returns the list sorted by grades in descending order. If two students have the same grade, sort them alphabetically by their names. \n\nExample:\n\nInput:\n```python\nstudents = [(\"John\",... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 587,
"level": 1,
"question": "Write a function `sort_students_by_grades` that takes a list of student-grade pairs (tuples) and returns the list sorted by grades in descending order. If two students have the same grade, sort them alphabetically by their names. \n\nExample:\n\nInput:\... |
def most_frequent_character(s):
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
max_count = max(freq.values())
candidates = [char for char, count in freq.items() if count == max_count]
candidates.sort()
return candidates[0] | simplelr_Code_Contests | [
{
"content": "Question:\nA common security task is performing a frequency analysis on a file to identify usage patterns or character distribution. Write a function that takes a string as input and returns the character that appears the most frequently. If there is a tie, return the character that appears first ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 588,
"level": 1,
"question": "A common security task is performing a frequency analysis on a file to identify usage patterns or character distribution. Write a function that takes a string as input and returns the character that appears the most frequently. If there is a tie, return... |
def median(numbers):
sorted_list = sorted(numbers)
n = len(sorted_list)
if n == 0:
return None
elif n % 2 == 1:
return sorted_list[n // 2]
else:
return (sorted_list[(n // 2) - 1] + sorted_list[n // 2]) / 2 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of numbers as an argument and returns the median of those numbers. The function should be able to sort the numbers, find the middle point, and return the middle number if the total number of numbers is odd. If the total number of numbers is even, the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 589,
"level": 1,
"question": "Create a function that takes a list of numbers as an argument and returns the median of those numbers. The function should be able to sort the numbers, find the middle point, and return the middle number if the total number of numbers is odd. If the tot... |
def is_well_formed(s: str) -> bool:
closing_to_opening = {')': '(', ']': '[', '}': '{'}
stack = []
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 = s... | simplelr_Evol | [
{
"content": "Question:\nCreate a function that takes a string as an input and returns True if the string is a well-formed mathematical expression using parentheses, brackets, and curly braces; otherwise, returns False. The function should validate that each opening symbol has a corresponding closing symbol and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 590,
"level": 1,
"question": "Create a function that takes a string as an input and returns True if the string is a well-formed mathematical expression using parentheses, brackets, and curly braces; otherwise, returns False. The function should validate that each opening symbol has ... |
def add_numbers(a, b):
sum = a + b
return sum
result = add_numbers(5, 3)
print(result) # Outputs: 8 | simplelr_Filter | [
{
"content": "Question:\nI am a beginner in coding, so please explain the concept of \"returning values\"\n\n<h1>Returning Values</h1>\n\nIn programming, functions can not only perform actions but also provide results back to the part of the code that called them. This \"sending back\" of a result is known as \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 591,
"level": 1,
"question": "I am a beginner in coding, so please explain the concept of \"returning values\"\n\n<h1>Returning Values</h1>\n\nIn programming, functions can not only perform actions but also provide results back to the part of the code that called them. This \"sendin... |
def invert_case(word):
return word.swapcase() | simplelr_Package | [
{
"content": "Question:\nYou need to develop a Python function `invert_case` which takes a string as input and returns a new string with the case of each alphabetic character inverted. Non-alphabetic characters should remain unchanged.\n\n**Function Signature:** \n```python\ndef invert_case(word):\n```\n\n**Par... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 592,
"level": 1,
"question": "You need to develop a Python function `invert_case` which takes a string as input and returns a new string with the case of each alphabetic character inverted. Non-alphabetic characters should remain unchanged.\n\n**Function Signature:** \n```python\nde... |
def update_departments(company_departments, recent_leavers):
for dept in company_departments:
company_departments[dept] = [emp for emp in company_departments[dept] if emp not in recent_leavers] | simplelr_Package | [
{
"content": "Question:\nYou are given a dictionary `company_departments` where the keys are department names and the values are lists of employee names. Additionally, you have a list called `recent_leavers` that contains the names of employees who have recently left the company.\n\nYour task is to write a func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 593,
"level": 1,
"question": "You are given a dictionary `company_departments` where the keys are department names and the values are lists of employee names. Additionally, you have a list called `recent_leavers` that contains the names of employees who have recently left the compan... |
def longest_consecutive(nums):
if not nums:
return 0
nums_set = set(nums)
max_length = 0
for num in nums:
if (num - 1) not in nums_set:
current_num = num
current_length = 1
while (current_num + 1) in nums_set:
current_num += 1
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array `nums` consisting of distinct integers, return _a length of the longest sequence of consecutive numbers that can be found in `nums`_.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 594,
"level": 1,
"question": "Given an array `nums` consisting of distinct integers, return _a length of the longest sequence of consecutive numbers that can be found in `nums`_.",
"split": "train"
} |
def insert_element(lst, index, x):
# Append a dummy value to create space
lst.append(None)
# Shift elements from the end down to the target index + 1
for i in range(len(lst) - 1, index, -1):
lst[i] = lst[i - 1]
# Insert the new element at the target index
lst[index] = x | simplelr_Filter | [
{
"content": "Question:\nModify the following code to insert the element 'x' into the list at position 'index' without using the built-in insert() function and without creating a new list. Additionally, ensure that the time complexity of your solution is O(n) and the space complexity is O(1).\nAnswer:\nLet's th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 595,
"level": 1,
"question": "Modify the following code to insert the element 'x' into the list at position 'index' without using the built-in insert() function and without creating a new list. Additionally, ensure that the time complexity of your solution is O(n) and the space comp... |
def list_of_tuples_to_dict(tuple_list):
return dict(tuple_list) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert a list of tuples where each tuple contains a key and a value, into a dictionary.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 596,
"level": 1,
"question": "Write a python function to convert a list of tuples where each tuple contains a key and a value, into a dictionary.",
"split": "train"
} |
def process_mixed_list(input_list: list) -> list:
result = []
for item in input_list:
if isinstance(item, int):
result.append(item * 2)
else:
result.append(item.upper())
return result | simplelr_Evol | [
{
"content": "Question:\nImplement a function to manipulate a mixed list of integers and strings. The function should be named `process_mixed_list` and take a single parameter, which is a list containing both integers and strings. \n\nThe task is to create a resultant list where all the integer values are doubl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 597,
"level": 1,
"question": "Implement a function to manipulate a mixed list of integers and strings. The function should be named `process_mixed_list` and take a single parameter, which is a list containing both integers and strings. \n\nThe task is to create a resultant list wher... |
def count_keyword_occurrences(file_path, keyword, case_sensitive=True):
"""
Counts the occurrences of a specific keyword in a given file.
Args:
file_path (str): Path to the file to be parsed.
keyword (str): The keyword to search for.
case_sensitive (bool, optional): Determines if th... | simplelr_Filter | [
{
"content": "Question:\nHow can I build a Python function that can parse a script file and count the occurrences of a specific keyword throughout the file?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 598,
"level": 1,
"question": "How can I build a Python function that can parse a script file and count the occurrences of a specific keyword throughout the file?",
"split": "train"
} |
def filter_strings_by_length(strings_list, n):
"""
Filters and returns a list of strings whose lengths are greater than the specified integer.
Args:
strings_list (list): A list of strings to be filtered.
n (int): The minimum length threshold.
Returns:
list: A list of strings wh... | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes a list of strings and an integer n as input, and returns a list of strings that are longer than n characters. Ensure your code is well-documented and follows best practices.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 599,
"level": 1,
"question": "Write a function in Python that takes a list of strings and an integer n as input, and returns a list of strings that are longer than n characters. Ensure your code is well-documented and follows best practices.",
"split": "train"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.