target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
def sum_of_elements(lst):
return sum(lst) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list as an input and returns the sum of its elements. The list contains integers. The sum of elements can be calculated using a loop or any other method. Please provide a Python code solution.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5200,
"level": 1,
"question": "Create a function that takes a list as an input and returns the sum of its elements. The list contains integers. The sum of elements can be calculated using a loop or any other method. Please provide a Python code solution.",
"split": "train"
} |
def min_deletions_to_avoid_adjacent_dupes(sequence):
dp = {'A': 0, 'B': 0, 'C': 0}
for c in sequence:
others = [char for char in dp if char != c]
max_prev = max(dp[others[0]], dp[others[1]])
if dp[c] < max_prev + 1:
dp[c] = max_prev + 1
max_length = max(dp.values())
r... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `sequence` which only contains the characters `'A'`, `'B'`, and `'C'`, determine the minimum number of deletions needed to make sure that no two adjacent characters are the same. Return the minimum number of deletions required. For example, given `sequence = \"ABCA\"`, th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5201,
"level": 1,
"question": "Given a string `sequence` which only contains the characters `'A'`, `'B'`, and `'C'`, determine the minimum number of deletions needed to make sure that no two adjacent characters are the same. Return the minimum number of deletions required. For examp... |
def reverse_join(lst, sep=''):
if not lst:
return ""
reversed_strings = [s[::-1] for s in lst]
return sep.join(reversed_strings) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of strings, reverse the order of each string, and then join them with a specific character. For instance, given a list `['hello', 'world']` and a separator `'-'`, the function should return `'olleh-worl'`. If the list is empty, it should return an emp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5202,
"level": 1,
"question": "Create a function that takes a list of strings, reverse the order of each string, and then join them with a specific character. For instance, given a list `['hello', 'world']` and a separator `'-'`, the function should return `'olleh-worl'`. If the lis... |
def first_even_number(lst):
first_even_num = next((num for num in lst if num % 2 == 0), None)
return [first_even_num] if first_even_num is not None else [] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns a new list containing only the very first even number from the original list. If there are no even numbers, the function should return an empty list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5203,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns a new list containing only the very first even number from the original list. If there are no even numbers, the function should return an empty list.",
"split": "train"
} |
from typing import List
def min_cost_path(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
rows = len(grid)
cols = len(grid[0])
# Initialize the dp array with the first row's cumulative sum
dp = [0] * cols
dp[0] = grid[0][0]
for j in range(1, cols):
d... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nYou are given a navigational map represented as a 2D grid. Each cell in the grid contains a non-negative integer that indicates the cost to enter that cell. Your task is to find the minimum cost path from the top-left corner to the bottom-right corner of the grid. Only move... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5204,
"level": 1,
"question": "### Context\nYou are given a navigational map represented as a 2D grid. Each cell in the grid contains a non-negative integer that indicates the cost to enter that cell. Your task is to find the minimum cost path from the top-left corner to the bottom-... |
def check_all_odd_or_even(lst):
if not lst:
return True
parities = {x % 2 for x in lst}
return len(parities) == 1 | simplelr_Filter | [
{
"content": "Question:\nCan you write a Python function that checks if the elements of a given list are either all odd or all even numbers? The function should take a list of integers as input and return `True` if all numbers are odd or all are even, and `False` otherwise. For example, if the input list is `[2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5205,
"level": 1,
"question": "Can you write a Python function that checks if the elements of a given list are either all odd or all even numbers? The function should take a list of integers as input and return `True` if all numbers are odd or all are even, and `False` otherwise. Fo... |
def min_jumps(arr):
n = len(arr)
if n == 1:
return 0
jumps = 0
current_end = 0
farthest = 0
for i in range(n):
if i > current_end:
return -1
farthest = max(farthest, i + arr[i])
if i == n - 1:
return jumps
if farthest >= n - 1:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` where each element represents the maximum length of rope you can cut from that position. You are initially positioned at the start of the array and you need to reach the last index in the minimum number of jumps. A jump from position `i` to any p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5206,
"level": 1,
"question": "You are given an array of integers `arr` where each element represents the maximum length of rope you can cut from that position. You are initially positioned at the start of the array and you need to reach the last index in the minimum number of jumps... |
def filter_dict_by_value_sublist(d, threshold):
result = {}
for key, value in d.items():
if isinstance(value, list):
filtered = [x for x in value if x > threshold]
result[key] = filtered
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a dictionary and returns a new dictionary with all key-value pairs where the value is a sublist that only contains elements 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": 5207,
"level": 1,
"question": "Create a function that takes a dictionary and returns a new dictionary with all key-value pairs where the value is a sublist that only contains elements that are greater than a given threshold.",
"split": "train"
} |
def is_valid_expression(expression: str) -> bool:
stack = []
mapping = {')': '(', ']': '[', '}': '{'}
for char in expression:
if char in mapping:
if not stack or stack[-1] != mapping[char]:
return False
stack.pop()
else:
stack.append(char)
... | simplelr_Data_Structure | [
{
"content": "Question:\n**Scenario**: \n\nYou are developing a text editor feature that assists programmers by highlighting matching parentheses. A core part of this feature is to validate whether the parentheses, brackets, and braces in a given string are balanced and correctly nested.\n\n**Task**:\n\nWrite a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5208,
"level": 1,
"question": "**Scenario**: \n\nYou are developing a text editor feature that assists programmers by highlighting matching parentheses. A core part of this feature is to validate whether the parentheses, brackets, and braces in a given string are balanced and correc... |
def countOnes(n):
m = n % (1 << 32)
return bin(m).count('1')
| simplelr_Taco | [
{
"content": "Question:\n## Task\n\nCreate a function called `countOnes` that counts the number of `1`s in the binary representation of a given integer.\n\n## Input\n\nAn integer \\( n \\). The function should handle both positive and negative integers.\n\n## Output\n\nThe function should return the number of `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5209,
"level": 1,
"question": "## Task\n\nCreate a function called `countOnes` that counts the number of `1`s in the binary representation of a given integer.\n\n## Input\n\nAn integer \\( n \\). The function should handle both positive and negative integers.\n\n## Output\n\nThe fun... |
from typing import List
def prime_factors(n: int) -> List[int]:
factors = []
# Handle the case of 2 separately
while n % 2 == 0:
factors.append(2)
n = n // 2
# Now n must be odd, so start from 3 and increment by 2
i = 3
while i * i <= n:
while n % i == 0:
fac... | simplelr_Taco | [
{
"content": "Question:\n## Prime Factorization\n\nGiven a positive integer `n`, the task is to find its prime factorization. The prime factorization of an integer is a product of prime numbers that, when multiplied together, yield the original integer `n`.\n\n## Example:\n\nFor example, if the input number is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5210,
"level": 1,
"question": "## Prime Factorization\n\nGiven a positive integer `n`, the task is to find its prime factorization. The prime factorization of an integer is a product of prime numbers that, when multiplied together, yield the original integer `n`.\n\n## Example:\n\nF... |
def repeat_string(A: str, B: str) -> int:
len_A = len(A)
len_B = len(B)
if len_A == 0:
return -1 # As per problem constraints, len(A) >=1, so this is just a safeguard
# Calculate the maximum number of repetitions needed
max_repeats = (len_B // len_A) + 2
s = A * max_repeats #... | simplelr_Data_Structure | [
{
"content": "Question:\n### Repeated Substring Search Implementation\n\nYou are given two strings `A` and `B`. Your task is to find the minimum number of times the string `A` must be repeated such that `B` becomes a substring of the resulted repeated string. If no such repetition is possible, return -1.\n\nImp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5211,
"level": 1,
"question": "### Repeated Substring Search Implementation\n\nYou are given two strings `A` and `B`. Your task is to find the minimum number of times the string `A` must be repeated such that `B` becomes a substring of the resulted repeated string. If no such repeti... |
def convert_to_seconds(hours: int, minutes: int, seconds: int) -> int:
return hours * 3600 + minutes * 60 + seconds
| simplelr_Taco | [
{
"content": "Question:\nA company is planning to organize a marathon event. Each runner will be timed and their results recorded as hours, minutes, and seconds. The event organizers need to calculate the total running time in seconds to evaluate completion times more efficiently.\n\nWrite a function `convert_t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5212,
"level": 1,
"question": "A company is planning to organize a marathon event. Each runner will be timed and their results recorded as hours, minutes, and seconds. The event organizers need to calculate the total running time in seconds to evaluate completion times more efficien... |
def add_squares(a, b):
return a ** 2 + b ** 2 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that adds the squares of two numbers and returns the result.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5213,
"level": 1,
"question": "Create a function that adds the squares of two numbers and returns the result.",
"split": "train"
} |
def gridGame(N, M, Grid):
# Find the maximum value in the grid
max_val = max(max(row) for row in Grid)
# Check if all elements are equal to max_val
all_max = True
for i in range(N):
for j in range(M):
if Grid[i][j] != max_val:
all_max = False
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a grid with N rows and M columns. Each cell of the grid contains a non-negative integer. Two players play a game taking turns. On each turn, a player can choose any cell and increment its value by 1. The game ends when all the cells in the grid contain the same value. The ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5214,
"level": 1,
"question": "You are given a grid with N rows and M columns. Each cell of the grid contains a non-negative integer. Two players play a game taking turns. On each turn, a player can choose any cell and increment its value by 1. The game ends when all the cells in th... |
def sum_of_odd_integers(nums):
return sum(num for num in nums if num % 2 != 0) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list of integers and returns the sum of the list. However, skip over any integers that are even.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5215,
"level": 1,
"question": "Create a function that takes in a list of integers and returns the sum of the list. However, skip over any integers that are even.",
"split": "train"
} |
def can_form_by_repeating_substring(s):
n = len(s)
for d in range(1, n // 2 + 1):
if n % d == 0:
k = n // d
if s == s[:d] * k:
return True
return False | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to determine if a given string can be formed by repeating a substring of it. For example, the string \"abab\" can be formed by repeating the substring \"ab\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5216,
"level": 1,
"question": "Write a python function to determine if a given string can be formed by repeating a substring of it. For example, the string \"abab\" can be formed by repeating the substring \"ab\".",
"split": "train"
} |
def is_palindrome(s):
# Clean the string by converting to lowercase and keeping only alphanumeric characters
cleaned = ''.join([c.lower() for c in s if c.isalnum()])
# Check if the cleaned string is equal to its reverse
return cleaned == cleaned[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to check if a string \"s\" is a palindrome or not. A palindrome is a string that reads the same backward as forward. For example, \"radar\" is a palindrome and \"apple\" is not. Make sure to handle empty strings and avoid any other non-alphanumeric characters fro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5217,
"level": 1,
"question": "Write a python function to check if a string \"s\" is a palindrome or not. A palindrome is a string that reads the same backward as forward. For example, \"radar\" is a palindrome and \"apple\" is not. Make sure to handle empty strings and avoid any ot... |
from collections import deque
from typing import List
def switch_pairs(stack: List[int]) -> List[int]:
dq = deque(stack)
result = []
while len(dq) >= 2:
first = dq.popleft()
second = dq.popleft()
result.append(second)
result.append(first)
if dq:
result.append(dq.... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked to write a function that demonstrates your understanding of stack-based operations and the use of auxiliary structures for manipulating data. Specifically, you need to switch successive pairs of elements in a given stack data structure.\n\n### Task\nImplement a function `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5218,
"level": 1,
"question": "You are tasked to write a function that demonstrates your understanding of stack-based operations and the use of auxiliary structures for manipulating data. Specifically, you need to switch successive pairs of elements in a given stack data structure.\... |
def sprintf(format_string, *args):
return format_string % args | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that mimics the behavior of the `sprintf` function in C, which formats a string according to a specified format and returns the formatted string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5219,
"level": 1,
"question": "How can I create a Python function that mimics the behavior of the `sprintf` function in C, which formats a string according to a specified format and returns the formatted string?",
"split": "train"
} |
def invert_dict(input_dict: dict) -> dict:
inverted = {}
for key, value in input_dict.items():
if value not in inverted:
inverted[value] = key
else:
# If the value is not a list, convert it to a list before appending
if isinstance(inverted[value], list):
... | simplelr_Package | [
{
"content": "Question:\nWrite a Python function named `invert_dict(input_dict: dict) -> dict` that inverts the keys and values of a dictionary. If the input dictionary contains duplicate values, combine the keys into a list. The function should ensure that no information is lost during the inversion process.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5220,
"level": 1,
"question": "Write a Python function named `invert_dict(input_dict: dict) -> dict` that inverts the keys and values of a dictionary. If the input dictionary contains duplicate values, combine the keys into a list. The function should ensure that no information is l... |
def findKthLargest(nums, k):
unique = list(set(nums))
if len(unique) < k:
return -1
sorted_unique = sorted(unique, reverse=True)
return sorted_unique[k - 1]
| simplelr_Taco | [
{
"content": "Question:\nYou are given a list of integers 'nums' where each number represents a score in an exam. Return the k-th largest unique score in the list. If there are fewer than k unique scores, return -1.\n\nExample 1:\nInput:\nnums = [4, 5, 1, 4, 3, 2, 5, 2]\nk = 3\nOutput:\n3\nExplanation:\nThe uni... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5221,
"level": 1,
"question": "You are given a list of integers 'nums' where each number represents a score in an exam. Return the k-th largest unique score in the list. If there are fewer than k unique scores, return -1.\n\nExample 1:\nInput:\nnums = [4, 5, 1, 4, 3, 2, 5, 2]\nk = 3... |
def count_unique_words(s):
words = s.split()
unique_words = set(words)
return len(unique_words) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and returns the number of unique words in the string. Words are defined as sequences of characters separated by whitespace. The function should be case-sensitive, meaning \"Hello\" and \"hello\" should be considered as different words.\nAns... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5222,
"level": 1,
"question": "Create a function that takes a string as input and returns the number of unique words in the string. Words are defined as sequences of characters separated by whitespace. The function should be case-sensitive, meaning \"Hello\" and \"hello\" should be ... |
def filter_and_sort_odds(numbers):
# Extract odds
odds = [num for num in numbers if num % 2 != 0]
# Remove duplicates
unique_odds = []
for num in odds:
if num not in unique_odds:
unique_odds.append(num)
# Sort in descending order using bubble sort
n = len(unique... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes in a list of integers and returns a list containing only the odd numbers from the original. Additionally, the function should sort the resulting list in descending order and remove any duplicates. Implement the solution without using any built-in func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5223,
"level": 1,
"question": "Create a Python function that takes in a list of integers and returns a list containing only the odd numbers from the original. Additionally, the function should sort the resulting list in descending order and remove any duplicates. Implement the solut... |
def is_palindrome(s):
return s == s[::-1] | simplelr_Evol | [
{
"content": "Question:\nWrite a function in Python that determines if a given string is a palindrome. A palindrome is a word that reads the same forwards and backwards.\n\"racecar\"\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5224,
"level": 1,
"question": "Write a function in Python that determines if a given string is a palindrome. A palindrome is a word that reads the same forwards and backwards.\n\"racecar\"",
"split": "train"
} |
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
# Test the function with n = 50
n = 50
result = fibonacci(n)
print(f"The {n}th Fibonacci number is: {result}") | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to generate the nth Fibonacci number using recursion. Ensure your function is optimized to handle larger values of n efficiently. Additionally, implement a memoization technique to improve performance. Test your function with n = 50 and explain the output.\nAnswe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5225,
"level": 1,
"question": "Write a Python function to generate the nth Fibonacci number using recursion. Ensure your function is optimized to handle larger values of n efficiently. Additionally, implement a memoization technique to improve performance. Test your function with n ... |
def generate_pascal_triangle(n):
triangle = [[1 for _ in range(i+1)] for i in range(n)]
for i in range(2, n):
for j in range(1, i):
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]
return triangle | simplelr_Filter | [
{
"content": "Question:\n### Pascal's Triangle\nPascal's triangle is a triangular array of the binomial coefficients. The numbers in Pascal's triangle can be determined by summing up the two numbers above it.\n\nHere is an example of Pascal's triangle where `n` (the number of rows) is `5`:\n```\n 1\n 1 1\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5226,
"level": 1,
"question": "### Pascal's Triangle\nPascal's triangle is a triangular array of the binomial coefficients. The numbers in Pascal's triangle can be determined by summing up the two numbers above it.\n\nHere is an example of Pascal's triangle where `n` (the number of ... |
def remove_small_strings(string_list, n):
return [s for s in string_list if len(s) > n]
| simplelr_Taco | [
{
"content": "Question:\nCreate a function called `remove_small_strings` that takes a list of strings `string_list` and an integer `n` as input and returns a new list containing only the strings from the original list that have a length greater than `n`. Examples are shown below:\n\n```\nremove_small_strings([\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5227,
"level": 1,
"question": "Create a function called `remove_small_strings` that takes a list of strings `string_list` and an integer `n` as input and returns a new list containing only the strings from the original list that have a length greater than `n`. Examples are shown bel... |
def convert_zigzag(s, num_rows):
if num_rows == 1:
return s
rows = [[] for _ in range(num_rows)]
current_row = 0
direction = 1 # 1 for down, -1 for up
for c in s:
rows[current_row].append(c)
if current_row == 0:
direction = 1
elif current_row == num_rows ... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Zigzag Conversion\n\n#### Context\nThe zigzag conversion is a process used to rearrange characters of a string in a zigzag pattern on a number of rows. After writing out the rows, the characters are read from left to right to get the final converted string.\n\n#### Task\nY... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5228,
"level": 1,
"question": "### Question: Zigzag Conversion\n\n#### Context\nThe zigzag conversion is a process used to rearrange characters of a string in a zigzag pattern on a number of rows. After writing out the rows, the characters are read from left to right to get the fina... |
import bisect
def longest_increasing_subsequence(nums):
tails = []
for num in nums:
idx = bisect.bisect_left(tails, num)
if idx == len(tails):
tails.append(num)
else:
tails[idx] = num
return len(tails)
# Example usage:
if __name__ == "__main__":
nums = [... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code example that demonstrates how to find the longest increasing subsequence in a list of integers?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5229,
"level": 1,
"question": "Can you provide a Python code example that demonstrates how to find the longest increasing subsequence in a list of integers?",
"split": "train"
} |
def sort_list(nums):
return sorted(nums) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list of integers and returns a new list that is a sorted version of the input list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5230,
"level": 1,
"question": "Create a function that takes in a list of integers and returns a new list that is a sorted version of the input list.",
"split": "train"
} |
def sort_array_and_find_median(array):
# Convert the Py4J array to a Python list
py_list = [x for x in array]
# Sort the list in ascending order
sorted_list = sorted(py_list)
n = len(sorted_list)
# Calculate the median
if n % 2 == 1:
median = sorted_list[n // 2]
else:
med... | simplelr_Filter | [
{
"content": "Question:\nPlease sort a py4j array using the smallest term first criteria. Then, create a function that also finds the median of the sorted array. Note that the median is the middle number in a sorted, ascending or descending, list of numbers. If there is an even number of observations, the media... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5231,
"level": 1,
"question": "Please sort a py4j array using the smallest term first criteria. Then, create a function that also finds the median of the sorted array. Note that the median is the middle number in a sorted, ascending or descending, list of numbers. If there is an eve... |
from collections import Counter
def is_permutation(list1, list2):
if len(list1) != len(list2):
return False
return Counter(list1) == Counter(list2) | simplelr_Filter | [
{
"content": "Question:\nCreate a function `is_permutation` which takes two integer lists as input and determines whether the first list is a permutation of the second list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5232,
"level": 1,
"question": "Create a function `is_permutation` which takes two integer lists as input and determines whether the first list is a permutation of the second list.",
"split": "train"
} |
import pandas as pd
import matplotlib.pyplot as plt
def analyze_employee_data(file_path: str) -> None:
# Load the dataset
df = pd.read_csv(file_path)
# Clean the data by removing rows with any null or missing values
df = df.dropna(how='any')
# Calculate average salary by department
av... | simplelr_Package | [
{
"content": "Question:\nYou are given a dataset containing information about various employees in a company. Your task is to analyze the dataset using Python and create a function, `analyze_employee_data`, that will:\n\n1. Load the dataset from a CSV file.\n2. Perform data cleaning by removing rows where any c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5233,
"level": 1,
"question": "You are given a dataset containing information about various employees in a company. Your task is to analyze the dataset using Python and create a function, `analyze_employee_data`, that will:\n\n1. Load the dataset from a CSV file.\n2. Perform data cl... |
from collections import defaultdict
def smallestRepeatedElement(arr):
freq = defaultdict(int)
for num in arr:
freq[num] += 1
min_repeated = float('inf')
for num in arr:
if freq[num] > 1 and num < min_repeated:
min_repeated = num
return min_repeated if min_repeated != flo... | simplelr_Taco | [
{
"content": "Question:\nYou are given an array `arr` of positive integers. Your task is to find the smallest element in the array that is repeated more than once.\n\nPrint the smallest repeated element or \"NO\" if there is no repeated element.\n \nExample 1:\nInput: arr = [4, 3, 2, 7, 8, 2, 3, 1]\nOutput: 2\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5234,
"level": 1,
"question": "You are given an array `arr` of positive integers. Your task is to find the smallest element in the array that is repeated more than once.\n\nPrint the smallest repeated element or \"NO\" if there is no repeated element.\n \nExample 1:\nInput: arr = [4... |
def count_cells_with_greater_neighbors(matrix):
if not matrix or not matrix[0]:
return 0
m = len(matrix)
n = len(matrix[0])
count = 0
directions = [(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1)]
for i in range(m):
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a 2D integer matrix `matrix` of size `m x n`. Your task is to count the number of cells that have at least one neighboring cell with a greater value than the current cell. Two cells are considered neighboring if they are adjacent horizontally, vertically, or diagonally. Im... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5235,
"level": 1,
"question": "You are given a 2D integer matrix `matrix` of size `m x n`. Your task is to count the number of cells that have at least one neighboring cell with a greater value than the current cell. Two cells are considered neighboring if they are adjacent horizont... |
def reverse_string(text):
"""
This function takes a string and returns the reversed string.
For example:
reverse_string("hello") == "olleh"
reverse_string("Python") == "nohtyP"
"""
return text[::-1] | simplelr_Filter | [
{
"content": "Question:\nThis is the code:\n```python\ndef reverse_string(text):\n \"\"\"\n This function takes a string and returns the reversed string.\n\n For example:\n\n reverse_string(\"hello\") == \"olleh\"\n reverse_string(\"Python\") == \"nohtyP\"\n \"\"\"\n return text[::-1]\nAnswer:\nLet's thi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5236,
"level": 1,
"question": "This is the code:\n```python\ndef reverse_string(text):\n \"\"\"\n This function takes a string and returns the reversed string.\n\n For example:\n\n reverse_string(\"hello\") == \"olleh\"\n reverse_string(\"Python\") == \"nohtyP\"\n \"\"\"\n re... |
def find_disappeared_numbers(nums):
n = len(nums)
for i in range(n):
num = nums[i]
x = abs(num)
if 1 <= x <= n:
nums[x - 1] = -abs(nums[x - 1])
missing = []
for i in range(n):
if nums[i] > 0:
missing.append(i + 1)
return missing | simplelr_Apps | [
{
"content": "Question:\nYou are given an array of integers where some elements appear twice and others appear once. Each element in the array is within the range `[1, n]` inclusive, where `n` is the length of the array. Write a function to find all the integers between 1 and `n` that do not appear in the array... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5237,
"level": 1,
"question": "You are given an array of integers where some elements appear twice and others appear once. Each element in the array is within the range `[1, n]` inclusive, where `n` is the length of the array. Write a function to find all the integers between 1 and ... |
import math
def prime_sequence_generator(n: int) -> list:
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, i... | simplelr_Algorithm | [
{
"content": "Question:\n## New Question for Coding Assessment\n\n### [Question 2]: Prime Number Sequence Generator\n\n**Problem Statement:**\n\nWrite a function `prime_sequence_generator` that generates a sequence of prime numbers up to a given limit `n`. The function should return a list of prime numbers in a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5238,
"level": 1,
"question": "## New Question for Coding Assessment\n\n### [Question 2]: Prime Number Sequence Generator\n\n**Problem Statement:**\n\nWrite a function `prime_sequence_generator` that generates a sequence of prime numbers up to a given limit `n`. The function should ... |
def is_even(num: int) -> bool:
return num % 2 == 0 | simplelr_Filter | [
{
"content": "Question:\nIn the Python programming language, how do you define a function that takes an integer as an input and returns True if the integer is even, and False otherwise?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5239,
"level": 1,
"question": "In the Python programming language, how do you define a function that takes an integer as an input and returns True if the integer is even, and False otherwise?",
"split": "train"
} |
def two_sum(nums: list[int], target: int) -> bool:
seen = set()
for num in nums:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given a list of integers `nums` and a target integer `target`. Your task is to determine if there are two distinct indices `i` and `j` in the list such that `nums[i] + nums[j] == target`.\n\n### Function Signature\n```python\ndef two_sum(nums: list[int],... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5240,
"level": 1,
"question": "### Problem Statement\n\nYou are given a list of integers `nums` and a target integer `target`. Your task is to determine if there are two distinct indices `i` and `j` in the list such that `nums[i] + nums[j] == target`.\n\n### Function Signature\n```p... |
def transpose_dict(input_dict):
""" Transposes the input dictionary of lists """
if not input_dict:
return {}
# Check if all lists have the same length
lengths = [len(v) for v in input_dict.values()]
if len(set(lengths)) != 1:
raise ValueError("All lists must be of the same leng... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with implementing a function `transpose_dict` in Python that transposes the structure of a given dictionary of lists. The transposition of a dictionary means converting its keys into indices and its values (lists) into values of new keys. The function will take a single a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5241,
"level": 1,
"question": "You are tasked with implementing a function `transpose_dict` in Python that transposes the structure of a given dictionary of lists. The transposition of a dictionary means converting its keys into indices and its values (lists) into values of new keys... |
from typing import List, Tuple
def rpsls_tournament(players: List[str], games: List[Tuple[str, str, str, str]]) -> str:
beats = {
'Rock': ['Scissors', 'Lizard'],
'Paper': ['Rock', 'Spock'],
'Scissors': ['Paper', 'Lizard'],
'Lizard': ['Spock', 'Paper'],
'Spock': ['Scissors', ... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge: Rock-Paper-Scissors Lizard-Spock Tournament\n\n#### Background:\nRock-Paper-Scissors is a classic hand game. There exists an extended version called Rock-Paper-Scissors-Lizard-Spock popularized by the TV show \"The Big Bang Theory\". The rules are:\n- Scissors cuts... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5242,
"level": 1,
"question": "### Coding Challenge: Rock-Paper-Scissors Lizard-Spock Tournament\n\n#### Background:\nRock-Paper-Scissors is a classic hand game. There exists an extended version called Rock-Paper-Scissors-Lizard-Spock popularized by the TV show \"The Big Bang Theory... |
def reverse_even_numbers(input_list):
even_numbers = []
for num in input_list:
if type(num) is not int:
raise ValueError("Input list contains non-integer values.")
if num % 2 == 0:
even_numbers.append(num)
return even_numbers[::-1]
# Example usage:
# Test case 1: Mix... | simplelr_Evol | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a new list containing only the even numbers from the original list, but in reverse order. You should handle cases where the list might be empty, contain all odd numbers, or have a mix of even and odd numbers. Make sure to inclu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5243,
"level": 1,
"question": "Create a function that takes a list of integers and returns a new list containing only the even numbers from the original list, but in reverse order. You should handle cases where the list might be empty, contain all odd numbers, or have a mix of even ... |
def concat_numbers_and_string(a, b, s):
return str(a) + s + str(b) | simplelr_Filter | [
{
"content": "Question:\nWrite a function that takes two numbers and a string as parameters and returns a concatenation of the first number's representation, the string, and the second number's representation.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5244,
"level": 1,
"question": "Write a function that takes two numbers and a string as parameters and returns a concatenation of the first number's representation, the string, and the second number's representation.",
"split": "train"
} |
def word_break(s, word_dict):
word_set = set(word_dict)
dp = [False] * (len(s) + 1)
dp[0] = True # empty string is segmentable
for i in range(1, len(s) + 1):
for j in range(i):
if dp[j] and s[j:i] in word_set:
dp[i] = True
break # no need to che... | simplelr_Package | [
{
"content": "Question:\n### String Segmentation with Dictionary Words\n\nIn natural language processing, the problem of segmenting a string into meaningful words is quite common. Given a string without spaces and a dictionary of valid words, the goal is to determine if the string can be segmented into a sequen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5245,
"level": 1,
"question": "### String Segmentation with Dictionary Words\n\nIn natural language processing, the problem of segmenting a string into meaningful words is quite common. Given a string without spaces and a dictionary of valid words, the goal is to determine if the st... |
from typing import List
def rotate_matrix(matrix: List[List[int]]) -> None:
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse() | simplelr_Data_Structure | [
{
"content": "Question:\n### Matrix Rotation Challenge\n\nGiven an n x n 2D matrix 'matrix', rotate the matrix 90 degrees clockwise in-place. Your implementation must modify the input matrix directly without using extra space for another matrix.\n\n#### Input Format\n- A 2D list `matrix` of dimensions \\( n \\t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5246,
"level": 1,
"question": "### Matrix Rotation Challenge\n\nGiven an n x n 2D matrix 'matrix', rotate the matrix 90 degrees clockwise in-place. Your implementation must modify the input matrix directly without using extra space for another matrix.\n\n#### Input Format\n- A 2D li... |
import numpy as np
def batch_gradient(X):
"""
Compute the gradients of the function F(x, y, z) = x^2 + y^2 + z^2 for a batch of input samples.
Parameters:
X (numpy.ndarray): A 2D array where each row is a delta to add to the starting point v.
Returns:
numpy.ndarray: A 2D array where each row ... | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function that avoids using loops. This function, named `batch_gradient`, should compute the gradients for a batch of input samples based on the provided format, leveraging NumPy for efficient computation. Consider having a starting point defined by `v = np.array([2.1, 3.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5247,
"level": 1,
"question": "Design a Python function that avoids using loops. This function, named `batch_gradient`, should compute the gradients for a batch of input samples based on the provided format, leveraging NumPy for efficient computation. Consider having a starting poin... |
def longest_prefix_lengths(text, words):
# Build the trie
trie = {}
current = trie
for char in text:
if char not in current:
current[char] = {}
current = current[char]
result = []
for word in words:
current_node = trie
count = 0
for char i... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `text` and an array of words `words`. A **prefix** of a string is any leading contiguous substring of that string. For example, the prefixes of the string `\"abcdef\"` are `\"a\"`, `\"ab\"`, `\"abc\"`, `\"abcd\"`, `\"abcde\"`, and `\"abcdef\"`. \n\nFor each word i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5248,
"level": 1,
"question": "You are given a string `text` and an array of words `words`. A **prefix** of a string is any leading contiguous substring of that string. For example, the prefixes of the string `\"abcdef\"` are `\"a\"`, `\"ab\"`, `\"abc\"`, `\"abcd\"`, `\"abcde\"`, an... |
def productExceptSelf(nums):
n = len(nums)
if n == 0:
return []
res = [1] * n
# Compute left products
for i in range(1, n):
res[i] = res[i-1] * nums[i-1]
# Compute right products and multiply with left
right = 1
for i in range(n-1, -1, -1):
res[i] *... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes an array of integers and returns a new array where each element is the product of all the elements in the original array except for the one at the same index. You should solve it without using division.\n\nExample: `[1, 2, 3, 4]` should return `[24, 12, 8, 6]... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5249,
"level": 1,
"question": "Write a function that takes an array of integers and returns a new array where each element is the product of all the elements in the original array except for the one at the same index. You should solve it without using division.\n\nExample: `[1, 2, 3... |
def enhanced_caesar_cipher(s: str, k: int) -> str:
effective_k = k % 26
result = []
for c in s:
if c.isalpha():
if c.isupper():
base = ord('A')
else:
base = ord('a')
offset = ord(c) - base
shifted = (offset + effective_k... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with implementing an enhanced version of the Caesar Cipher. Assume that you are working with an advanced encryption system which requires not just letter shifts but also incorporates non-alphabetic characters handling for encryption, ensuring they remain unchanged.\n\n###... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5250,
"level": 1,
"question": "You are tasked with implementing an enhanced version of the Caesar Cipher. Assume that you are working with an advanced encryption system which requires not just letter shifts but also incorporates non-alphabetic characters handling for encryption, ens... |
def initialize_3d_array(x, y, z):
return [[[0 for _ in range(z)] for _ in range(y)] for _ in range(x)] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to initialize and fill a 3D array with zeros. The dimensions of the 3D array should be specified as arguments to the function. The function should return the initialized 3D array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5251,
"level": 1,
"question": "Write a python function to initialize and fill a 3D array with zeros. The dimensions of the 3D array should be specified as arguments to the function. The function should return the initialized 3D array.",
"split": "train"
} |
from collections import Counter
def most_frequent_integers(lst):
counts = Counter(lst)
if not counts:
return []
max_count = max(counts.values())
result = [k for k, v in counts.items() if v == max_count]
return result if len(result) > 1 else result[0] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers as an argument and returns the most frequently occurring integer in the list. If there is more than one integer occurring most frequently, return all of them in a list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5252,
"level": 1,
"question": "Create a function that takes a list of integers as an argument and returns the most frequently occurring integer in the list. If there is more than one integer occurring most frequently, return all of them in a list.",
"split": "train"
} |
def count_vowels(s):
count = 0
vowels = {'a', 'e', 'i', 'o', 'u'}
for char in s:
if char in vowels:
count += 1
return count | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts a string value and returns the number of vowels in it, but it should only consider lowercase English alphabets.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5253,
"level": 1,
"question": "Create a function that accepts a string value and returns the number of vowels in it, but it should only consider lowercase English alphabets.",
"split": "train"
} |
def matrix_diagonal_difference(matrix):
n = len(matrix)
main_sum = 0
secondary_sum = 0
for i in range(n):
main_sum += matrix[i][i]
secondary_sum += matrix[i][n - 1 - i]
return abs(main_sum - secondary_sum) | simplelr_Evol | [
{
"content": "Question:\nWrite a function `matrix_diagonal_difference` that:\n\n1. Takes a 2D list `matrix` representing an NxN matrix (a square matrix).\n2. Computes the difference between the sums of the matrix's two diagonals (the main diagonal and the secondary diagonal).\n3. Returns this absolute differenc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5254,
"level": 1,
"question": "Write a function `matrix_diagonal_difference` that:\n\n1. Takes a 2D list `matrix` representing an NxN matrix (a square matrix).\n2. Computes the difference between the sums of the matrix's two diagonals (the main diagonal and the secondary diagonal).\... |
def fibonacci(n):
if n == 0:
return []
elif n == 1:
return [0]
else:
fib_sequence = [0, 1]
for i in range(2, n):
next_term = fib_sequence[i-1] + fib_sequence[i-2]
fib_sequence.append(next_term)
return fib_sequence
# Example usage:
n = 5
print(... | simplelr_Filter | [
{
"content": "Question:\nI need to calculate the Fibonacci sequence up to the nth term using a loop in Python. Can you provide a simple example?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5255,
"level": 1,
"question": "I need to calculate the Fibonacci sequence up to the nth term using a loop in Python. Can you provide a simple example?",
"split": "train"
} |
def seasonal_calendar():
calendar = {}
seasons = [
('Spring', ['March', 'April', 'May']),
('Summer', ['June', 'July', 'August']),
('Autumn', ['September', 'October', 'November']),
('Winter', ['December', 'January', 'February'])
]
for season, months in seasons:
for... | simplelr_Filter | [
{
"content": "Question:\nYou've been given a task to create a function `seasonal_calendar` that takes no arguments and returns a dictionary where the keys are the names of the months and the values are the corresponding seasons. \n\nThe months and their corresponding seasons in the Northern Hemisphere are:\n- S... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5256,
"level": 1,
"question": "You've been given a task to create a function `seasonal_calendar` that takes no arguments and returns a dictionary where the keys are the names of the months and the values are the corresponding seasons. \n\nThe months and their corresponding seasons i... |
def extract_last_part_of_text(text, separator):
parts = text.split(separator)
return parts[-1]
text_to_parse = "first(client)name,Second(last)Name"
separator = ')'
print(extract_last_part_of_text(text_to_parse, separator)) # Output: 'Name' | simplelr_Filter | [
{
"content": "Question:\ndef extract_last_part_of_text(text, separator):\n parts = text.split(separator)\n return parts[-1]\n\n\ntext_to_parse = \"first(client)name,Second(last)Name\"\nseparator = ')'\nprint(extract_last_part_of_text(text_to_parse, separator))\nAnswer:\nLet's think step by step.\n",
"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5257,
"level": 1,
"question": "def extract_last_part_of_text(text, separator):\n parts = text.split(separator)\n return parts[-1]\n\n\ntext_to_parse = \"first(client)name,Second(last)Name\"\nseparator = ')'\nprint(extract_last_part_of_text(text_to_parse, separator))",
"split... |
def four_sum(arr, target):
arr.sort()
result = []
n = len(arr)
for i in range(n - 3):
if i > 0 and arr[i] == arr[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and arr[j] == arr[j - 1]:
continue
left = j + 1
rig... | simplelr_Filter | [
{
"content": "Question:\nYou’re given an array of integers and a target sum. Your task is to write a program to find all unique quadruplets in the array which add up to the target sum.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5258,
"level": 1,
"question": "You’re given an array of integers and a target sum. Your task is to write a program to find all unique quadruplets in the array which add up to the target sum.",
"split": "train"
} |
def max_product_of_three(nums):
if len(nums) < 3:
raise ValueError("The array must contain at least three elements.")
max1 = max2 = max3 = float('-inf')
min1 = min2 = float('inf')
for num in nums:
# Update the three largest numbers
if num > max1:
max3 = max2... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum product of three numbers in an array. The array may contain both positive and negative numbers. Your function should have a time complexity of O(n).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5259,
"level": 1,
"question": "Write a python function to find the maximum product of three numbers in an array. The array may contain both positive and negative numbers. Your function should have a time complexity of O(n).",
"split": "train"
} |
def stutter_stack(stack: list) -> list:
result = []
for num in stack:
result.append(num)
result.append(num)
return result | simplelr_Data_Structure | [
{
"content": "Question:\n### Stuttering Stack Elements\n\nYou are given a stack that contains integers. Your task is to write a function `stutter_stack` that replaces every value in the stack with two occurrences of that value.\n\nThe function should operate in the following way:\n* For a given stack, it should... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5260,
"level": 1,
"question": "### Stuttering Stack Elements\n\nYou are given a stack that contains integers. Your task is to write a function `stutter_stack` that replaces every value in the stack with two occurrences of that value.\n\nThe function should operate in the following w... |
def is_valid_serialization(preorder: str) -> bool:
tokens = preorder.split(',')
if not tokens:
return True
available = 1
for token in tokens:
if available <= 0:
return False
if token != '#':
available += 1
else:
available -= 1
retur... | simplelr_Evol | [
{
"content": "Question:\nConsider a function that checks if a string is a valid serialized binary tree preorder traversal. The serial format is defined in such a way that a single letter represents a node and a '#' character represents a null node. Each non-null node can have two children. \n\nWrite a function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5261,
"level": 1,
"question": "Consider a function that checks if a string is a valid serialized binary tree preorder traversal. The serial format is defined in such a way that a single letter represents a node and a '#' character represents a null node. Each non-null node can have ... |
def multiply(multiplicand: list[list[int]], multiplier: list[list[int]]) -> list[list[int]]:
# Check if the matrices are compatible for multiplication
if len(multiplicand[0]) != len(multiplier):
raise ValueError("Matrices are not compatible for multiplication.")
# Get the dimensions of the matr... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with implementing a function to multiply two given matrices. The function will verify that the matrices are compatible for multiplication and return the product matrix.\n\n### Function Signature\n```python\ndef multiply(multiplicand: list[list[int]], multiplier: list[list... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5262,
"level": 1,
"question": "You are tasked with implementing a function to multiply two given matrices. The function will verify that the matrices are compatible for multiplication and return the product matrix.\n\n### Function Signature\n```python\ndef multiply(multiplicand: lis... |
def max_non_adjacent_sum(arr):
if not arr:
return 0
prev_prev = 0
prev = max(arr[0], 0)
for i in range(1, len(arr)):
current = max(prev, prev_prev + arr[i])
prev_prev, prev = prev, current
return prev | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the maximum possible sum of elements in a subarray such that no two elements in the subarray are adjacent. Given an array of non-negative integers, this function should return the maximum sum. For example, if the array is [1, 2, 3, 4], the function should r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5263,
"level": 1,
"question": "Write a function to calculate the maximum possible sum of elements in a subarray such that no two elements in the subarray are adjacent. Given an array of non-negative integers, this function should return the maximum sum. For example, if the array is ... |
def replace_substrings(s, mapping):
modified = s
for key in sorted(mapping.keys(), key=lambda x: -len(x)):
modified = modified.replace(key, mapping[key])
return modified | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to replace substrings in a string based on a dictionary mapping. You can assume that the dictionary keys are the substrings to be replaced, and the dictionary values are the substrings to replace them with.\nAnswer:\nLet's think step by step.\n",
"role": "use... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5264,
"level": 1,
"question": "Write a python function to replace substrings in a string based on a dictionary mapping. You can assume that the dictionary keys are the substrings to be replaced, and the dictionary values are the substrings to replace them with.",
"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]
suffix = [1] * n
for i in range(n-2, -1, -1):
suffix[i] = suffix[i+1] * nums[i+1]
result = []
for i in range(n):
result.append(prefix[i] * suffix[i])
... | simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, write a function that will return the list where each integer is replaced with the product of every integer in the original list except for the integer at that index. You should not use division in your solution.\n\n## Examples\n\nFor example, given the input l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5265,
"level": 1,
"question": "Given a list of integers, write a function that will return the list where each integer is replaced with the product of every integer in the original list except for the integer at that index. You should not use division in your solution.\n\n## Example... |
def is_sorted(nums):
if len(nums) <= 1:
return True
is_ascending = True
is_descending = True
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
is_ascending = False
if nums[i] < nums[i + 1]:
is_descending = False
return is_ascending or is_descend... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function that checks if a list of numbers is sorted in either ascending or descending order?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5266,
"level": 1,
"question": "Can you provide a Python function that checks if a list of numbers is sorted in either ascending or descending order?",
"split": "train"
} |
def count_adjacent_pairs(heights):
count = 0
for i in range(len(heights) - 1):
if heights[i] != heights[i + 1]:
count += 1
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `heights` representing the heights of people standing in a queue. Each position in the queue is denoted by an index of the array. Two people can see each other if they are placed in adjacent positions and one of them is taller than the other. Calculate the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5267,
"level": 1,
"question": "You are given an integer array `heights` representing the heights of people standing in a queue. Each position in the queue is denoted by an index of the array. Two people can see each other if they are placed in adjacent positions and one of them is t... |
def substring_frequency(text: str, length: int) -> dict[str, int]:
if length <= 0 or len(text) < length:
return {}
freq = {}
max_end = len(text) - length
for i in range(max_end + 1):
current_sub = text[i:i+length]
if current_sub in freq:
freq[current_sub] += 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Substring Frequency Analyzer\nYou need to create a program that finds all unique substrings of a given length within a string and counts their frequencies. This will help in text analysis by identifying the repeated patterns within the text.\n\nYour function should account for:\n- T... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5268,
"level": 1,
"question": "### Substring Frequency Analyzer\nYou need to create a program that finds all unique substrings of a given length within a string and counts their frequencies. This will help in text analysis by identifying the repeated patterns within the text.\n\nYou... |
from collections import Counter
def frequency_sort(lst):
counts = Counter(lst)
sorted_list = sorted(counts.items(), key=lambda x: (-x[1], x[0]))
return sorted_list | simplelr_Evol | [
{
"content": "Question:\nCreate a Python function that takes a list of integers and returns a list of tuples, where each tuple contains an integer from the list and its frequency in the list, sorted in descending order by frequency. If two integers have the same frequency, they should be sorted in ascending ord... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5269,
"level": 1,
"question": "Create a Python function that takes a list of integers and returns a list of tuples, where each tuple contains an integer from the list and its frequency in the list, sorted in descending order by frequency. If two integers have the same frequency, the... |
from collections import deque
def longest_subarray(nums, limit):
if not nums:
return 0
max_deque = deque()
min_deque = deque()
max_len = 0
left = 0
for right in range(len(nums)):
# Update max_deque: keep elements in decreasing order
while max_deque and nums[rig... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums`, you need to find the **length of the longest subarray** where the absolute difference between any two elements is less than or equal to `limit`. Return _the length of the longest such subarray_. If there is no such subarray, return `0`. For example, given ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5270,
"level": 1,
"question": "Given an integer array `nums`, you need to find the **length of the longest subarray** where the absolute difference between any two elements is less than or equal to `limit`. Return _the length of the longest such subarray_. If there is no such subarr... |
def int_partition(n: int) -> int:
dp = [0] * (n + 1)
dp[0] = 1 # Base case: one way to make sum 0 (using no elements)
for k in range(1, n + 1):
for j in range(k, n + 1):
dp[j] += dp[j - k]
return dp[n] | simplelr_Data_Structure | [
{
"content": "Question:\n### Integer Partitioning\n\nYou have been tasked to determine the number of ways an integer `n` can be partitioned into sums of smaller positive integers. This process of breakdown is known as integer partitioning. Implement the dynamic programming algorithm to compute the number of suc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5271,
"level": 1,
"question": "### Integer Partitioning\n\nYou have been tasked to determine the number of ways an integer `n` can be partitioned into sums of smaller positive integers. This process of breakdown is known as integer partitioning. Implement the dynamic programming alg... |
def shift_characters(s):
result = ""
for char in s:
result += chr(ord(char) + 1)
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to replace every character in a string with the next character in the ASCII table.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5272,
"level": 1,
"question": "Write a python function to replace every character in a string with the next character in the ASCII table.",
"split": "train"
} |
def max_len_subarray_zero_sum(nums):
prefix_sum_dict = {0: -1}
current_sum = 0
max_length = 0
for i, num in enumerate(nums):
current_sum += num
if current_sum in prefix_sum_dict:
length = i - prefix_sum_dict[current_sum]
if length > max_length:
max... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums`, return the **maximum length** of a subarray that sums to `0`. * The subarray can be from any continuous set of indices within the array. For example, given `nums = [1, -1, 3, 2, -2, -3, 3, 1]`, the longest subarray with sum `0` is `[1, -1, 3, 2, -2, -3... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5273,
"level": 1,
"question": "Given an integer array `nums`, return the **maximum length** of a subarray that sums to `0`. * The subarray can be from any continuous set of indices within the array. For example, given `nums = [1, -1, 3, 2, -2, -3, 3, 1]`, the longest subarray wi... |
def find_added_letter(s: str, t: str) -> str:
sum_s = sum(ord(c) for c in s)
sum_t = sum(ord(c) for c in t)
return chr(sum_t - sum_s) | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nYou are tasked with verifying the integrity of a transmitted string. The initial string `s` is transformed by adding one random character to it, resulting in a new string `t`. Your objective is to identify this newly added character.\n\n#### Problem Statement\nGiven two s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5274,
"level": 1,
"question": "#### Scenario\nYou are tasked with verifying the integrity of a transmitted string. The initial string `s` is transformed by adding one random character to it, resulting in a new string `t`. Your objective is to identify this newly added character.\n\n... |
from typing import List
def rotate_matrix_90(matrix: List[List[int]]) -> List[List[int]]:
rows = len(matrix)
if rows == 0:
return []
cols = len(matrix[0])
new_matrix = []
for j in range(cols):
new_row = []
for i in range(rows - 1, -1, -1):
new_row.append(mat... | simplelr_Package | [
{
"content": "Question:\nYou are required to implement a function named `rotate_matrix_90` that takes a 2D list (matrix) as an input and returns a new matrix that is rotated 90 degrees clockwise. Do not use built-in functions for rotating or transposing the matrix; instead, manually compute the transformation.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5275,
"level": 1,
"question": "You are required to implement a function named `rotate_matrix_90` that takes a 2D list (matrix) as an input and returns a new matrix that is rotated 90 degrees clockwise. Do not use built-in functions for rotating or transposing the matrix; instead, ma... |
def replace_zero_with_next_nonzero(nums):
new_list = list(nums)
next_non_zero = None
for i in range(len(new_list) - 1, -1, -1):
if new_list[i] == 0:
if next_non_zero is not None:
new_list[i] = next_non_zero
else:
next_non_zero = new_list[i]
return ... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer list of numbers and returns a list of stored numbers where zero has been replaced with the next non-zero number from the list. If there is no non-zero number after a zero, then the zero should remain zero.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5276,
"level": 1,
"question": "Create a function that takes an integer list of numbers and returns a list of stored numbers where zero has been replaced with the next non-zero number from the list. If there is no non-zero number after a zero, then the zero should remain zero.",
"s... |
from collections import Counter
def find_unique_elements(list_of_lists):
# Flatten the list of lists into a single list of elements
flat_list = [element for sublist in list_of_lists for element in sublist]
# Count the occurrences of each element
element_counts = Counter(flat_list)
# Collect element... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that finds the unique elements in the elements of a list of lists. In other words, write a function that takes a list of lists as an input and returns a list containing only those elements that appear exactly once in the entire list of lists. Your solution should inclu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5277,
"level": 1,
"question": "Create a function that finds the unique elements in the elements of a list of lists. In other words, write a function that takes a list of lists as an input and returns a list containing only those elements that appear exactly once in the entire list o... |
def sort_list(nums):
return sorted(nums) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns the list sorted in ascending order. The function should handle duplicates and sort them correctly.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5278,
"level": 1,
"question": "Create a function that takes a list of integers and returns the list sorted in ascending order. The function should handle duplicates and sort them correctly.",
"split": "train"
} |
from typing import List
def min_travel_time(grid: List[List[int]]) -> int:
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = grid[0][0]
# Fill the first row
for j in range(1, n):
dp[0][j] = dp[0][j-1] + grid[0][j]
# ... | simplelr_Taco | [
{
"content": "Question:\nA secret agent is stuck in a trapped building consisting of a grid of rooms, each represented as an integer in a 2D array. The integer values in the array represent the time in seconds required to bypass the security mechanism in that room. The agent starts at the top-left corner of the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5279,
"level": 1,
"question": "A secret agent is stuck in a trapped building consisting of a grid of rooms, each represented as an integer in a 2D array. The integer values in the array represent the time in seconds required to bypass the security mechanism in that room. The agent s... |
def threshold_indices(nums, threshold):
product = 1
result = []
for i in range(len(nums)):
product *= nums[i]
if product <= threshold:
result.append(i)
return result | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `nums` and an integer `threshold`. A **threshold index** is an index `i` of `nums` for which the product of all elements from `nums[0]` to `nums[i]` (inclusive) is less than or equal to `threshold`. Return _a list of all threshold indices sort... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5280,
"level": 1,
"question": "You are given a **0-indexed** integer array `nums` and an integer `threshold`. A **threshold index** is an index `i` of `nums` for which the product of all elements from `nums[0]` to `nums[i]` (inclusive) is less than or equal to `threshold`. Return _a... |
from typing import List, Tuple
def min_laptops(intervals: List[Tuple[int, int]]) -> int:
events = []
for start, end in intervals:
events.append((start, 1))
events.append((end, -1))
# Sort the events by time, and for the same time, end events (-1) come before start events (1)
events... | simplelr_Code_Contests | [
{
"content": "Question:\nYou are given a list of n time intervals `(start[i], end[i])` representing the times a person starts and finishes using a laptop. Each interval is closed, meaning the person starts using the laptop at `start[i]` and stops at `end[i]`. You are to determine the minimum number of laptops r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5281,
"level": 1,
"question": "You are given a list of n time intervals `(start[i], end[i])` representing the times a person starts and finishes using a laptop. Each interval is closed, meaning the person starts using the laptop at `start[i]` and stops at `end[i]`. You are to determ... |
import heapq
from collections import Counter
def reorganize_string(s):
count = Counter(s)
max_freq = max(count.values())
n = len(s)
if max_freq > (n + 1) // 2:
return ""
heap = [(-freq, char) for char, freq in count.items()]
heapq.heapify(heap)
result = []
wh... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a string s consisting of lowercase English letters. Your task is to reorder the string in such a way that no two adjacent characters are the same. If such a reordering is possible, return any valid reordering of s. If it is not possible, return an empty string.\n\n### Inpu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5282,
"level": 1,
"question": "You are given a string s consisting of lowercase English letters. Your task is to reorder the string in such a way that no two adjacent characters are the same. If such a reordering is possible, return any valid reordering of s. If it is not possible, ... |
def min_path_sum(grid):
n = len(grid)
if n == 0:
return 0
dp = [[0 for _ in range(n)] for _ in range(n)]
dp[0][0] = grid[0][0]
# Fill the first row
for j in range(1, n):
dp[0][j] = dp[0][j-1] + grid[0][j]
# Fill the first column
for i in range(1, n):
dp[... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a grid of size `n x n` filled with positive integers, you are allowed to move either right or down from any cell, starting from the top-left corner. Write a function to find the minimum path sum from the top-left corner to the bottom-right corner of the grid. Return the minimum pa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5283,
"level": 1,
"question": "Given a grid of size `n x n` filled with positive integers, you are allowed to move either right or down from any cell, starting from the top-left corner. Write a function to find the minimum path sum from the top-left corner to the bottom-right corner... |
def first_non_repeating_character(s):
# Create a dictionary to store the frequency of each character
frequency = {}
for char in s:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
# Iterate through the string to find the first character wi... | simplelr_Filter | [
{
"content": "Question:\nDesign a program to find the first non-repeating character in a given string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5284,
"level": 1,
"question": "Design a program to find the first non-repeating character in a given string.",
"split": "train"
} |
def sorted_squares(nums):
return sorted([num ** 2 for num in nums]) | simplelr_Filter | [
{
"content": "Question:\ndef sorted_squares(nums):\n return sorted([num ** 2 for num in nums])\n\nsorted_squares([-4, -1, 0, 3, 10])\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5285,
"level": 1,
"question": "def sorted_squares(nums):\n return sorted([num ** 2 for num in nums])\n\nsorted_squares([-4, -1, 0, 3, 10])",
"split": "train"
} |
def compress_sequence(s: str) -> str:
if not s:
return ''
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(f"{current_char}{count}")
current_char = char
... | simplelr_Algorithm | [
{
"content": "Question:\n### Compress Consecutive Characters\n\n#### Objective\nYou will implement a function `compress_sequence` that compresses a sequence of consecutive characters in a string by replacing them with the character followed by the number of consecutive occurrences.\n\n#### Function Signature\n`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5286,
"level": 1,
"question": "### Compress Consecutive Characters\n\n#### Objective\nYou will implement a function `compress_sequence` that compresses a sequence of consecutive characters in a string by replacing them with the character followed by the number of consecutive occurre... |
import pandas as pd
def load_and_aggregate_sales(input_file):
"""
Function to load the sales data from a CSV file and perform aggregation.
Input:
- input_file: path to the input file (CSV format with columns: 'Date', 'Store', 'Item', 'Sales').
Output:
- aggregated_df: pandas DataFrame w... | simplelr_Package | [
{
"content": "Question:\nIn the context of managing large-scale datasets, it is often necessary to perform efficient data aggregation and summarization. This can involve grouping data by specific attributes and applying various aggregation functions to generate insightful summaries. In this problem, you will wr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5287,
"level": 1,
"question": "In the context of managing large-scale datasets, it is often necessary to perform efficient data aggregation and summarization. This can involve grouping data by specific attributes and applying various aggregation functions to generate insightful summ... |
def has_pair_with_sum(nums, k):
seen = set()
for num in nums:
complement = k - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Apps | [
{
"content": "Question:\n# Task\nGiven a list of n integers and an integer k, determine whether there are two distinct indices i and j in the list such that nums[i] + nums[j] equals k. Return true if such indices exist, otherwise return false.\n\n**Example:**\n\nFor `nums = [1, 2, 3, 9]` and `k = 8`, the result... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5288,
"level": 1,
"question": "# Task\nGiven a list of n integers and an integer k, determine whether there are two distinct indices i and j in the list such that nums[i] + nums[j] equals k. Return true if such indices exist, otherwise return false.\n\n**Example:**\n\nFor `nums = [1... |
import math
def find_nearest_points(points):
if len(points) < 2:
raise ValueError("At least two points are required.")
min_distance = float('inf')
closest_pair = None
for i in range(len(points)):
for j in range(i + 1, len(points)):
p1 = points[i]
p2 = points[j]
... | simplelr_Package | [
{
"content": "Question:\nYou are asked to write a Python function named `find_nearest_points` that identifies the pair of points in a 2D plane which are closest to each other. Your function should use a brute-force algorithm to ensure the pair with the minimum distance is found.\n\n**Function Specification:**\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5289,
"level": 1,
"question": "You are asked to write a Python function named `find_nearest_points` that identifies the pair of points in a 2D plane which are closest to each other. Your function should use a brute-force algorithm to ensure the pair with the minimum distance is foun... |
def string_repeater(s):
count = 0
for c in s:
if c.isalpha():
count += 1
return s * count | simplelr_Filter | [
{
"content": "Question:\nAlex's friend gave him the opportunity to build his a String Repeater, the older version of the old text repeater. He needs the repeating text to print out the same word as many times as the number of alphabets in the original word. So he needs a code. The code should take an input of s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5290,
"level": 1,
"question": "Alex's friend gave him the opportunity to build his a String Repeater, the older version of the old text repeater. He needs the repeating text to print out the same word as many times as the number of alphabets in the original word. So he needs a code.... |
def find_max(numbers):
if not numbers:
raise ValueError("The list is empty.")
return max(numbers) | simplelr_Filter | [
{
"content": "Question:\nYou are given a list of numbers, and your goal is to write a function called `find_max` that finds the highest number in the list. \n\nTo do this, you need to implement a function that takes in a list of numbers as input and returns the maximum value in the list.\n\nHere's an example of... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5291,
"level": 1,
"question": "You are given a list of numbers, and your goal is to write a function called `find_max` that finds the highest number in the list. \n\nTo do this, you need to implement a function that takes in a list of numbers as input and returns the maximum value i... |
from collections import deque
def min_hops(boxes):
n = len(boxes)
if n == 1:
return 0
visited = [False] * n
q = deque()
q.append((0, 0))
visited[0] = True
while q:
i, hops = q.popleft()
max_reach = i + boxes[i]
for j in range(i + 1, max_reach + 1):
... | simplelr_Codeforces | [
{
"content": "Question:\nAlex loves spending his free time playing a popular board game called NumberHoppers. The game involves a line of boxes numbered from 1 to n, and each box contains a single integer. The objective is to start at the first box and reach the last box by hopping according to the rules of the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5292,
"level": 1,
"question": "Alex loves spending his free time playing a popular board game called NumberHoppers. The game involves a line of boxes numbered from 1 to n, and each box contains a single integer. The objective is to start at the first box and reach the last box by ho... |
def calculate_lps_array(s: str) -> list[int]:
n = len(s)
lps = [0] * n
current_length = 0 # length of the previous longest prefix suffix
for i in range(1, n):
# The while loop to backtrack
while current_length > 0 and s[i] != s[current_length]:
current_length = lps[current_... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n**Find Longest Proper Prefix which is also Suffix (LPS Array Calculation)**\n\nGiven a string, write a function `calculate_lps_array(s: str) -> list[int]` that computes the Longest Proper Prefix which is also Suffix array used in the KMP (Knuth-Morris-P... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5293,
"level": 1,
"question": "### Coding Assessment Question\n\n**Find Longest Proper Prefix which is also Suffix (LPS Array Calculation)**\n\nGiven a string, write a function `calculate_lps_array(s: str) -> list[int]` that computes the Longest Proper Prefix which is also Suffix ar... |
def product_of_list(numbers):
if not numbers:
return 1
product = 1
for number in numbers:
product *= number
return product | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of numbers as input and returns the product of all the numbers in the list. The function should handle the case where the list is empty by returning 1, as the product of an empty set is conventionally 1.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5294,
"level": 1,
"question": "Write a Python function that takes a list of numbers as input and returns the product of all the numbers in the list. The function should handle the case where the list is empty by returning 1, as the product of an empty set is conventionally 1.",
"s... |
def firstUniqChar(s: str) -> str:
counts = [0] * 26
for c in s:
counts[ord(c) - ord('a')] += 1
for c in s:
if counts[ord(c) - ord('a')] == 1:
return c
return ' ' | simplelr_Filter | [
{
"content": "Question:\nGiven a string containing only lowercase letters, find the first non-repeating character in the string.\n\nExample:\n\nInput: \"leetcode\"\nOutput: \"l\"\n\nConstraints:\n\n 1 <= s.length <= 10^5\n s consists only of lowercase letters.\n\nSolution:\n\n```python\ndef firstUniqChar(s: str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5295,
"level": 1,
"question": "Given a string containing only lowercase letters, find the first non-repeating character in the string.\n\nExample:\n\nInput: \"leetcode\"\nOutput: \"l\"\n\nConstraints:\n\n 1 <= s.length <= 10^5\n s consists only of lowercase letters.\n\nSolution:\n\n... |
import re
def search_dicts_by_key_value(list_of_dicts, key_name, regex):
results = []
for dictionary in list_of_dicts:
if key_name in dictionary:
value = dictionary[key_name]
if re.search(regex, str(value)):
results.append(dictionary)
return results | simplelr_Filter | [
{
"content": "Question:\nI need help with a function in Python that will allow me to search through a list of dictionaries to find all entries where a specified key has a value that matches a given regular expression. Can you provide a function that takes a list of dictionaries, a key name, and a regular expres... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5296,
"level": 1,
"question": "I need help with a function in Python that will allow me to search through a list of dictionaries to find all entries where a specified key has a value that matches a given regular expression. Can you provide a function that takes a list of dictionarie... |
def can_become_goal(s, goal):
if len(s) != len(goal):
return False
if len(s) == 0:
return True
return goal in (s + s) | simplelr_Leetcode | [
{
"content": "Question:\nGiven two strings `s` and `goal`, return `True` if and only if `s` can become `goal` after some number of **shifts** on `s`. A **shift** on `s` consists of moving the leftmost character of `s` to the rightmost position. For example, if `s = \"abcde\"`, then it will be `\"bcdea\"` after ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5297,
"level": 1,
"question": "Given two strings `s` and `goal`, return `True` if and only if `s` can become `goal` after some number of **shifts** on `s`. A **shift** on `s` consists of moving the leftmost character of `s` to the rightmost position. For example, if `s = \"abcde\"`,... |
def process_list(numbers, operation):
"""
This function performs a given mathematical operation on all items in a list.
Args:
numbers (list): A list of numbers.
operation (str): The mathematical operation to perform. It can be 'add', 'subtract', 'multiply', 'divide'.
Returns:
... | simplelr_Filter | [
{
"content": "Question:\nIn the problem we are discussing the process of iterating through a list of items and applying a set of operations to each item. The items in the list are of type `int` or `float`. We want to write a Python function that takes a list of numbers and returns the result of performing a cer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5298,
"level": 1,
"question": "In the problem we are discussing the process of iterating through a list of items and applying a set of operations to each item. The items in the list are of type `int` or `float`. We want to write a Python function that takes a list of numbers and ret... |
def longest_consecutive_subarray(nums):
if not nums:
return 0
s = set(nums)
max_length = 0
for num in s:
if (num - 1) not in s:
current_length = 1
next_num = num + 1
while next_num in s:
current_length += 1
next_num += 1... | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers, find the length of the longest subarray such that all elements are consecutive (the elements can be in any order).\n\nIf the array is empty, return 0.\n\nExample 1:\n\nInput: [1, 9, 3, 10, 4, 20, 2]\n\nOutput: 4\n\nExplanation: The longest consecutive element... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5299,
"level": 1,
"question": "Given an array of integers, find the length of the longest subarray such that all elements are consecutive (the elements can be in any order).\n\nIf the array is empty, return 0.\n\nExample 1:\n\nInput: [1, 9, 3, 10, 4, 20, 2]\n\nOutput: 4\n\nExplanati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.