target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
from collections import defaultdict
from typing import List
def max_distinct_subarray(arr: List[int], k: int) -> int:
freq = defaultdict(int)
max_distinct = 0
current_distinct = 0
left = 0
for right in range(len(arr)):
num = arr[right]
if freq[num] == 0:
current_distinc... | simplelr_Code_Contests | [
{
"content": "Question:\nYou're given an array of integers and an integer `k`. Write a function that finds the maximum number of distinct elements in any subarray of length `k`.\n\nFunction Signature:\n```python\ndef max_distinct_subarray(arr: List[int], k: int) -> int:\n```\n\n### Input\n- `arr` - a list of in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2700,
"level": 1,
"question": "You're given an array of integers and an integer `k`. Write a function that finds the maximum number of distinct elements in any subarray of length `k`.\n\nFunction Signature:\n```python\ndef max_distinct_subarray(arr: List[int], k: int) -> int:\n```\n... |
def reverse_words(sentence):
words = sentence.split()
reversed_words = []
for i in range(len(words) - 1, -1, -1):
reversed_words.append(words[i])
return ' '.join(reversed_words) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that reverses the order of words in a given sentence without using any built-in Python functions or methods for reversing a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2701,
"level": 1,
"question": "Write a Python function that reverses the order of words in a given sentence without using any built-in Python functions or methods for reversing a string.",
"split": "train"
} |
import math
def sum_of_divisors(n: int) -> tuple:
sum_div = 0
sqrt_n = int(math.sqrt(n))
for i in range(1, sqrt_n + 1):
if n % i == 0:
if i != n:
sum_div += i
other = n // i
if other != i and other != n:
sum_div += other
is_pri... | simplelr_Taco | [
{
"content": "Question:\nGiven a number `num`, write a function `sum_of_divisors(n)` that returns a tuple `(sum, is_prime)`. \n\n- `sum` is the sum of all divisors of the number `num` (excluding the number itself).\n- `is_prime` is a boolean indicating whether `num` is a prime number or not.\n\nA number is said... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2702,
"level": 1,
"question": "Given a number `num`, write a function `sum_of_divisors(n)` that returns a tuple `(sum, is_prime)`. \n\n- `sum` is the sum of all divisors of the number `num` (excluding the number itself).\n- `is_prime` is a boolean indicating whether `num` is a prime... |
from collections import Counter
def sum_of_unique_elements(nums: list) -> int:
# Check if the input is a list
if not isinstance(nums, list):
raise TypeError("Input must be a list of integers.")
# Check each element is an integer (not a boolean)
for num in nums:
if type(num) is not int:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of Unique Elements in a List\n\nWrite a function that takes a list of integers and returns the sum of elements that appear only once in the list. Your implementation should efficiently handle the problem by utilizing appropriate data structures to keep track of the element count... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2703,
"level": 1,
"question": "### Sum of Unique Elements in a List\n\nWrite a function that takes a list of integers and returns the sum of elements that appear only once in the list. Your implementation should efficiently handle the problem by utilizing appropriate data structures... |
def remove_duplicates(nums):
if not nums:
return 0
write_pointer = 0
current_val = nums[0]
count = 1
for j in range(1, len(nums)):
if nums[j] == current_val:
count += 1
else:
# Process the current group
write_length = min(count, 2... | simplelr_Filter | [
{
"content": "Question:\nGiven a sorted array, remove the duplicates in-place such that each element appears at most twice and return the length of the new array.\n\nExample 1:\nInput: nums = [1, 1, 1, 2, 2, 3]\nOutput: 5, nums = [1, 1, 2, 2, 3]\n\nExample 2:\nInput: nums = [0, 0, 1, 1, 1, 1, 2, 3, 3]\nOutput: ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2704,
"level": 1,
"question": "Given a sorted array, remove the duplicates in-place such that each element appears at most twice and return the length of the new array.\n\nExample 1:\nInput: nums = [1, 1, 1, 2, 2, 3]\nOutput: 5, nums = [1, 1, 2, 2, 3]\n\nExample 2:\nInput: nums = [0... |
from typing import List, Dict
import fnmatch
def organize_files_by_extension(files: List[str]) -> Dict[str, List[str]]:
extension_groups = {}
# Collect all unique file extensions
extensions = set()
for file in files:
parts = file.split('.')
ext_part = parts[-1]
ext = '.' + ext_p... | simplelr_Docs | [
{
"content": "Question:\n**Coding Assessment Question**\n\n### Objective\nWrite a Python program using the `fnmatch` module to organize files based on their extensions into directories named after the extension.\n\n### Problem Statement\nYou are provided with a list of filenames in a directory. Your task is to ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2705,
"level": 1,
"question": "**Coding Assessment Question**\n\n### Objective\nWrite a Python program using the `fnmatch` module to organize files based on their extensions into directories named after the extension.\n\n### Problem Statement\nYou are provided with a list of filenam... |
from typing import List
def sum_list(lst: List[int]) -> int:
return sum(lst)
# Test cases
assert sum_list([1, 2, 3, 4, 5]) == 15, f"Expected sum_list([1, 2, 3, 4, 5]) to return 15, but got {sum_list([1, 2, 3, 4, 5])}"
assert sum_list([-1, -2, -3, -4, -5]) == -15, f"Expected sum_list([-1, -2, -3, -4, -5]) to retur... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers as input and returns the sum of all the integers in the list. If the list is empty, the function should return 0. Use the built-in `sum` function to compute the sum. The function should be named `sum_list` and should have the followi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2706,
"level": 1,
"question": "Write a Python function that takes a list of integers as input and returns the sum of all the integers in the list. If the list is empty, the function should return 0. Use the built-in `sum` function to compute the sum. The function should be named `su... |
def search_matrix(matrix: list[list[int]], target: int) -> bool:
if not matrix or not matrix[0]:
return False
rows = len(matrix)
cols = len(matrix[0])
i, j = 0, cols - 1
while i < rows and j >= 0:
current = matrix[i][j]
if current == target:
return True
el... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge: Optimizing Integer Matrix Search\n\nGiven an `m x n` matrix of integers, where each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom, optimize a search function that checks if a given integer exist... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2707,
"level": 1,
"question": "### Coding Challenge: Optimizing Integer Matrix Search\n\nGiven an `m x n` matrix of integers, where each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom, optimize a search function t... |
from collections import Counter
def count_occurrences(numbers, queries):
count = Counter(numbers)
return [count[q] for q in queries]
| simplelr_Taco | [
{
"content": "Question:\nYou are given a list of integers `numbers` and another list of integers `queries`. For each query, you need to count how many times the corresponding number appears in the `numbers` list and return a list of counts. \n\nWrite a function `count_occurrences(numbers: List[int], queries: Li... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2708,
"level": 1,
"question": "You are given a list of integers `numbers` and another list of integers `queries`. For each query, you need to count how many times the corresponding number appears in the `numbers` list and return a list of counts. \n\nWrite a function `count_occurren... |
def repeated_substring_pattern(s: str) -> bool:
n = len(s)
if n <= 1:
return False # A single character or empty string cannot be decomposed
# Compute the failure function using KMP algorithm
f = [0] * n
for i in range(1, n):
j = f[i-1]
while j > 0 and s[i] != s[j]:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge\n\n#### Context\nYou are tasked with developing an efficient algorithm for manipulating strings based on given rules. The challenge requires you to determine if a string can be constructed by repeating a smaller substring multiple times.\n\n#### Task\nImplement a fu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2709,
"level": 1,
"question": "### Coding Challenge\n\n#### Context\nYou are tasked with developing an efficient algorithm for manipulating strings based on given rules. The challenge requires you to determine if a string can be constructed by repeating a smaller substring multiple ... |
from sklearn.kernel_approximation import RBFSampler
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def kernel_approximation_pipeline(X, y):
# Apply RBF Sampler for kernel approximation with n_components
rbf_feature = RBFSampler(n_components=100, gamma=1, random_state=... | simplelr_Docs | [
{
"content": "Question:\n### Kernel Approximation Coding Task\n\n**Objective:**\nImplement an efficient machine learning pipeline using scikit-learn's kernel approximation methods to classify a given dataset.\n\n**Problem Statement:**\n\nYou are given a labeled dataset `X` (feature matrix) and `y` (labels). You... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2710,
"level": 1,
"question": "### Kernel Approximation Coding Task\n\n**Objective:**\nImplement an efficient machine learning pipeline using scikit-learn's kernel approximation methods to classify a given dataset.\n\n**Problem Statement:**\n\nYou are given a labeled dataset `X` (fe... |
import torch
def complex_tensor_operations():
"""
This function performs operations on complex tensors, including matrix multiplication,
element-wise absolute values, angles, and gradient computation using autograd.
Returns:
C_abs: Tensor of element-wise absolute values of C.
C_angle: ... | simplelr_Docs | [
{
"content": "Question:\n### Complex Tensor Operations and Automatic Differentiation in PyTorch\n\n#### Objective:\nWrite a function that performs a series of operations on complex tensors and returns specific results. The function should demonstrate proficiency in handling complex numbers, linear algebra opera... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2711,
"level": 1,
"question": "### Complex Tensor Operations and Automatic Differentiation in PyTorch\n\n#### Objective:\nWrite a function that performs a series of operations on complex tensors and returns specific results. The function should demonstrate proficiency in handling co... |
def shortest_palindrome(s):
if not s:
return s
s_rev = s[::-1]
t = s + '#' + s_rev
n = len(t)
fail = [0] * n
j = 0
for i in range(1, n):
while j > 0 and t[i] != t[j]:
j = fail[j-1]
if t[i] == t[j]:
j += 1
fail[i] = j
else:... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s`, return the shortest palindrome you can find by adding characters in front of `s`. A palindrome is a string that reads the same forward and backward. For example, given `s = \"abca\"`, the shortest palindrome you can form by adding characters in front of it is `\"acba... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2712,
"level": 1,
"question": "Given a string `s`, return the shortest palindrome you can find by adding characters in front of `s`. A palindrome is a string that reads the same forward and backward. For example, given `s = \"abca\"`, the shortest palindrome you can form by adding c... |
def group_scores_by_name(names: list[str], scores: list[int]) -> dict[str, list[int]]:
result = {}
for name, score in zip(names, scores):
if name in result:
result[name].append(score)
else:
result[name] = [score]
for name in result:
result[name] = sorted(resul... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are provided with a list of strings representing names and a list of numbers representing scores. Each name corresponds to a score at the same index in its respective list. Your task is to write a function that groups the scores by the names and returns a di... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2713,
"level": 1,
"question": "### Problem Statement\n\nYou are provided with a list of strings representing names and a list of numbers representing scores. Each name corresponds to a score at the same index in its respective list. Your task is to write a function that groups the s... |
import math
def gcd_of_factorials(a: int, b: int) -> int:
min_val = min(a, b)
return math.factorial(min_val) | simplelr_Algorithm | [
{
"content": "Question:\n## New Question Creation for Coding Assessment\n\n### Question Style\nAfter analyzing the provided example, the questions aim to assess fundamental programming skills and knowledge of algorithms. The existing question falls within the problem-solving and algorithmic thinking domain, wit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2714,
"level": 1,
"question": "## New Question Creation for Coding Assessment\n\n### Question Style\nAfter analyzing the provided example, the questions aim to assess fundamental programming skills and knowledge of algorithms. The existing question falls within the problem-solving a... |
import aifc
import struct
def increase_volume(input_file: str, output_file: str, volume_factor: float) -> None:
"""
Increases the volume of the audio file by the specified volume factor.
Args:
input_file (str): The path to the input AIFF or AIFC audio file.
output_file (str): The path to the outpu... | simplelr_Docs | [
{
"content": "Question:\n**Objective:** To assess your understanding of the `aifc` module in Python for handling AIFF and AIFC audio files.\n\n**Problem Statement:**\n\nYou are provided with an AIFF or AIFC audio file. Your task is to write a Python function that reads this audio file, increases the volume of t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2715,
"level": 1,
"question": "**Objective:** To assess your understanding of the `aifc` module in Python for handling AIFF and AIFC audio files.\n\n**Problem Statement:**\n\nYou are provided with an AIFF or AIFC audio file. Your task is to write a Python function that reads this au... |
def caesar_cipher(text, shift):
encrypted = []
for char in text:
if char.isupper():
base = ord('A')
elif char.islower():
base = ord('a')
else:
encrypted.append(char)
continue
shifted_offset = (ord(char) - base + shift) % 26
... | simplelr_Filter | [
{
"content": "Question:\nUtilize Python to encrypt a given sentence using the Caesar cipher with a variable shift. Also, ensure the case-sensitivity during encryption i.e. Your encrypted version of 'B' should be different than that of 'b'.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2716,
"level": 1,
"question": "Utilize Python to encrypt a given sentence using the Caesar cipher with a variable shift. Also, ensure the case-sensitivity during encryption i.e. Your encrypted version of 'B' should be different than that of 'b'.",
"split": "train"
} |
from typing import List
def single_number(nums: List[int]) -> int:
result = 0
for num in nums:
result ^= num
return result | simplelr_Algorithm | [
{
"content": "Question:\n### Single Number Identifier\n\nGiven an array `nums` containing n integers where each integer appears twice except for one integer that appears only once, find that single integer. Implement a function to return the single integer that occurs only once.\n\n#### Function Signature\n```p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2717,
"level": 1,
"question": "### Single Number Identifier\n\nGiven an array `nums` containing n integers where each integer appears twice except for one integer that appears only once, find that single integer. Implement a function to return the single integer that occurs only onc... |
def alphabet_position(s):
positions = []
for c in s:
if c.isalpha():
pos = ord(c) - ord('a') + 1
positions.append(str(pos))
return ' '.join(positions) | simplelr_Apps | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters. Your task is to create a function `alphabet_position` that replaces each letter in the string with its corresponding position in the alphabet (i.e., `a` = 1, `b` = 2, ..., `z` = 26).\n\n## Example:\n\n```python\nalphabe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2718,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters. Your task is to create a function `alphabet_position` that replaces each letter in the string with its corresponding position in the alphabet (i.e., `a` = 1, `b` = 2, ..., `z` = 26).\n... |
def count_distinct_chars(s):
return len(set(s)) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns the count of distinct characters in the string, considering case sensitivity.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2719,
"level": 1,
"question": "Write a Python function that takes a string as input and returns the count of distinct characters in the string, considering case sensitivity.",
"split": "train"
} |
def longest_common_prefix(strs):
if not strs:
return ""
prefix = []
for chars in zip(*strs):
if len(set(chars)) == 1:
prefix.append(chars[0])
else:
break
return ''.join(prefix) | simplelr_Filter | [
{
"content": "Question:\nHow can I find the longest common prefix string amongst an array of strings in Python? For example, given the array `[\"flower\", \"flow\", \"flight\"]`, the function should return `\"fl\"`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2720,
"level": 1,
"question": "How can I find the longest common prefix string amongst an array of strings in Python? For example, given the array `[\"flower\", \"flow\", \"flight\"]`, the function should return `\"fl\"`.",
"split": "train"
} |
from typing import List, Tuple
def find_pairs(nums: List[int], target: int) -> List[Tuple[int, int]]:
seen = set()
pairs = set()
for num in nums:
complement = target - num
if complement in seen:
pair = tuple(sorted((complement, num)))
pairs.add(pair)
seen.add... | simplelr_Code_Contests | [
{
"content": "Question:\nCreate a function that takes a list of integers and a single integer target value. The function should return a list of unique pairs (tuples) from the input list that add up to the target value. Each pair should be in ascending order, and the list of pairs should also be sorted in ascen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2721,
"level": 1,
"question": "Create a function that takes a list of integers and a single integer target value. The function should return a list of unique pairs (tuples) from the input list that add up to the target value. Each pair should be in ascending order, and the list of p... |
from typing import List, Tuple
def search_key_in_sorted_matrix(matrix: List[List[int]], key: int) -> Tuple[int, int]:
m = len(matrix)
if m == 0:
return (-1, -1)
n = len(matrix[0])
i = 0
j = n - 1
while i < m and j >= 0:
current = matrix[i][j]
if current == key:
... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Context\nGiven a matrix sorted in non-decreasing order both row-wise and column-wise, your task is to locate a specified key within this matrix. This problem is essential in understanding search algorithms and efficient data access patterns in matrix data structures.\n\n#### Proble... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2722,
"level": 1,
"question": "#### Context\nGiven a matrix sorted in non-decreasing order both row-wise and column-wise, your task is to locate a specified key within this matrix. This problem is essential in understanding search algorithms and efficient data access patterns in mat... |
from collections import Counter
def most_common_values(lst):
if not lst:
return []
count = Counter(lst)
max_count = max(count.values())
return [k for k, v in count.items() if v == max_count] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that finds the most common value(s) in a list. If multiple values are the most common, return them all in a list. If the input list is empty, return an empty list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2723,
"level": 1,
"question": "Write a Python function that finds the most common value(s) in a list. If multiple values are the most common, return them all in a list. If the input list is empty, return an empty list.",
"split": "train"
} |
def count_ways(n: int) -> int:
if n == 0:
return 1
m = n + 1
a, b = 0, 1
for _ in range(m - 1):
c = a + b
a = b
b = c
return b | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\nYou are given a staircase with `n` steps. You can either climb 1 step or 2 steps at a time. Write a function `count_ways` that takes an integer `n` as input and returns the number of unique ways to climb to the top of the staircase.\n\n**Function Signature:**\n```python\nd... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2724,
"level": 1,
"question": "### Question\nYou are given a staircase with `n` steps. You can either climb 1 step or 2 steps at a time. Write a function `count_ways` that takes an integer `n` as input and returns the number of unique ways to climb to the top of the staircase.\n\n**... |
def transpose(matrix):
return [[row[i] for row in matrix] for i in range(len(matrix))] | simplelr_Apps | [
{
"content": "Question:\nWrite a function that transposes a given NxN matrix. The transpose of a matrix is obtained by swapping the elements across the main diagonal (i.e., the element at row i and column j would move to row j and column i).\n\nYour task is to write a function that takes a 2D list (matrix) as i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2725,
"level": 1,
"question": "Write a function that transposes a given NxN matrix. The transpose of a matrix is obtained by swapping the elements across the main diagonal (i.e., the element at row i and column j would move to row j and column i).\n\nYour task is to write a function... |
def cartesian_product(setA: set[int], setB: set[int]) -> set[tuple[int, int]]:
result = set()
for a in setA:
for b in setB:
result.add((a, b))
return result | simplelr_Algorithm | [
{
"content": "Question:\nCartesian Product of Sets\n\nYou are given two sets of integers. Your task is to compute the Cartesian product of these sets. The Cartesian product of two sets `A` and `B` is defined as the set of all ordered pairs `(a, b)` where `a` is an element of `A` and `b` is an element of `B`.\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2726,
"level": 1,
"question": "Cartesian Product of Sets\n\nYou are given two sets of integers. Your task is to compute the Cartesian product of these sets. The Cartesian product of two sets `A` and `B` is defined as the set of all ordered pairs `(a, b)` where `a` is an element of `... |
def nth_term_sequence(n):
return 2 ** n - 1
| simplelr_Taco | [
{
"content": "Question:\nGiven the infinite sequence of numbers where each term is generated by doubling the previous term and adding 1, starting from 1:\n\n```\n1, 3, 7, 15, 31, 63, ...\n```\n\nWrite a function that calculates the nth term of this sequence from the term index (starting at index 1) e.g.:\n\n```... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2727,
"level": 1,
"question": "Given the infinite sequence of numbers where each term is generated by doubling the previous term and adding 1, starting from 1:\n\n```\n1, 3, 7, 15, 31, 63, ...\n```\n\nWrite a function that calculates the nth term of this sequence from the term index... |
def fibonacci(n):
if n == 0:
return 0
memo = {0: 0, 1: 1}
for i in range(2, n + 1):
memo[i] = memo[i - 1] + memo[i - 2]
return memo[n] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to get the nth Fibonacci number in Python. The function should be efficient, even with large values of n. Consider using a technique to optimize the performance of the function. One way to achieve this is by using memoization. Can you provide a Python function that impl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2728,
"level": 1,
"question": "Write a function to get the nth Fibonacci number in Python. The function should be efficient, even with large values of n. Consider using a technique to optimize the performance of the function. One way to achieve this is by using memoization. Can you ... |
def find_element(matrix, target):
rows = len(matrix)
cols = len(matrix[0]) if rows > 0 else 0
low, high = 0, rows * cols - 1
while low <= high:
mid = (low + high) // 2
mid_val = matrix[mid // cols][mid % cols]
if mid_val == target:
return True
elif mid_val <... | simplelr_Filter | [
{
"content": "Question:\ndef find_element(matrix, target):\n rows = len(matrix)\n cols = len(matrix[0])\n low, high = 0, rows * cols - 1\n\n while low <= high:\n mid = (low + high) // 2\n mid_val = matrix[mid // cols][mid % cols]\n\n if mid_val == target:\n return Tru... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2729,
"level": 1,
"question": "def find_element(matrix, target):\n rows = len(matrix)\n cols = len(matrix[0])\n low, high = 0, rows * cols - 1\n\n while low <= high:\n mid = (low + high) // 2\n mid_val = matrix[mid // cols][mid % cols]\n\n if mid_val... |
def square_list(lst):
return [x ** 2 for x in lst] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts a list of integers and returns a new list containing the squares of each number in the original list, without using any loops.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2730,
"level": 1,
"question": "Create a function that accepts a list of integers and returns a new list containing the squares of each number in the original list, without using any loops.",
"split": "train"
} |
def list_intersection(lst1, lst2):
return [value for value in lst1 if value in lst2] | simplelr_Filter | [
{
"content": "Question:\ndef list_intersection(lst1, lst2):\n return [value for value in lst1 if value in lst2]\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2731,
"level": 1,
"question": "def list_intersection(lst1, lst2):\n return [value for value in lst1 if value in lst2]",
"split": "train"
} |
def find_missing_integer(nums: list[int]) -> int:
n = len(nums) + 1
expected = n * (n + 1) // 2
actual = sum(nums)
return expected - actual | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\n\nWrite a function called `find_missing_integer` that takes an array of integers, which contains all the numbers from 1 to `n` except one missing number, and finds that missing number. The array will not be in sorted order.\n\n### Input:\n\n- `nums` (List[int]): ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2732,
"level": 1,
"question": "### Problem Statement:\n\nWrite a function called `find_missing_integer` that takes an array of integers, which contains all the numbers from 1 to `n` except one missing number, and finds that missing number. The array will not be in sorted order.\n\n#... |
def trapWater(heights):
if not heights:
return 0
left = 0
right = len(heights) - 1
max_left = 0
max_right = 0
result = 0
while left <= right:
if max_left <= max_right:
current = heights[left]
if current > max_left:
max_left = current
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of integers where each element represents the height of a building. The buildings form a skyline, and it is raining. You need to determine how much water can be trapped between the buildings.\n\nMore formally, given an integer array 'heights' representing the height... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2733,
"level": 1,
"question": "You are given a list of integers where each element represents the height of a building. The buildings form a skyline, and it is raining. You need to determine how much water can be trapped between the buildings.\n\nMore formally, given an integer arra... |
from collections import deque
def min_subarray_len(arr, x):
pre_sum = [0]
for num in arr:
pre_sum.append(pre_sum[-1] + num)
dq = deque()
min_length = float('inf')
for i in range(len(pre_sum)):
# Maintain deque in increasing order of pre_sum
while dq and pre_sum[i] <= pre_sum... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` and an integer `x`. Find the **smallest** possible length of a contiguous subarray of which the sum is **equal to or greater than** `x`. If there isn't one, return `0` instead. For example, given `arr = [2, 3, 1, 2, 4, 3]` and `x = 7`, the minimu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2734,
"level": 1,
"question": "You are given an array of integers `arr` and an integer `x`. Find the **smallest** possible length of a contiguous subarray of which the sum is **equal to or greater than** `x`. If there isn't one, return `0` instead. For example, given `arr = [2, 3, 1... |
def concatenate_and_unique(A, B):
seen = set()
result = []
for elem in A:
if elem not in seen:
seen.add(elem)
result.append(elem)
for elem in B:
if elem not in seen:
seen.add(elem)
result.append(elem)
return result | simplelr_Filter | [
{
"content": "Question:\nConcatenate the following two lists in Python and create a new list that contains only unique elements. The order of the elements in the resulting list should be the same as the order of their first occurrence. Additionally, the solution should have a time complexity of O(n), where n is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2735,
"level": 1,
"question": "Concatenate the following two lists in Python and create a new list that contains only unique elements. The order of the elements in the resulting list should be the same as the order of their first occurrence. Additionally, the solution should have a ... |
def string_length(s):
i = 0
while True:
try:
s[i] # Attempt to access the i-th character
i += 1
except IndexError:
break
return i | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code snippet to get the length of a string, but without using the built-in function `len()`, and without using any loops or recursion. You can only use slicing, and you cannot use any external libraries or modules.\nAnswer:\nLet's think step by step.\n",
"role": "user... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2736,
"level": 1,
"question": "Write a Python code snippet to get the length of a string, but without using the built-in function `len()`, and without using any loops or recursion. You can only use slicing, and you cannot use any external libraries or modules.",
"split": "train"
} |
def combine_lists_to_dict(keys: list, values: list) -> dict:
"""
Combines two lists into a dictionary where keys come from the first list and values from the second.
Handles lists of unequal length by taking elements up to the length of the shorter list.
Raises ValueError if inputs are not lists.
""... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes two lists as input parameters, checks if they have equal length, and then combines the elements of the lists into a single dictionary. The keys of the dictionary should come from the first list and the values from the second list. Additionally, implem... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2737,
"level": 1,
"question": "Create a Python function that takes two lists as input parameters, checks if they have equal length, and then combines the elements of the lists into a single dictionary. The keys of the dictionary should come from the first list and the values from th... |
def is_palindrome(input_str):
"""
Checks if the input string is a palindrome.
Args:
input_str (str): The string to check.
Returns:
bool: True if the string is a palindrome, False otherwise.
"""
# Remove spaces and punctuation, and convert to lower case
cleaned_... | simplelr_Filter | [
{
"content": "Question:\nYou've been tasked with creating a function that determines whether a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). \n\n### Parameters:\n-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2738,
"level": 1,
"question": "You've been tasked with creating a function that determines whether a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capi... |
def fibonacci(n):
"""
This function generates the Fibonacci sequence up to n terms.
Args:
n: The number of terms to generate.
Returns:
A list containing the Fibonacci sequence up to n terms.
"""
fib_seq = []
a, b = 0, 1
for _ in range(n):
fib_seq.append(a)
... | simplelr_Filter | [
{
"content": "Question:\nThis is the code for the Fibonacci sequence generator, in Python:\n\n```python\ndef fibonacci(n):\n \"\"\"\n This function generates the Fibonacci sequence up to n terms.\n\n Args:\n n: The number of terms to generate.\n\n Returns:\n A list containing the Fibonacci sequence up... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2739,
"level": 1,
"question": "This is the code for the Fibonacci sequence generator, in Python:\n\n```python\ndef fibonacci(n):\n \"\"\"\n This function generates the Fibonacci sequence up to n terms.\n\n Args:\n n: The number of terms to generate.\n\n Returns:\n A list c... |
def has_schedule_overlap(schedule_1: list[tuple[int, int]], schedule_2: list[tuple[int, int]]) -> bool:
for a, b in schedule_1:
for c, d in schedule_2:
if a < d and c < b:
return True
return False | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Schedule Overlap Detection\n\nYou are tasked with developing a function that determines if there is any overlap between two schedules. Each schedule consists of a list of time intervals. An interval is represented by a tuple with start and end times in the format `(start, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2740,
"level": 1,
"question": "### Question: Schedule Overlap Detection\n\nYou are tasked with developing a function that determines if there is any overlap between two schedules. Each schedule consists of a list of time intervals. An interval is represented by a tuple with start an... |
from typing import List
def find_largest_consecutive_sum(nums: List[int]) -> int:
if not nums:
return 0
current_max = global_max = nums[0]
for num in nums[1:]:
current_max = max(num, current_max + num)
if current_max > global_max:
global_max = current_max
return glob... | simplelr_Package | [
{
"content": "Question:\nCreate a function named `find_largest_consecutive_sum` that finds the largest sum of consecutive integers in a list. The function should be efficient, having a time complexity of O(n). This problem is typically known as finding the maximum subarray sum.\n\nThe function signature should ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2741,
"level": 1,
"question": "Create a function named `find_largest_consecutive_sum` that finds the largest sum of consecutive integers in a list. The function should be efficient, having a time complexity of O(n). This problem is typically known as finding the maximum subarray sum... |
from collections import Counter
def can_form_palindrome(s: str) -> bool:
freq = Counter(s)
odd_count = sum(1 for count in freq.values() if count % 2 != 0)
if len(s) % 2 == 0:
return odd_count == 0
else:
return odd_count == 1
| simplelr_Taco | [
{
"content": "Question:\nYou are given a string containing only lowercase letters. You need to check if the string can be rearranged to form a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitaliz... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2742,
"level": 1,
"question": "You are given a string containing only lowercase letters. You need to check if the string can be rearranged to form a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring... |
from typing import List
def calculate_water_trapped(heights: List[int]) -> int:
if not heights or len(heights) < 2:
return 0
n = len(heights)
left = 0
right = n - 1
max_left = 0
max_right = 0
result = 0
while left <= right:
if max_left < max_right:
if h... | simplelr_Apps | [
{
"content": "Question:\n## Calculate the Water Trapped by the Heights\n\nYou are given an array of non-negative integers representing the elevations of a bar graph. Each element in the array represents the height of a bar at the corresponding position. Imagine that it is raining and each bar traps the amount o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2743,
"level": 1,
"question": "## Calculate the Water Trapped by the Heights\n\nYou are given an array of non-negative integers representing the elevations of a bar graph. Each element in the array represents the height of a bar at the corresponding position. Imagine that it is rain... |
from collections import defaultdict, deque
def topological_sort(graph):
"""Performs a topological sort on the given graph using Kahn's algorithm.
Args:
graph (dict): Adjacency list representation of the graph where each key is a node,
and its value is a list of neighboring nodes.... | simplelr_Filter | [
{
"content": "Question:\nI have a graph data structure implemented in Python using an adjacency list representation, with each node in the graph being a string. I need to implement the Kahn's algorithm to perform topological sorting on the graph. \n\nHere is my attempt so far:\n\n```python\nfrom collections imp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2744,
"level": 1,
"question": "I have a graph data structure implemented in Python using an adjacency list representation, with each node in the graph being a string. I need to implement the Kahn's algorithm to perform topological sorting on the graph. \n\nHere is my attempt so far:... |
def rearrange_buildings(heights):
sorted_h = sorted(heights)
n = len(sorted_h)
mid = n // 2
lower = sorted_h[:mid]
upper = sorted_h[mid:]
upper_reversed = upper[::-1]
result = []
i = j = 0
for k in range(n):
if k % 2 == 0:
result.append(upper_reversed[i])
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `heights` representing the heights of buildings. Your task is to **rearrange** the buildings such that the **absolute difference** between the heights of any two adjacent buildings is **maximized**. Return _the rearranged array_. If there are ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2745,
"level": 1,
"question": "You are given a **0-indexed** integer array `heights` representing the heights of buildings. Your task is to **rearrange** the buildings such that the **absolute difference** between the heights of any two adjacent buildings is **maximized**. Return _t... |
import seaborn as sns
import matplotlib.pyplot as plt
def create_residual_plots():
mpg = sns.load_dataset('mpg')
# Simple Residual Plot
plt.figure(figsize=(8,6))
sns.residplot(x='weight', y='displacement', data=mpg)
plt.title('Residual Plot: Displacement vs Weight')
plt.tight_layout()
... | simplelr_Docs | [
{
"content": "Question:\n**Objective:** \nEvaluate the student's ability to use seaborn for creating residual plots and understanding their significance in regression analysis.\n\n**Problem Statement:**\n\nYou are provided with the \"mpg\" dataset from seaborn. This dataset contains various attributes of differ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2746,
"level": 1,
"question": "**Objective:** \nEvaluate the student's ability to use seaborn for creating residual plots and understanding their significance in regression analysis.\n\n**Problem Statement:**\n\nYou are provided with the \"mpg\" dataset from seaborn. This dataset co... |
def remove_divisible_by_3(nums):
return [num for num in nums if num % 3 != 0] | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python to remove all numbers from an array that are divisible by 3.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2747,
"level": 1,
"question": "Write a function in Python to remove all numbers from an array that are divisible by 3.",
"split": "train"
} |
def first_missing_positive(nums):
if not nums:
return 1
num_set = set(nums)
current = 1
while current in num_set:
current += 1
return current | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the first missing positive integer in an array of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2748,
"level": 1,
"question": "Write a python function to find the first missing positive integer in an array of integers.",
"split": "train"
} |
def is_balanced(s: str) -> bool:
"""
Check if the brackets in the string are balanced.
:param s: A string containing just the characters '(', ')', '{', '}', '[' and ']'
:return: True if the string is valid, False otherwise.
"""
stack = []
closing_to_opening = {')': '(', '}': '{', '... | simplelr_Package | [
{
"content": "Question:\n**Problem: Balanced Parentheses Checker**\n\nIn this problem, you are tasked with creating 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 are clo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2749,
"level": 1,
"question": "**Problem: Balanced Parentheses Checker**\n\nIn this problem, you are tasked with creating a function that takes a string containing just the characters '(', ')', '{', '}', '[' and ']', and determines if the input string is valid. An input string is va... |
def cube_even_numbers(lst):
result = []
for num in lst:
if num % 2 == 0:
result.append(num ** 3)
return result | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns a new list containing the cubes of the original integers, but only for those integers that are even. The function should maintain the order of appearance from the original list.\nAnswer:\nLet's think step by step.\n",
"role"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2750,
"level": 1,
"question": "Write a function that takes a list of integers and returns a new list containing the cubes of the original integers, but only for those integers that are even. The function should maintain the order of appearance from the original list.",
"split": "t... |
from typing import List
def find_missing_number(nums: List[int]) -> int:
n = len(nums)
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum | simplelr_Data_Structure | [
{
"content": "Question:\n### Missing Number Finder\n\n**Objective**: Implement a function to determine the missing number in a given sequence of unique integers ranging from 0 to n.\n\n#### Scenario\nYou are tasked with verifying and correcting a sequence of IDs assigned from a range [0..n] that might be missin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2751,
"level": 1,
"question": "### Missing Number Finder\n\n**Objective**: Implement a function to determine the missing number in a given sequence of unique integers ranging from 0 to n.\n\n#### Scenario\nYou are tasked with verifying and correcting a sequence of IDs assigned from ... |
def min_deletions_to_palindrome(s):
n = len(s)
if n == 0:
return 0
# Create a DP table with all elements initialized to 0
dp = [[0] * n for _ in range(n)]
# Fill the diagonal: single character substrings
for i in range(n):
dp[i][i] = 1
# Fill the table for subs... | simplelr_Filter | [
{
"content": "Question:\nI have a need to write a Python function that takes a string as input and returns the minimum number of deletions required to make the string a palindrome. How can I achieve this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2752,
"level": 1,
"question": "I have a need to write a Python function that takes a string as input and returns the minimum number of deletions required to make the string a palindrome. How can I achieve this?",
"split": "train"
} |
import heapq
from typing import List, Tuple
def process_tasks(tasks: List[Tuple[int, str]]) -> List[str]:
heap = []
count = 0
for priority, task_name in tasks:
heapq.heappush(heap, (priority, count, task_name))
count += 1
result = []
while heap:
_, _, task_name = heapq.... | simplelr_Docs | [
{
"content": "Question:\nIn this assessment, you will implement a function that processes a list of tasks, each with a priority, using a priority queue implemented with the `heapq` module. Each task is represented as a tuple `(priority, task_name)`, where `priority` is an integer (smaller values indicate higher... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2753,
"level": 1,
"question": "In this assessment, you will implement a function that processes a list of tasks, each with a priority, using a priority queue implemented with the `heapq` module. Each task is represented as a tuple `(priority, task_name)`, where `priority` is an inte... |
def sort_array(arr):
return sorted(arr)
# Example usage:
# print(sort_array([5, 1, 3, 2, 4])) # Output: [1, 2, 3, 4, 5] | simplelr_Filter | [
{
"content": "Question:\nCreate a function in Python for sorting an array of numbers in increasing order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2754,
"level": 1,
"question": "Create a function in Python for sorting an array of numbers in increasing order.",
"split": "train"
} |
from typing import List
def max_profit(prices: List[int], k: int) -> int:
sorted_prices = sorted(prices, reverse=True)
return sum(sorted_prices[:k]) | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given a list of integers representing prices of items in a store and an integer `k`, where `k` is the maximum number of items you can choose from the list. You need to find the maximum profit you can make by selecting `k` items whose prices sum up to the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2755,
"level": 1,
"question": "### Problem Statement\n\nYou are given a list of integers representing prices of items in a store and an integer `k`, where `k` is the maximum number of items you can choose from the list. You need to find the maximum profit you can make by selecting `... |
def filter_users(users: list[dict], lower_bound: int, upper_bound: int) -> list[dict]:
filtered = []
for index, user in enumerate(users):
count = user['follower_count']
if lower_bound <= count <= upper_bound:
filtered.append( (-count, index, user) )
filtered.sort()
result = [... | simplelr_Algorithm | [
{
"content": "Question:\n### **Coding Assessment Question**\n\n#### Context:\nA popular social media application stores users' data as a list of dictionaries where each dictionary contains information about a user, including their `username`, `follower_count`, and other related attributes. To improve the recomm... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2756,
"level": 1,
"question": "### **Coding Assessment Question**\n\n#### Context:\nA popular social media application stores users' data as a list of dictionaries where each dictionary contains information about a user, including their `username`, `follower_count`, and other relate... |
def smallest_missing_positive_integer(lst):
s = set(lst)
n = 1
while n in s:
n += 1
return n | simplelr_Filter | [
{
"content": "Question:\nI need to write a Python function that finds the smallest positive integer not present in a given list of integers. Can you guide me on how to approach this problem?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2757,
"level": 1,
"question": "I need to write a Python function that finds the smallest positive integer not present in a given list of integers. Can you guide me on how to approach this problem?",
"split": "train"
} |
def remove_consecutive_repeats(s):
result = ""
previous_char = None
for char in s:
if previous_char != char:
result += char
previous_char = char
return result | simplelr_Filter | [
{
"content": "Question:\nCan you write a function in Python that removes consecutive repeating characters in a given string, while keeping the first character of each sequence of repeating characters intact?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2758,
"level": 1,
"question": "Can you write a function in Python that removes consecutive repeating characters in a given string, while keeping the first character of each sequence of repeating characters intact?",
"split": "train"
} |
def can_measure_exact_volume(capacities, volume):
if volume == 0:
return True
dp = [False] * (volume + 1)
dp[0] = True
for c in capacities:
for i in range(c, volume + 1):
if dp[i - c]:
dp[i] = True
return dp[volume] | simplelr_Apps | [
{
"content": "Question:\n# Task\nYou are provided with an array of integers representing the capacities of containers and the exact volume of water you need to measure using these containers.\n\nEach container can be filled to its capacity or left empty, but you can only measure exact volumes that can be formed... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2759,
"level": 1,
"question": "# Task\nYou are provided with an array of integers representing the capacities of containers and the exact volume of water you need to measure using these containers.\n\nEach container can be filled to its capacity or left empty, but you can only measu... |
def replace_with_average(lst):
new_lst = lst.copy()
for i in range(len(new_lst) - 2):
a, b, c = new_lst[i], new_lst[i+1], new_lst[i+2]
if b == a + 1 and c == a + 2:
avg = (a + b + c) / 3
rounded_avg = round(avg)
new_lst[i] = rounded_avg
break
r... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that takes in a list of numbers as input. The program should find the first three elements in the list that are consecutive integers. Once found, it should replace the first of these three elements with the average of the three numbers, rounded to the nearest inte... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2760,
"level": 1,
"question": "Write a Python program that takes in a list of numbers as input. The program should find the first three elements in the list that are consecutive integers. Once found, it should replace the first of these three elements with the average of the three n... |
def reverse_string(s):
return s[::-1] | simplelr_Filter | [
{
"content": "Question:\nWe need to write a Python function that takes a string as input and returns the reverse of the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2761,
"level": 1,
"question": "We need to write a Python function that takes a string as input and returns the reverse of the string.",
"split": "train"
} |
def f(x, n):
return [element for num in x for element in [num] * n] | simplelr_Filter | [
{
"content": "Question:\nIn the context of the provided code, can you explain the purpose of the function `f` and how it works? The function `f` takes a list `x` and an integer `n` as inputs and returns a new list where each element of `x` is repeated `n` times. For example, if `x = [1, 2, 3]` and `n = 2`, the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2762,
"level": 1,
"question": "In the context of the provided code, can you explain the purpose of the function `f` and how it works? The function `f` takes a list `x` and an integer `n` as inputs and returns a new list where each element of `x` is repeated `n` times. For example, i... |
def find_max(numbers):
if not numbers:
return None
return max(numbers) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the maximum element in a list of numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2763,
"level": 1,
"question": "Write a Python function to find the maximum element in a list of numbers.",
"split": "train"
} |
import json
def read_json_file(file_path):
try:
with open(file_path, 'r') as file:
return json.load(file)
except (FileNotFoundError, PermissionError, json.JSONDecodeError):
return None | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that reads a JSON file and converts its contents to a dictionary. If the file is not found, it should return `None`. The function should also handle potential errors related to file permissions or invalid JSON format gracefully.\nAnswer:\nLet's think step by step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2764,
"level": 1,
"question": "Write a Python function that reads a JSON file and converts its contents to a dictionary. If the file is not found, it should return `None`. The function should also handle potential errors related to file permissions or invalid JSON format gracefully.... |
def median_monthly_rainfall(rainfall):
if not rainfall:
return 0.0
sorted_rainfall = sorted(rainfall)
n = len(sorted_rainfall)
if n % 2 == 0:
mid1 = sorted_rainfall[(n // 2) - 1]
mid2 = sorted_rainfall[n // 2]
median = (mid1 + mid2) / 2
else:
median = sorted_r... | simplelr_Apps | [
{
"content": "Question:\n# Task\n\nImplement a function to calculate the median monthly rainfall given a list of daily rainfall amounts for a certain period.\n\n# Notes\n\n* The input is a list of integers where each integer represents the rainfall amount for one day.\n* If the list is empty, return 0.\n* If th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2765,
"level": 1,
"question": "# Task\n\nImplement a function to calculate the median monthly rainfall given a list of daily rainfall amounts for a certain period.\n\n# Notes\n\n* The input is a list of integers where each integer represents the rainfall amount for one day.\n* If th... |
def get_unique_elements(lst):
freq = {}
for num in lst:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
result = []
for num in lst:
if freq[num] == 1:
result.append(num)
return result | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns a new list containing only the elements that are unique within the original list. For the purposes of this problem, \"unique\" means the element appears exactly once in the input list. Ensure that the relative order of the eleme... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2766,
"level": 1,
"question": "Write a function that takes a list of integers and returns a new list containing only the elements that are unique within the original list. For the purposes of this problem, \"unique\" means the element appears exactly once in the input list. Ensure t... |
from typing import List
def is_sorted(stack: List[int]) -> bool:
n = len(stack)
if n <= 1:
return True
for i in range(n - 1):
if stack[i] > stack[i + 1]:
return False
return True | simplelr_Data_Structure | [
{
"content": "Question:\n### Sorting Check in Stack\n\nYou are given a stack. Implement a function to check if the elements in the stack are in ascending order from bottom to top.\n\n#### Function Signature\n```python\ndef is_sorted(stack: List[int]) -> bool:\n # implementation here\n```\n\n#### Input\n* `st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2767,
"level": 1,
"question": "### Sorting Check in Stack\n\nYou are given a stack. Implement a function to check if the elements in the stack are in ascending order from bottom to top.\n\n#### Function Signature\n```python\ndef is_sorted(stack: List[int]) -> bool:\n # implementa... |
from collections import Counter
def count_items(items):
counts = Counter(items)
return dict(counts) | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function in Python that demonstrates the use of the `collections.Counter` class from the `collections` module. Your goal is to write a function named `count_items` that takes a list of items and returns a dictionary with the count of each unique item.\n\nS... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2768,
"level": 1,
"question": "You are tasked with creating a function in Python that demonstrates the use of the `collections.Counter` class from the `collections` module. Your goal is to write a function named `count_items` that takes a list of items and returns a dictionary with ... |
def segment_sum(arr, queries):
# Calculate prefix sums
prefix_sums = [0] # prefix_sums[0] is 0, prefix_sums[1] is arr[0], etc.
current_sum = 0
for num in arr:
current_sum += num
prefix_sums.append(current_sum)
# Process each query and compute the sum
results = []
for l,... | simplelr_Code_Contests | [
{
"content": "Question:\n### Problem: Array Segments Summation\n\nYou are given an array of integers, and your task is to find the sum of elements in specified segments of the array. Each segment is defined by its starting and ending indices (inclusive).\n\nWrite a function `segment_sum(arr: List[int], queries:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2769,
"level": 1,
"question": "### Problem: Array Segments Summation\n\nYou are given an array of integers, and your task is to find the sum of elements in specified segments of the array. Each segment is defined by its starting and ending indices (inclusive).\n\nWrite a function `s... |
def filter_dicts_by_key(dict_list, key, threshold):
return [d for d in dict_list if key in d and d[key] > threshold] | simplelr_Filter | [
{
"content": "Question:\nHow to create a Python function that takes a list of dictionaries as input and returns a new list containing only the dictionaries from the input list whose values for a given key 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": 2770,
"level": 1,
"question": "How to create a Python function that takes a list of dictionaries as input and returns a new list containing only the dictionaries from the input list whose values for a given key are greater than a given threshold.",
"split": "train"
} |
def calculate_discount(original_price, discount_percentage):
return original_price * (1 - discount_percentage / 100) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `calculate_discount(original_price, discount_percentage)` that calculates and returns the discounted price.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2771,
"level": 1,
"question": "Write a Python function `calculate_discount(original_price, discount_percentage)` that calculates and returns the discounted price.",
"split": "train"
} |
from collections import deque
def shortest_path_unweighted(graph, source, target):
if source == target:
return 0
visited = set()
queue = deque([(source, 0)])
visited.add(source)
while queue:
current_node, current_dist = queue.popleft()
for neighbor in graph[current... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\n#### Context\nA common task in various algorithms and data structures is to find the shortest path in an unweighted graph. One widely used algorithm for this purpose is Breadth-First Search (BFS). BFS explores the graph level by level, starting from a given source node.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2772,
"level": 1,
"question": "### Question\n\n#### Context\nA common task in various algorithms and data structures is to find the shortest path in an unweighted graph. One widely used algorithm for this purpose is Breadth-First Search (BFS). BFS explores the graph level by level, ... |
def find_missing_letter(chars):
given_sum = sum(ord(c) for c in chars)
n = len(chars)
a = ord(chars[0])
expected_sum = (n + 1) * (2 * a + n) // 2
missing_ord = expected_sum - given_sum
return chr(missing_ord) | simplelr_Apps | [
{
"content": "Question:\nWrite a function `find_missing_letter` that takes in an array of consecutive (increasing) letters as input, with one letter missing, and returns the missing letter.\n\nYou will always get an array that contains consecutive letters in increasing order with exactly one letter missing. The... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2773,
"level": 1,
"question": "Write a function `find_missing_letter` that takes in an array of consecutive (increasing) letters as input, with one letter missing, and returns the missing letter.\n\nYou will always get an array that contains consecutive letters in increasing order w... |
def vigenere_cipher(text, key, encrypt=True):
key = key.upper()
key_len = len(key)
if key_len == 0:
return text
text_len = len(text)
key_stream = [key[i % key_len] for i in range(text_len)]
result = []
for i in range(text_len):
char = text[i]
if not char.isalpha():
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to implement the Vigenere Cipher with a key provided by the user. Ensure that the function can both encrypt and decrypt any given string with this key. The key will only consist of uppercase letters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2774,
"level": 1,
"question": "Write a python function to implement the Vigenere Cipher with a key provided by the user. Ensure that the function can both encrypt and decrypt any given string with this key. The key will only consist of uppercase letters.",
"split": "train"
} |
def first_non_repeating(nums):
freq = {}
for num in nums:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
for num in nums:
if freq[num] == 1:
return num
return -1 | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers, where some values are duplicated, you need to find the first non-repeating element. Return the value of the first non-repeating element. If no such element exists, return -1. The code should accomplish this with a time complexity of O(n).\n\nExample 1:\nInput... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2775,
"level": 1,
"question": "Given an array of integers, where some values are duplicated, you need to find the first non-repeating element. Return the value of the first non-repeating element. If no such element exists, return -1. The code should accomplish this with a time compl... |
from collections import Counter
def can_rearrange_spells(spells):
if not spells:
return True
freq = Counter(spells)
max_freq = max(freq.values())
n = len(spells)
threshold = (n + 1) // 2
return max_freq <= threshold | simplelr_Leetcode | [
{
"content": "Question:\nA wizard is creating spell sequences. He wants to make sure that no two consecutive spells in his sequence are the same type. Given an integer array `spells`, where each integer represents a type of spell, return _**true** if it's possible to rearrange the spells such that no two consec... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2776,
"level": 1,
"question": "A wizard is creating spell sequences. He wants to make sure that no two consecutive spells in his sequence are the same type. Given an integer array `spells`, where each integer represents a type of spell, return _**true** if it's possible to rearrange... |
from typing import List
def transpose(matrix: List[List[int]]) -> List[List[int]]:
return [list(row) for row in zip(*matrix)] | simplelr_Algorithm | [
{
"content": "Question:\n### Matrix Transpose\n\nYou are tasked with performing a common operation on matrices: transposing. Transposing a matrix means switching the rows and columns of the matrix.\n\n#### Objective\nWrite a function `transpose` that takes a 2D list (matrix) and returns its transpose.\n\n#### F... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2777,
"level": 1,
"question": "### Matrix Transpose\n\nYou are tasked with performing a common operation on matrices: transposing. Transposing a matrix means switching the rows and columns of the matrix.\n\n#### Objective\nWrite a function `transpose` that takes a 2D list (matrix) a... |
def multiply(num1, num2):
if num1 == "0" or num2 == "0":
return "0"
num1_list = list(map(int, reversed(num1)))
num2_list = list(map(int, reversed(num2)))
m = len(num1_list)
n = len(num2_list)
res = [0] * (m + n)
for i in range(n):
for j in range(m):
product = ... | simplelr_Taco | [
{
"content": "Question:\nYou are given two non-negative integers as strings. Write a function to multiply these two numbers and return the product as a string. \n\nNote:\n1. The input numbers are strings, and their lengths are between 1 and 200.\n2. The numbers represented by the input strings are both non-nega... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2778,
"level": 1,
"question": "You are given two non-negative integers as strings. Write a function to multiply these two numbers and return the product as a string. \n\nNote:\n1. The input numbers are strings, and their lengths are between 1 and 200.\n2. The numbers represented by ... |
from sklearn.linear_model import LinearRegression
def fit_and_predict_linear_regression(X_train, y_train, X_new):
model = LinearRegression()
model.fit(X_train, y_train)
coef = model.coef_
intercept = model.intercept_
predictions = model.predict(X_new)
return coef, intercept, predictions | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function to fit a linear regression model using the `scikit-learn` library. The function will train the model on a given dataset and predict values for new data points, returning the coefficient and intercept of the model as well.\n\n### Task\n\nCreate a f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2779,
"level": 1,
"question": "You are tasked with creating a function to fit a linear regression model using the `scikit-learn` library. The function will train the model on a given dataset and predict values for new data points, returning the coefficient and intercept of the model... |
def summarize_file(filepath):
try:
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
except FileNotFoundError:
raise FileNotFoundError(f"The file {filepath} does not exist.")
except UnicodeDecodeError:
raise ValueError("The file contains non-text c... | simplelr_Package | [
{
"content": "Question:\nDesign a function that will take in a string representing a filepath to a text file, read through the file, and summarize the contents by providing the total word count and the count of each unique word, ignoring case. The function should output a dictionary where the keys represent uni... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2780,
"level": 1,
"question": "Design a function that will take in a string representing a filepath to a text file, read through the file, and summarize the contents by providing the total word count and the count of each unique word, ignoring case. The function should output a dict... |
import bisect
def max_consecutive_days(nums, limit):
prefix = [0]
for num in nums:
prefix.append(prefix[-1] + num)
max_length = 0
for j in range(1, len(prefix)):
target = prefix[j] - limit
i = bisect.bisect_left(prefix, target, 0, j)
current_length = j - i
if cur... | simplelr_Evol | [
{
"content": "Question:\nYou are given an integer array `nums` representing the cost of different stocks on given days, and you are allowed to accumulate stocks over several days. Each day, you can choose to either buy one stock of the current day’s price or not buy any stock at all. Write a function to find th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2781,
"level": 1,
"question": "You are given an integer array `nums` representing the cost of different stocks on given days, and you are allowed to accumulate stocks over several days. Each day, you can choose to either buy one stock of the current day’s price or not buy any stock ... |
from collections import deque
def longest_subsequence_within_range(arr, k):
if not arr:
return 0
max_deque = deque()
min_deque = deque()
left = 0
max_length = 0 # Initialize max_length to 0
for right in range(len(arr)):
# Update max_deque
while max_deque and arr[righ... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Description\n\nYou are given the task of implementing a function to determine the longest contiguous subsequence in an array where the difference between the maximum and minimum elements is no greater than `k`. The function should return the length of this subsequence.\n\n##... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2782,
"level": 1,
"question": "### Problem Description\n\nYou are given the task of implementing a function to determine the longest contiguous subsequence in an array where the difference between the maximum and minimum elements is no greater than `k`. The function should return th... |
import heapq
def k_smallest_pairs(nums1, nums2, k):
if not nums1 or not nums2 or k == 0:
return []
heap = []
visited = set()
# Initialize the heap with the smallest possible pair
heapq.heappush(heap, (nums1[0] + nums2[0], 0, 0))
visited.add((0, 0))
result = []
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two integer arrays `nums1` and `nums2` sorted in non-decreasing order and an integer `k`. Find the `k` pairs `(u, v)` which have the smallest sums, where `u` is an element from `nums1` and `v` is an element from `nums2`. Return the answer in any order.\n\nExample:\n```pyth... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2783,
"level": 1,
"question": "You are given two integer arrays `nums1` and `nums2` sorted in non-decreasing order and an integer `k`. Find the `k` pairs `(u, v)` which have the smallest sums, where `u` is an element from `nums1` and `v` is an element from `nums2`. Return the answer... |
def merge_lists(list1, list2):
combined = list1 + list2
seen = set()
result = []
for item in combined:
if item not in seen:
seen.add(item)
result.append(item)
return result | simplelr_Filter | [
{
"content": "Question:\nI need to write a Python function that takes two lists as input and returns a new list containing all the elements from both input lists, without any duplicates.\n\nHere's what I have so far:\n\n```python\ndef merge_lists(list1, list2):\n new_list = list1 + list2\n return new_list... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2784,
"level": 1,
"question": "I need to write a Python function that takes two lists as input and returns a new list containing all the elements from both input lists, without any duplicates.\n\nHere's what I have so far:\n\n```python\ndef merge_lists(list1, list2):\n new_list =... |
from typing import List
def find_single_element(nums: List[int]) -> int:
result = 0
for num in nums:
result ^= num
return result | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a list of integers where every element appears exactly twice, except for one element which appears exactly once. Your task is to find that single element which appears exactly once.\n\nWrite a function:\n```python\ndef find_single_element(nums: List[int]) -> int:\n \"\"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2785,
"level": 1,
"question": "You are given a list of integers where every element appears exactly twice, except for one element which appears exactly once. Your task is to find that single element which appears exactly once.\n\nWrite a function:\n```python\ndef find_single_element... |
def reverse_list(lst):
if len(lst) <= 1:
return lst
else:
return reverse_list(lst[1:]) + [lst[0]] | simplelr_Filter | [
{
"content": "Question:\nCould you provide a simple example of a Python function that reverses a list using recursion?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2786,
"level": 1,
"question": "Could you provide a simple example of a Python function that reverses a list using recursion?",
"split": "train"
} |
from typing import List
def calculate_trapped_water(heights: List[int]) -> int:
if not heights or len(heights) < 3:
return 0
n = len(heights)
left_max = [0] * n
for i in range(1, n):
left_max[i] = max(left_max[i - 1], heights[i - 1])
right_max = [0] * n
for i in range(n - ... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a list of integers representing the amount of rainwater trapped above each building in a skyline. Each index in the list represents the height of the building. Calculate the total amount of rainwater trapped after it rains.\n\nFor example, given the list `[0, 2, 0, 3, 0, 4... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2787,
"level": 1,
"question": "You are given a list of integers representing the amount of rainwater trapped above each building in a skyline. Each index in the list represents the height of the building. Calculate the total amount of rainwater trapped after it rains.\n\nFor example... |
def reverse_array(arr):
low = 0
high = len(arr) - 1
while low < high:
arr[low], arr[high] = arr[high], arr[low]
low += 1
high -= 1
return arr | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that reverses a given array of integers without using extra space. The function should modify the array in-place and return the reversed array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2788,
"level": 1,
"question": "Create a function that reverses a given array of integers without using extra space. The function should modify the array in-place and return the reversed array.",
"split": "train"
} |
def calculate_game_score(events):
points = {
"quest": 50,
"battle_win": 100,
"battle_loss": -20,
"treasure": 75,
"trap": -30
}
total = 0
for event in events:
total += points[event]
if total < 0:
return 'Defeated'
elif total <= 100:
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of strings representing different types of events in a video game. Each event can either increase or decrease the player's score. The events and their corresponding impact on the score are as follows:\n\n- \"quest\" = +50 points\n- \"battle_win\" = +100 points\n- \"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2789,
"level": 1,
"question": "You are given a list of strings representing different types of events in a video game. Each event can either increase or decrease the player's score. The events and their corresponding impact on the score are as follows:\n\n- \"quest\" = +50 points\n-... |
def containsDuplicate(nums):
return len(nums) != len(set(nums)) | simplelr_Filter | [
{
"content": "Question:\nGiven an unsorted array of integers, write a function that determines whether it contains any duplicates.\n\nExample:\n\nInput: [1,2,3,1]\nOutput: True\n\nInput: [4,5,6,7]\nOutput: False\n\nHere is the solution in Python:\n```python\ndef containsDuplicate(nums):\n seen = set()\n f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2790,
"level": 1,
"question": "Given an unsorted array of integers, write a function that determines whether it contains any duplicates.\n\nExample:\n\nInput: [1,2,3,1]\nOutput: True\n\nInput: [4,5,6,7]\nOutput: False\n\nHere is the solution in Python:\n```python\ndef containsDuplic... |
def find_digit_occurrences(list1, list2):
# Create a set of target digits as strings
target_digits = {str(d) for d in list2}
# Initialize counts for each digit
counts = {str(d): 0 for d in list2}
# Iterate through each string in list1
for string in list1:
for char in string:
... | simplelr_Filter | [
{
"content": "Question:\nI have two lists in python, one containing strings and the other containing integers. I want to find the most occurrences of a specific digit in all the strings. \n\nExample:\nlist1 = ['hello1', 'hello3', '3hello', '2hello2']\nlist2 = [1, 2, 3]\n\nI would like to get a list of tuples, w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2791,
"level": 1,
"question": "I have two lists in python, one containing strings and the other containing integers. I want to find the most occurrences of a specific digit in all the strings. \n\nExample:\nlist1 = ['hello1', 'hello3', '3hello', '2hello2']\nlist2 = [1, 2, 3]\n\nI wo... |
def count_distinct_vowels(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
found = set()
for char in s:
lower_char = char.lower()
if lower_char in vowels:
found.add(lower_char)
return len(found)
| simplelr_Taco | [
{
"content": "Question:\nComplete the function/method so that it returns the count of distinct vowels in a given string. The vowels are 'a', 'e', 'i', 'o', and 'u'. The function should be case-insensitive.\n\n## Examples\n\n```python\n# returns 2\ncount_distinct_vowels('Hello')\n\n# returns 0\ncount_distinct_vo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2792,
"level": 1,
"question": "Complete the function/method so that it returns the count of distinct vowels in a given string. The vowels are 'a', 'e', 'i', 'o', and 'u'. The function should be case-insensitive.\n\n## Examples\n\n```python\n# returns 2\ncount_distinct_vowels('Hello'... |
def generate_sequence(n):
if n <= 0:
return ""
else:
return ' '.join(str(i) for i in range(1, n + 1)) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that generates a sequence of numbers from 1 to a given number n, and then returns the sequence as a string where numbers are separated by spaces. If the sequence is empty (i.e., n is 0 or negative), the function should return an empty string.\nAnswer:\nLet's thin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2793,
"level": 1,
"question": "Write a Python function that generates a sequence of numbers from 1 to a given number n, and then returns the sequence as a string where numbers are separated by spaces. If the sequence is empty (i.e., n is 0 or negative), the function should return an... |
import math
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, math.isqrt(n) + 1, 2):
if n % i == 0:
return False
return True | simplelr_Filter | [
{
"content": "Question:\nCreate a function in Python that checks if a given number is a prime number. The function should take an integer as input and return `True` if the number is prime, and `False` otherwise. Make sure to handle edge cases, such as when the input number is less than 2.\nAnswer:\nLet's think ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2794,
"level": 1,
"question": "Create a function in Python that checks if a given number is a prime number. The function should take an integer as input and return `True` if the number is prime, and `False` otherwise. Make sure to handle edge cases, such as when the input number is ... |
def count_non_extinguished_candles(heights):
max_so_far = 0
count = 0
for h in reversed(heights):
if h > max_so_far:
count += 1
max_so_far = h
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of `n` integers `heights` representing the heights of a collection of candles. A candle can be extinguished if there is a taller candle to its right that can block the view of the wind. Determine the _number of candles that cannot be extinguished._ A candle is con... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2795,
"level": 1,
"question": "You are given an array of `n` integers `heights` representing the heights of a collection of candles. A candle can be extinguished if there is a taller candle to its right that can block the view of the wind. Determine the _number of candles that canno... |
def circular_array_rotation(arr: list[int], k: int) -> list[int]:
n = len(arr)
if n == 0:
return []
effective_k = k % n
return arr[-effective_k:] + arr[:-effective_k] | simplelr_Algorithm | [
{
"content": "Question:\n### Circular Array Rotation\n\n#### Context\nYou are building a feature for a data analysis application that allows users to rotate elements in a circular array. This feature is often used to analyze data with periodic patterns, such as time-series data.\n\n#### Task\nImplement a functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2796,
"level": 1,
"question": "### Circular Array Rotation\n\n#### Context\nYou are building a feature for a data analysis application that allows users to rotate elements in a circular array. This feature is often used to analyze data with periodic patterns, such as time-series dat... |
def execute_commands(commands):
current = []
for command in commands:
ops = command.split(',')
for op in ops:
parts = op.split('/')
for part in parts:
if part == '..':
if current:
current.pop()
el... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of strings `commands`, where each command is a comma-separated sequence of operations. Each operation is a string of directory names followed by \"/\" or \"..\" to represent moving into a directory or moving one level up, respectively. You are supposed to determine ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2797,
"level": 1,
"question": "You are given a list of strings `commands`, where each command is a comma-separated sequence of operations. Each operation is a string of directory names followed by \"/\" or \"..\" to represent moving into a directory or moving one level up, respectiv... |
def is_balanced(s: str) -> bool:
"""
Returns whether the given string of parentheses is balanced.
Parameters:
s (str): A string containing only the characters '(', ')', '[', ']', '{', '}'.
Returns:
bool: True if the string is balanced, False otherwise.
"""
stack = []
cl... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Objective\nImplement a function that checks whether a given string of parentheses is balanced or not. The string can contain different types of parentheses: round `()`, square `[]`, and curly `{}`.\n\n**Function Signature**:\n```python\ndef is_bala... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2798,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Objective\nImplement a function that checks whether a given string of parentheses is balanced or not. The string can contain different types of parentheses: round `()`, square `[]`, and curly `{}`.\n\n**Function S... |
def hailstone_length(n: int) -> int:
# Check if input is an integer
if not isinstance(n, int):
raise TypeError("The input must be a positive integer.")
# Check if input is a positive integer
if n <= 0:
raise ValueError("The input must be a positive integer.")
count = 1
curre... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\nIn computer science, the hailstone sequence (also known as the Collatz sequence) is an integer sequence defined as follows:\n\n- Start with any positive integer \\( n \\).\n- Then each term is obtained from the previous term as follows:\n - If the previous term is even, t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2799,
"level": 1,
"question": "### Question\nIn computer science, the hailstone sequence (also known as the Collatz sequence) is an integer sequence defined as follows:\n\n- Start with any positive integer \\( n \\).\n- Then each term is obtained from the previous term as follows:\n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.