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 findMaxLength(arr):
sum_so_far = 0
max_len = 0
sum_indices = {0: -1} # Initialize with sum 0 at index -1
for i in range(len(arr)):
if arr[i] == 0:
sum_so_far += 1
else:
sum_so_far -= 1
if sum_so_far in sum_indices:
current_length = i - s... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a **0-indexed** integer array `arr` of size `n`, return _the length of the largest subarray with an equal number of 0s and 1s_. For example, given `arr = [0, 1, 0]`, the longest subarray with equal number of 0s and 1s is `[0, 1]`, so you should return its length, which is 2.\nAnsw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1700,
"level": 1,
"question": "Given a **0-indexed** integer array `arr` of size `n`, return _the length of the largest subarray with an equal number of 0s and 1s_. For example, given `arr = [0, 1, 0]`, the longest subarray with equal number of 0s and 1s is `[0, 1]`, so you should r... |
def count_odd_sum_pairs(nums):
even_count = 0
odd_count = 0
for num in nums:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
return even_count * odd_count | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums`, return _the count of distinct pairs (i, j) where i < j and nums[i] + nums[j] is an odd number_. The array may contain both positive and negative integers and the numbers can be repeated. \n\nFor example, given `nums = [1, 2, 3, 4, 5]`, the valid pairs ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1701,
"level": 1,
"question": "Given an array of integers `nums`, return _the count of distinct pairs (i, j) where i < j and nums[i] + nums[j] is an odd number_. The array may contain both positive and negative integers and the numbers can be repeated. \n\nFor example, given `nums =... |
def fun(lst):
if not lst:
return () # Though per constraints, this case doesn't occur
min_val = max_val = lst[0]
for num in lst[1:]:
if num < min_val:
min_val = num
elif num > max_val:
max_val = num
return (min_val, max_val) | simplelr_Filter | [
{
"content": "Question:\nYou have been tasked with writing a function `fun` that takes a list of integers as input and returns the minimum and maximum values in the list using only built-in Python functions and no external libraries. \n\nGiven the following constraints:\n- The input list will always contain at ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1702,
"level": 1,
"question": "You have been tasked with writing a function `fun` that takes a list of integers as input and returns the minimum and maximum values in the list using only built-in Python functions and no external libraries. \n\nGiven the following constraints:\n- The... |
def get_squares_between(s1: int, s2: int) -> int:
"""Return a bitboard with all squares between s1 and s2 (inclusive) set,
assuming they are on the same file or rank."""
f1 = s1 % 8
r1 = s1 // 8
f2 = s2 % 8
r2 = s2 // 8
result = 0
if r1 == r2:
# Same rank
min_f... | simplelr_Filter | [
{
"content": "Question:\nI have a bitboard representation of a chess board. The board is represented by a 64-bit integer, with bits 0-7 representing the first row, bits 8-15 representing the second row and so on. \n\nHere are some functions for common operations:\n\n```python\ndef get_square(bitboard: int, squa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1703,
"level": 1,
"question": "I have a bitboard representation of a chess board. The board is represented by a 64-bit integer, with bits 0-7 representing the first row, bits 8-15 representing the second row and so on. \n\nHere are some functions for common operations:\n\n```python\... |
import re
def count_occurrences(sentence: str, word: str) -> int:
# Escape any special regex characters in the word to avoid issues with characters like apostrophes
pattern = re.compile(r'\b{}\b'.format(re.escape(word)), re.IGNORECASE)
return len(pattern.findall(sentence)) | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nWrite a function `count_occurrences(sentence: str, word: str) -> int` that counts the number of occurrences of a given word in a string. Your implementation should only count whole word matches and should be case-insensitive.\n\n### Input and Output Formats\n\n-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1704,
"level": 1,
"question": "### Problem Statement\n\nWrite a function `count_occurrences(sentence: str, word: str) -> int` that counts the number of occurrences of a given word in a string. Your implementation should only count whole word matches and should be case-insensitive.\n... |
def rearrange_string(s):
digits = []
letters = []
for c in s:
if c.isdigit():
digits.append(c)
else:
letters.append(c)
return ''.join(digits + letters) | simplelr_Apps | [
{
"content": "Question:\nDesign a function that, given a string with letters and digits, rearranges the characters so that all the digits come before all the letters. The digits should remain in their original relative order, and the letters should remain in their original relative order as well.\n\nExample 1:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1705,
"level": 1,
"question": "Design a function that, given a string with letters and digits, rearranges the characters so that all the digits come before all the letters. The digits should remain in their original relative order, and the letters should remain in their original rel... |
def wiggle_sort(nums):
nums = nums.copy()
for i in range(len(nums) - 1):
if i % 2 == 0:
if nums[i] > nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]
else:
if nums[i] < nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]
return nums | simplelr_Apps | [
{
"content": "Question:\nDesign a function that takes an unsorted list of integers and returns the same list but sorted in the 'wiggle' order. \n\nA list is in 'wiggle' order if `nums[0] <= nums[1] >= nums[2] <= nums[3] >= ...`\n\nExample\n-----\n\n`wiggle_sort([3, 5, 2, 1, 6, 4])` should return `[3, 5, 1, 6, 2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1706,
"level": 1,
"question": "Design a function that takes an unsorted list of integers and returns the same list but sorted in the 'wiggle' order. \n\nA list is in 'wiggle' order if `nums[0] <= nums[1] >= nums[2] <= nums[3] >= ...`\n\nExample\n-----\n\n`wiggle_sort([3, 5, 2, 1, 6,... |
def multiply_matrices(matrix1, matrix2):
# Check if either matrix is empty
if not matrix1 or not matrix2:
return None
# Get dimensions of the matrices
rows1 = len(matrix1)
cols1 = len(matrix1[0]) if rows1 > 0 else 0
rows2 = len(matrix2)
# Check if multiplication is possible
if co... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that multiplies two matrices. The matrices can have any number of rows and columns. However, the number of columns in the first matrix must match the number of rows in the second matrix. Here is how the function should work: `multiply_matrices(matrix1, matrix2)`, where... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1707,
"level": 1,
"question": "Create a function that multiplies two matrices. The matrices can have any number of rows and columns. However, the number of columns in the first matrix must match the number of rows in the second matrix. Here is how the function should work: `multiply... |
from typing import List
def find_substring_anagrams(s: str, p: str) -> List[int]:
len_p = len(p)
len_s = len(s)
result = []
if len_p == 0 or len_s < len_p:
return result
# Create frequency count for p
p_count = [0] * 26
for c in p:
p_count[ord(c) - ord('a')] += 1
... | simplelr_Package | [
{
"content": "Question:\nYou are required to implement a function called `find_substring_anagrams` that finds all starting indices of substrings in a given string `s` that are anagrams of a given string `p`.\n\nAn anagram is formed by rearranging the letters of another string using all the original letters exac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1708,
"level": 1,
"question": "You are required to implement a function called `find_substring_anagrams` that finds all starting indices of substrings in a given string `s` that are anagrams of a given string `p`.\n\nAn anagram is formed by rearranging the letters of another string ... |
def mod_expo(base: int, exponent: int, mod: int) -> int:
if exponent < 0:
raise ValueError("Exponent must be positive.")
if exponent == 0:
return 1 % mod
result = 1
current_base = base % mod
while exponent > 0:
if exponent % 2 == 1:
result = (result * current_base... | simplelr_Data_Structure | [
{
"content": "Question:\nIn the context of cryptographic computations, you have been assigned the task of implementing a modular exponentiation function. This function is crucial for efficient handling of large powers under a modulo operation. \n\nImplement a function `mod_expo` that computes `(base ^ exponent)... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1709,
"level": 1,
"question": "In the context of cryptographic computations, you have been assigned the task of implementing a modular exponentiation function. This function is crucial for efficient handling of large powers under a modulo operation. \n\nImplement a function `mod_exp... |
def daily_step_goal(step_counts, goal):
return [steps >= goal for steps in step_counts] | simplelr_Apps | [
{
"content": "Question:\nYou're a software developer for a fitness app, and your task is to create a feature that tracks a user's daily step count. Each day, the user uploads their step data, and you need to determine on which days their step count exceeded their goal.\n\nWrite a function `daily_step_goal()` th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1710,
"level": 1,
"question": "You're a software developer for a fitness app, and your task is to create a feature that tracks a user's daily step count. Each day, the user uploads their step data, and you need to determine on which days their step count exceeded their goal.\n\nWrit... |
def merge_sorted_lists(a, b):
result = []
i, j = 0, 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
result += a[i:]
result += b[j:]
return result | simplelr_Filter | [
{
"content": "Question:\nWhen we merge two sorted lists into one, we place the smaller element from the front of the lists into the new list. We repeat this process until one list is empty. Then we just append the remaining elements, if any, from the non-empty list to the new list. \n\nWrite a function that mer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1711,
"level": 1,
"question": "When we merge two sorted lists into one, we place the smaller element from the front of the lists into the new list. We repeat this process until one list is empty. Then we just append the remaining elements, if any, from the non-empty list to the new ... |
def two_sum(nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return [] | simplelr_Filter | [
{
"content": "Question:\nGiven an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`.\n\n\n Example:\n\n ```\n Input: nums = [2,7,11,15], target = 9\n Output: [0,1]\n Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].\n ```\n\n Const... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1712,
"level": 1,
"question": "Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`.\n\n\n Example:\n\n ```\n Input: nums = [2,7,11,15], target = 9\n Output: [0,1]\n Explanation: Because nums[0] + nums[1] == 9... |
def is_optimized_palindrome(s: str) -> bool:
left = 0
right = len(s) - 1
while left < right:
# Move left pointer to the next alphanumeric character
while left < right and not s[left].isalnum():
left += 1
# Move right pointer to the previous alphanumeric character
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Implement an Optimized Palindrome Checker\n\nGiven a string, determine if it is a palindrome considering only alphanumeric characters and ignoring cases. Write an optimized function, `is_optimized_palindrome(s:str) -> bool`, that achieves this with minimal space complexity... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1713,
"level": 1,
"question": "### Question: Implement an Optimized Palindrome Checker\n\nGiven a string, determine if it is a palindrome considering only alphanumeric characters and ignoring cases. Write an optimized function, `is_optimized_palindrome(s:str) -> bool`, that achieves... |
import re
def palindromeCheck(s):
cleaned = re.sub(r'[^a-z0-9]', '', s.lower())
return cleaned == cleaned[::-1]
| simplelr_Taco | [
{
"content": "Question:\n```python\nComplete the function ```palindromeCheck``` that takes a string as input and returns ```True``` if the string is a palindrome and ```False``` otherwise. A palindrome is a word that reads the same backward as forward. Ignore case, spaces, and punctuation when determining if th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1714,
"level": 1,
"question": "```python\nComplete the function ```palindromeCheck``` that takes a string as input and returns ```True``` if the string is a palindrome and ```False``` otherwise. A palindrome is a word that reads the same backward as forward. Ignore case, spaces, and... |
def reverse_string(s):
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a string and returns its reverse. The function should handle special characters and numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1715,
"level": 1,
"question": "Create a function that takes in a string and returns its reverse. The function should handle special characters and numbers.",
"split": "train"
} |
import math
def find_divisor(n):
if n < 1:
return None
if n == 1:
return 1
for d in range(2, int(math.sqrt(n)) + 1):
if n % d == 0:
return d
return n | simplelr_Filter | [
{
"content": "Question:\nYou have been tasked with writing a function `find_divisor` that takes an integer `n` as input and returns the smallest divisor of `n`. The function should return `None` if `n` is less than 1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1716,
"level": 1,
"question": "You have been tasked with writing a function `find_divisor` that takes an integer `n` as input and returns the smallest divisor of `n`. The function should return `None` if `n` is less than 1.",
"split": "train"
} |
def longest_increasing_subarray(temps):
if not temps:
return 0
max_len = 1
current_len = 1
for i in range(1, len(temps)):
if temps[i] > temps[i - 1]:
current_len += 1
if current_len > max_len:
max_len = current_len
else:
current... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `temps` representing the daily temperatures for a certain period, where `temps[i]` is the temperature on the `ith` day. You need to find the length of the longest subarray in which the temperatures are strictly increasing on each day except th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1717,
"level": 1,
"question": "You are given a **0-indexed** integer array `temps` representing the daily temperatures for a certain period, where `temps[i]` is the temperature on the `ith` day. You need to find the length of the longest subarray in which the temperatures are strict... |
def is_palindrome(s):
processed = ''.join([char.lower() for char in s if char.isalnum()])
return processed == processed[::-1]
| simplelr_Taco | [
{
"content": "Question:\nKenneth loves puzzles and recently got fascinated with palindromes. He wants to write a function that verifies if a given string is a palindrome or not. He has heard about case differences and non-alphanumeric characters affecting the palindrome check and needs to account for them.\n\nW... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1718,
"level": 1,
"question": "Kenneth loves puzzles and recently got fascinated with palindromes. He wants to write a function that verifies if a given string is a palindrome or not. He has heard about case differences and non-alphanumeric characters affecting the palindrome check ... |
def sortColors(colors: list[int]) -> None:
low = 0
mid = 0
high = len(colors) - 1
while mid <= high:
if colors[mid] == 0:
colors[low], colors[mid] = colors[mid], colors[low]
low += 1
mid += 1
elif colors[mid] == 1:
mid += 1
else:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Sort Colors in Place\n\n#### Scenario\nYou are given an array containing 0s, 1s, and 2s (similar to the sorting challenge in the Dutch national flag problem). Your task is to sort these integers in-place so that all 0s come first, followed by all 1s, and then all 2s.\n\n#### Objecti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1719,
"level": 1,
"question": "### Sort Colors in Place\n\n#### Scenario\nYou are given an array containing 0s, 1s, and 2s (similar to the sorting challenge in the Dutch national flag problem). Your task is to sort these integers in-place so that all 0s come first, followed by all 1... |
def swap_first_last(lst):
if len(lst) > 1:
lst[0], lst[-1] = lst[-1], lst[0]
return lst
# Example usage:
numbers = [1, 2, 3, 4]
print("Original list:", numbers)
print("After swapping:", swap_first_last(numbers)) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program to swap the first and last element of a given list of integers. If the list has only one element, leave it unchanged.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1720,
"level": 1,
"question": "Write a Python program to swap the first and last element of a given list of integers. If the list has only one element, leave it unchanged.",
"split": "train"
} |
def smallest_missing_positive(nums: list[int]) -> int:
positive_nums = {x for x in nums if x > 0}
current = 1
while current in positive_nums:
current += 1
return current | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\n#### Context\nIn data analysis or competitive programming, efficiently finding statistics on a list of integers can be a frequent task. One common requirement is to identify the smallest missing positive integer from a sequence, which can assist in various problem-solvin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1721,
"level": 1,
"question": "### Question\n\n#### Context\nIn data analysis or competitive programming, efficiently finding statistics on a list of integers can be a frequent task. One common requirement is to identify the smallest missing positive integer from a sequence, which c... |
def sum_within_ranges(lst, ranges):
return [sum(lst[start:end+1]) for start, end in ranges] | simplelr_Apps | [
{
"content": "Question:\nGiven a list of integers and a set of ranges, write a function that returns the sum of the elements within each range.\n\nEach range is provided as a tuple where the first element is the start index and the second element is the end index (inclusive). Assume the indices are zero-based, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1722,
"level": 1,
"question": "Given a list of integers and a set of ranges, write a function that returns the sum of the elements within each range.\n\nEach range is provided as a tuple where the first element is the start index and the second element is the end index (inclusive). ... |
def remove_vowels(s):
vowels = 'aeiouAEIOU'
return ''.join([c for c in s if c not in vowels]) | simplelr_Filter | [
{
"content": "Question:\nThis is a coding challenge:\n\n**Challenge:**\n\nWrite a function that takes a string as input and returns a new string with all vowels removed.\n\n**Example:**\n\n```\nremove_vowels(\"Hello World!\")\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1723,
"level": 1,
"question": "This is a coding challenge:\n\n**Challenge:**\n\nWrite a function that takes a string as input and returns a new string with all vowels removed.\n\n**Example:**\n\n```\nremove_vowels(\"Hello World!\")",
"split": "train"
} |
def final_counter_value(operations):
counter = 0
for op in operations:
if op == "+":
counter += 1
elif op == "-":
counter -= 1
elif op == "++":
counter += 2
elif op == "--":
counter -= 2
return counter | simplelr_Leetcode | [
{
"content": "Question:\nYou are provided with a list of strings `operations` where each string represents a specific mathematical operation to be performed on a counter that starts at 0. The operations can be as follows:\n- `\"+\"` : Increment the counter by 1.\n- `\"-\"` : Decrement the counter by 1.\n- `\"++... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1724,
"level": 1,
"question": "You are provided with a list of strings `operations` where each string represents a specific mathematical operation to be performed on a counter that starts at 0. The operations can be as follows:\n- `\"+\"` : Increment the counter by 1.\n- `\"-\"` : D... |
import bisect
def process_operations_and_queries(operations, queries1, queries2):
s = set()
sorted_list = []
for op in operations:
parts = op.split()
cmd = parts[0]
x = int(parts[1])
if cmd == 'I':
if x not in s:
bisect.insort(sorted_list, x)
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array `operations` where `operations[i]` is either \"I x\" or \"D x\". \"I x\" means inserting the integer `x` into a set and \"D x\" means deleting the integer `x` from the set if it exists. Additionally, you are given two arrays `queries1` and `queries2` each containi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1725,
"level": 1,
"question": "You are given an array `operations` where `operations[i]` is either \"I x\" or \"D x\". \"I x\" means inserting the integer `x` into a set and \"D x\" means deleting the integer `x` from the set if it exists. Additionally, you are given two arrays `que... |
def square_numbers(numbers):
return [x ** 2 for x in numbers] | simplelr_Filter | [
{
"content": "Question:\nIs there any way to write a function in Python that can take a list of numbers as **input and return the square of each number** in the list?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1726,
"level": 1,
"question": "Is there any way to write a function in Python that can take a list of numbers as **input and return the square of each number** in the list?",
"split": "train"
} |
from typing import List, Tuple
def average_completion_time(data: List[Tuple[int, int]]) -> float:
completion_times = [timestamp for percent, timestamp in data if percent == 100]
if not completion_times:
return -1.0
return sum(completion_times) / len(completion_times) | simplelr_Code_Contests | [
{
"content": "Question:\nA company has recently introduced a new feature in their project management tool that allows users to track progress through a series of checkpoints. Each checkpoint is represented by a completion percentage and a timestamp indicating when this checkpoint was reached. The company wants ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1727,
"level": 1,
"question": "A company has recently introduced a new feature in their project management tool that allows users to track progress through a series of checkpoints. Each checkpoint is represented by a completion percentage and a timestamp indicating when this checkpo... |
def double_values(d):
return {k: v * 2 for k, v in d.items()} | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts a dictionary and returns a new dictionary with all the values doubled.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1728,
"level": 1,
"question": "Create a function that accepts a dictionary and returns a new dictionary with all the values doubled.",
"split": "train"
} |
def sort_books(books):
return sorted(books, key=lambda x: (x['year'], x['title'], x['author'])) | simplelr_Apps | [
{
"content": "Question:\nYou are tasked with managing the inventory of a small library. Each book in the library is cataloged with its title, author, and the year it was published. You need to create an inventory report sorted by specific criteria.\n\nWrite a function that takes a list of objects representing t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1729,
"level": 1,
"question": "You are tasked with managing the inventory of a small library. Each book in the library is cataloged with its title, author, and the year it was published. You need to create an inventory report sorted by specific criteria.\n\nWrite a function that tak... |
def is_palindrome(s):
# Process the string to include only alphanumeric characters in lowercase
processed = []
for char in s:
if char.isalnum():
processed.append(char.lower())
processed_str = ''.join(processed)
# Two-pointer approach to check if the processed string is a pal... | simplelr_Package | [
{
"content": "Question:\nIn this exercise, you are asked to write a function that determines if a given string is a valid palindrome, considering only alphanumeric characters and ignoring cases. The function will take a single parameter: the input string.\n\nYour task is to write a function `is_palindrome(s)` t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1730,
"level": 1,
"question": "In this exercise, you are asked to write a function that determines if a given string is a valid palindrome, considering only alphanumeric characters and ignoring cases. The function will take a single parameter: the input string.\n\nYour task is to wr... |
def increase_values(arr, factor=1):
counts = {}
result = []
for num in arr:
current_count = counts.get(num, 0)
incremented_num = num + current_count * factor
result.append(incremented_num)
counts[num] = current_count + 1
return result | simplelr_Filter | [
{
"content": "Question:\nI have an array of numbers from 0-100. I want to write a python function that will increase each value in the array by a value that is proportional to the number of times it has been seen before in the array. The more times a number has been seen, the more it will be increased. How can ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1731,
"level": 1,
"question": "I have an array of numbers from 0-100. I want to write a python function that will increase each value in the array by a value that is proportional to the number of times it has been seen before in the array. The more times a number has been seen, the ... |
def maximum_difference(arr):
if len(arr) < 2:
return 0
max_diff = 0
min_so_far = arr[0]
for num in arr[1:]:
current_diff = num - min_so_far
if current_diff > max_diff:
max_diff = current_diff
if num < min_so_far:
min_so_far = num
return max_dif... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns the maximum difference between any two elements such that the larger element comes after the smaller element. For example, given the list [4, 3, 10, 2, 9, 7], the maximum difference would be 7 (10 - 3). Ensure the function handl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1732,
"level": 1,
"question": "Write a function that takes a list of integers and returns the maximum difference between any two elements such that the larger element comes after the smaller element. For example, given the list [4, 3, 10, 2, 9, 7], the maximum difference would be 7 ... |
def longest_consecutive_subsequence(nums: list[int]) -> int:
if not nums:
return 0
num_set = set(nums)
max_length = 0
for num in num_set:
if (num - 1) not in num_set:
current_length = 1
current_num = num
while (current_num + 1) in num_set:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nWrite a function `longest_consecutive_subsequence(nums: List[int]) -> int` that returns the length of the longest consecutive elements subsequence. A consecutive elements subsequence is a sequence of numbers that can be obtained by selecting some elements from t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1733,
"level": 1,
"question": "### Problem Statement\n\nWrite a function `longest_consecutive_subsequence(nums: List[int]) -> int` that returns the length of the longest consecutive elements subsequence. A consecutive elements subsequence is a sequence of numbers that can be obtaine... |
def swap_adjacent_characters(s):
s = list(s)
for i in range(0, len(s) - 1, 2):
s[i], s[i+1] = s[i+1], s[i]
return ''.join(s) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to swap every two adjacent characters in a string. If the string has an odd number of characters, the last character remains in its original place. For example, if the input is \"hello\", the output should be \"elhol\". If the input is \"world\", the output shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1734,
"level": 1,
"question": "Write a python function to swap every two adjacent characters in a string. If the string has an odd number of characters, the last character remains in its original place. For example, if the input is \"hello\", the output should be \"elhol\". If the i... |
from collections import Counter
def can_form_palindrome(word):
return sum(v % 2 for v in Counter(word).values()) <= 1 | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `word` that consists of only lowercase English letters. You need to determine if you can rearrange the letters of the string to form a palindrome. Return `true` if it is possible to rearrange the letters to form a palindrome, and `false` otherwise. A string can fo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1735,
"level": 1,
"question": "You are given a string `word` that consists of only lowercase English letters. You need to determine if you can rearrange the letters of the string to form a palindrome. Return `true` if it is possible to rearrange the letters to form a palindrome, and... |
def naive_bayes_iris_classification():
# Step 1: Importing the necessary libraries and loading the Iris dataset
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
import numpy as np
# Load the Iris dataset
... | simplelr_Docs | [
{
"content": "Question:\n## Coding Assessment Question\n\n### Naive Bayes Classifiers in Scikit-Learn\n\nIn this assessment, you are required to explore and implement a Naive Bayes classifier to classify a given dataset. The task will focus on using the `GaussianNB` classifier from the `scikit-learn` library to... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1736,
"level": 1,
"question": "## Coding Assessment Question\n\n### Naive Bayes Classifiers in Scikit-Learn\n\nIn this assessment, you are required to explore and implement a Naive Bayes classifier to classify a given dataset. The task will focus on using the `GaussianNB` classifier... |
def join_with_slash(base: str, suffix: str) -> str:
base_stripped = base.rstrip('/')
suffix_stripped = suffix.lstrip('/')
if not base_stripped:
return '/' + suffix_stripped
else:
return f"{base_stripped}/{suffix_stripped}" | simplelr_Data_Structure | [
{
"content": "Question:\n## Problem Statement\nYou are developing a web application that constructs URLs for API endpoints based on a base URL and various endpoints. Additionally, the same function should work for joining file paths in the different parts of the system. Write a function `join_with_slash` that t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1737,
"level": 1,
"question": "## Problem Statement\nYou are developing a web application that constructs URLs for API endpoints based on a base URL and various endpoints. Additionally, the same function should work for joining file paths in the different parts of the system. Write ... |
from collections import deque
def smallest_subarray_with_sum(arr, x):
if not arr:
return 0
prefix = [0]
for num in arr:
prefix.append(prefix[-1] + num)
min_len = float('inf')
dq = deque()
dq.append(0)
for j in range(1, len(prefix)):
# Check if current prefix sum w... | simplelr_Leetcode | [
{
"content": "Question:\n**Question 4**: You are given an array of integers `arr` and a number `x`. You need to find the length of the smallest contiguous subarray of which the sum is greater than or equal to `x`. If no such subarray exists, return `0`.\nAnswer:\nLet's think step by step.\n",
"role": "user"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1738,
"level": 1,
"question": "**Question 4**: You are given an array of integers `arr` and a number `x`. You need to find the length of the smallest contiguous subarray of which the sum is greater than or equal to `x`. If no such subarray exists, return `0`.",
"split": "train"
} |
def compare_versions(version1, version2):
v1 = list(map(int, version1.split('.')))
v2 = list(map(int, version2.split('.')))
max_length = max(len(v1), len(v2))
v1 += [0] * (max_length - len(v1))
v2 += [0] * (max_length - len(v2))
for i in range(max_length):
if v1[i] < v2[i]... | simplelr_Evol | [
{
"content": "Question:\nWrite a function `compare_versions(version1, version2)` that takes two version strings as input and returns -1 if `version1` is less than `version2`, 1 if `version1` is greater than `version2`, and 0 if they are equal. Versions are composed of one or more integers separated by dots, and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1739,
"level": 1,
"question": "Write a function `compare_versions(version1, version2)` that takes two version strings as input and returns -1 if `version1` is less than `version2`, 1 if `version1` is greater than `version2`, and 0 if they are equal. Versions are composed of one or m... |
from collections import Counter
def are_anagrams(str1, str2):
# Process both strings to remove spaces and convert to lowercase
s1 = str1.replace(' ', '').lower()
s2 = str2.replace(' ', '').lower()
# If the lengths are different, they can't be anagrams
if len(s1) != len(s2):
return Fals... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes two strings as input and returns True if they are anagrams of each other, False otherwise. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For exampl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1740,
"level": 1,
"question": "Write a Python function that takes two strings as input and returns True if they are anagrams of each other, False otherwise. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the origin... |
def factorial(n):
if not isinstance(n, int) or n < 0:
raise ValueError("n must be a non-negative integer")
result = 1
for i in range(1, n + 1):
result *= i
return result | simplelr_Filter | [
{
"content": "Question:\nWhat is the most efficient way to create a Python function that returns the factorial of a number?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1741,
"level": 1,
"question": "What is the most efficient way to create a Python function that returns the factorial of a number?",
"split": "train"
} |
def reverse_string(s: str) -> str:
reversed_str = ""
for i in range(len(s)-1, -1, -1):
reversed_str += s[i]
return reversed_str | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns the string with the order of characters reversed, but without using the explicit reverse function or slicing. For example, the input string \"hello\" should return \"olleh\". \n\n```python\ndef reverse_string(s: str) -> st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1742,
"level": 1,
"question": "Write a Python function that takes a string as input and returns the string with the order of characters reversed, but without using the explicit reverse function or slicing. For example, the input string \"hello\" should return \"olleh\". \n\n```pytho... |
from collections import deque
def minSteps(matrix):
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
return -1
n = len(matrix)
m = len(matrix[0])
if matrix[0][0] == 0 or matrix[n-1][m-1] == 0:
return -1
visited = [[False for _ in range(m)] for _ in range(n)]
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a 2D matrix of integers where each cell represents a block. You are standing at the top-left corner of the matrix (cell [0,0]) and need to reach the bottom-right corner of the matrix (cell [n-1, m-1]). You can move right, left, up, or down, but only through cells that have... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1743,
"level": 1,
"question": "You are given a 2D matrix of integers where each cell represents a block. You are standing at the top-left corner of the matrix (cell [0,0]) and need to reach the bottom-right corner of the matrix (cell [n-1, m-1]). You can move right, left, up, or dow... |
def three_sum(nums, target):
nums.sort()
res = []
n = len(nums)
for i in range(n - 2):
if i > 0 and nums[i] == nums[i-1]:
continue
left, right = i + 1, n - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
if current_sum < ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers `nums` and an integer `target`. Your goal is to find all the unique triplets in the list which gives the sum of zero when added. To ensure the triplets are unique, the triplets should be sorted in non-descending order and no two triplets should have the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1744,
"level": 1,
"question": "You are given a list of integers `nums` and an integer `target`. Your goal is to find all the unique triplets in the list which gives the sum of zero when added. To ensure the triplets are unique, the triplets should be sorted in non-descending order a... |
def longest_subsequence_sum_k(nums, k):
dp = {0: 0}
for num in nums:
temp = {}
for s in dp:
new_sum = s + num
new_length = dp[s] + 1
if new_sum in temp:
if new_length > temp[new_sum]:
temp[new_sum] = new_length
e... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums` and an integer `k`, you need to find the **length of the longest subsequence** that has a sum equal to `k`. A **subsequence** is derived from the array by deleting some or none of the elements without changing the order of the remaining elements. The su... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1745,
"level": 1,
"question": "Given an array of integers `nums` and an integer `k`, you need to find the **length of the longest subsequence** that has a sum equal to `k`. A **subsequence** is derived from the array by deleting some or none of the elements without changing the orde... |
def modular_exponentiation(a: int, n: int, m: int) -> int:
if n == 0:
return 1 % m
if m == 1:
return 0
result = 1
current_a = a % m
current_n = n
while current_n > 0:
if current_n % 2 == 1:
result = (result * current_a) % m
current_a = (current_a * cur... | simplelr_Data_Structure | [
{
"content": "Question:\n### Digital Fortress Security\n\nIn the realm of Digital Fortress, high-security encryption protocols often need large exponentiations for encryption and decryption processes. You have been recruited to enhance and ensure the efficiency of one such algorithm.\n\n#### Problem Statement\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1746,
"level": 1,
"question": "### Digital Fortress Security\n\nIn the realm of Digital Fortress, high-security encryption protocols often need large exponentiations for encryption and decryption processes. You have been recruited to enhance and ensure the efficiency of one such alg... |
def max_profit_with_k_transactions(prices, k):
if not prices or k == 0:
return 0
n = len(prices)
k = min(k, n // 2) # Each transaction needs at least two days
dp = [[-float('inf')] * 2 for _ in range(k + 1)]
dp[0][0] = 0 # Base case: 0 transactions, not holding stock
for price in ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the maximum profit that can be made from at most k transactions on a given list of stock prices. You can complete as many transactions as you like, but you must sell the stock before you buy again, and you cannot engage in multiple transactions simultaneous... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1747,
"level": 1,
"question": "Write a function to calculate the maximum profit that can be made from at most k transactions on a given list of stock prices. You can complete as many transactions as you like, but you must sell the stock before you buy again, and you cannot engage in... |
from collections import Counter
def can_form_palindrome(s):
counts = Counter(s)
odd_counts = 0
for count in counts.values():
if count % 2 != 0:
odd_counts += 1
if odd_counts > 1:
return False
return True | simplelr_Leetcode | [
{
"content": "Question:\nImplement a function that takes a string `s` as input and checks if it can be rearranged to form a palindrome. Return `true` if it is possible to rearrange the string to form a palindrome, otherwise return `false`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1748,
"level": 1,
"question": "Implement a function that takes a string `s` as input and checks if it can be rearranged to form a palindrome. Return `true` if it is possible to rearrange the string to form a palindrome, otherwise return `false`.",
"split": "train"
} |
def cumulative_except_self(numbers):
total = sum(numbers)
return [total - x for x in numbers] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a new list. The new list should contain the cumulative sum of the original list, excluding the current element in the sum. The function should be named `cumulative_except_self` and have one parameter `numbers` (a list of intege... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1749,
"level": 1,
"question": "Create a function that takes a list of integers and returns a new list. The new list should contain the cumulative sum of the original list, excluding the current element in the sum. The function should be named `cumulative_except_self` and have one pa... |
def sum_of_natural_numbers(n):
if n < 1:
return 0
total = 0
for i in range(1, n + 1):
total += i
return total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the sum of the first 'n' natural numbers using a loop.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1750,
"level": 1,
"question": "Create a function that calculates the sum of the first 'n' natural numbers using a loop.",
"split": "train"
} |
def calculate_moving_average(prices: list[float], k: int) -> list[float]:
n = len(prices)
if n == 0 or k <= 0 or k > n:
return []
current_sum = sum(prices[:k])
result = [current_sum / k]
for i in range(k, n):
current_sum = current_sum - prices[i - k] + prices[i]
res... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\nYou're working on a feature for an e-commerce application that manages product pricing. To better understand how pricing changes over time, you need a function that calculates the moving average of product prices. A moving average smooths out price data to show l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1751,
"level": 1,
"question": "### Problem Statement:\nYou're working on a feature for an e-commerce application that manages product pricing. To better understand how pricing changes over time, you need a function that calculates the moving average of product prices. A moving avera... |
import re
def is_palindrome(s):
"""
Determine if a given string is a palindrome.
Args:
s (str): The input string.
Returns:
bool: True if the string is a palindrome, False otherwise.
"""
# Remove all non-alphanumeric characters and convert to lowercase
cleaned_s = re.sub(r'\W+', ''... | simplelr_Filter | [
{
"content": "Question:\nGiven a string, determine if it 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### Example Use Cases\n\n* `is_palindrome(\"A man, a plan, a canal: Pa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1752,
"level": 1,
"question": "Given a string, determine if it 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### Example Use Cases\n\n* `is_pali... |
def sort_problems(problem_list):
# Extract the difficulty levels to check for duplicates
difficulties = [p[1] for p in problem_list]
if len(difficulties) != len(set(difficulties)):
return 'impossible'
# Sort the problems by their difficulty level
sorted_problems = sorted(problem_list, key=la... | simplelr_Taco | [
{
"content": "Question:\nJenny is organizing a programming competition for her university. To determine the sequence of problems to present, she has to ensure the difficulty levels increase monotonically. Each problem has a unique identifier and a difficulty level, both given as inputs. However, some problem se... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1753,
"level": 1,
"question": "Jenny is organizing a programming competition for her university. To determine the sequence of problems to present, she has to ensure the difficulty levels increase monotonically. Each problem has a unique identifier and a difficulty level, both given ... |
def decode_symbols(encoded_sequence: list, k: int, symbol_set_size: int) -> list:
result = []
for s in encoded_sequence:
decoded = ((s - 1 - k) % symbol_set_size) + 1
result.append(decoded)
return result | simplelr_Codeforces | [
{
"content": "Question:\nAn island is inhabited by a tribe that communicates using a unique language made up of various symbols. Each symbol represents a specific positive integer. In order to record their history, the tribe decides to inscribe a sequence of these symbols on stone tablets.\n\nHowever, their for... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1754,
"level": 1,
"question": "An island is inhabited by a tribe that communicates using a unique language made up of various symbols. Each symbol represents a specific positive integer. In order to record their history, the tribe decides to inscribe a sequence of these symbols on s... |
from typing import List
def three_sum_closest(nums: List[int], target: int) -> int:
nums.sort()
n = len(nums)
closest_sum = nums[0] + nums[1] + nums[2]
closest_diff = abs(closest_sum - target)
for i in range(n - 2):
left = i + 1
right = n - 1
while left < right:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` and an integer `target`. Your task is to find three distinct integers in the array `nums` such that the sum is closest to the given `target`. Write a function that returns the sum of the three integers. \nIf there are multiple answers, return the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1755,
"level": 1,
"question": "You are given an integer array `nums` and an integer `target`. Your task is to find three distinct integers in the array `nums` such that the sum is closest to the given `target`. Write a function that returns the sum of the three integers. \nIf ther... |
def canAttendAllMeetings(meetings):
# Sort the meetings based on start time
meetings.sort()
# Check each consecutive pair of meetings for overlap
for i in range(1, len(meetings)):
if meetings[i][0] < meetings[i-1][1]:
return False
return True | simplelr_Leetcode | [
{
"content": "Question:\nA startup is developing a new scheduling system, and you are tasked with implementing a specific feature. You are given a list of meetings, each with a start time and an end time represented as integer tuples `(start, end)`. Your task is to determine if a person can attend all the given... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1756,
"level": 1,
"question": "A startup is developing a new scheduling system, and you are tasked with implementing a specific feature. You are given a list of meetings, each with a start time and an end time represented as integer tuples `(start, end)`. Your task is to determine i... |
def rearrange_max_min(arr: list[int]) -> list[int]:
n = len(arr)
result = []
low = 0
high = n - 1
while low < high:
result.append(arr[high])
result.append(arr[low])
high -= 1
low += 1
if low == high:
result.append(arr[low])
return result | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Rearrange Array Alternately\n\nYou are given a sorted array of distinct positive integers. Your task is to rearrange the array such that the maximum element is followed by the minimum, then the second maximum element is followed by the second minimum, and so on.\n\n**Funct... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1757,
"level": 1,
"question": "### Question: Rearrange Array Alternately\n\nYou are given a sorted array of distinct positive integers. Your task is to rearrange the array such that the maximum element is followed by the minimum, then the second maximum element is followed by the se... |
from typing import Union, List
def total_kinetic_energy(masses: List[float], velocities: List[Union[float, List[float]]]) -> float:
if len(masses) != len(velocities):
raise ValueError("Mismatch between number of masses and velocities")
total_ke = 0.0
for mass, velocity in zip(masses, velociti... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are tasked with implementing a function to calculate the total kinetic energy of a system of objects.\n\n### Functional Requirements\n\nImplement a function `total_kinetic_energy(masses: list[float], velocities: list[Union[float, list[float]]]) -> float` tha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1758,
"level": 1,
"question": "### Problem Statement\n\nYou are tasked with implementing a function to calculate the total kinetic energy of a system of objects.\n\n### Functional Requirements\n\nImplement a function `total_kinetic_energy(masses: list[float], velocities: list[Union[... |
def even_or_odd(nums):
result = []
for num in nums:
if num % 2 == 0:
result.append('Even')
else:
result.append('Odd')
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks whether each number in an array is even or odd and returns a new array with a description of each number. For example, if the input array is `[2, 5, 8, 9]`, the output should be `['Even', 'Odd', 'Even', 'Odd']`.\nAnswer:\nLet's think step by step.\n",
"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1759,
"level": 1,
"question": "Create a function that checks whether each number in an array is even or odd and returns a new array with a description of each number. For example, if the input array is `[2, 5, 8, 9]`, the output should be `['Even', 'Odd', 'Even', 'Odd']`.",
"split... |
def max_odd_number(numbers):
max_odd = None
for num in numbers:
if num == int(num): # Check if the number is an integer
if num % 2 != 0: # Check if the number is odd
if max_odd is None or num > max_odd:
max_odd = num
return max_odd | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python function that can find the maximum odd number in a given list? If there are no odd numbers, the function should return `None`. I also want this function to be efficient and easy to understand. Could you provide a code snippet for this?\nAnswer:\nLet's think... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1760,
"level": 1,
"question": "Can you help me with a Python function that can find the maximum odd number in a given list? If there are no odd numbers, the function should return `None`. I also want this function to be efficient and easy to understand. Could you provide a code snip... |
def restore_string(s, indices):
n = len(indices)
res = [''] * n
for i in range(n):
res[indices[i]] = s[i]
return ''.join(res) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` and an array of integers `indices` of the same length. The string `s` is scrambled such that the character at the `i`-th position moves to `indices[i]` in the resulting string. Construct the resulting string from the scrambled string `s` and the array `indices... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1761,
"level": 1,
"question": "You are given a string `s` and an array of integers `indices` of the same length. The string `s` is scrambled such that the character at the `i`-th position moves to `indices[i]` in the resulting string. Construct the resulting string from the scramble... |
from typing import List
def rotate_90_clockwise(matrix: List[List[int]]) -> None:
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nImplement a function to manipulate a square matrix by rotating it 90 degrees clockwise. Ensure your solution handles matrices of any size and does not use any auxiliary matrices for storage.\n\n#### Input:\n- A square matrix represented as a list of lists, where... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1762,
"level": 1,
"question": "### Problem Statement\n\nImplement a function to manipulate a square matrix by rotating it 90 degrees clockwise. Ensure your solution handles matrices of any size and does not use any auxiliary matrices for storage.\n\n#### Input:\n- A square matrix re... |
from typing import List
def maxProfit(prices: List[int]) -> int:
max_profit = 0
for i in range(len(prices) - 1):
if prices[i+1] > prices[i]:
max_profit += prices[i+1] - prices[i]
return max_profit | simplelr_Algorithm | [
{
"content": "Question:\n**Problem Statement**:\nYou are given an array of integers, which represents stock prices on consecutive days. Your task is to write a function `maxProfit` that computes the maximum profit you can achieve by buying and selling the stock. You are allowed to complete as many transactions ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1763,
"level": 1,
"question": "**Problem Statement**:\nYou are given an array of integers, which represents stock prices on consecutive days. Your task is to write a function `maxProfit` that computes the maximum profit you can achieve by buying and selling the stock. You are allowe... |
def is_interesting_substring(s: str, k: int) -> bool:
n = len(s)
if n < k or k == 0:
return False
current_sum = sum(ord(c) for c in s[:k])
if current_sum % k == 0:
return True
for i in range(1, n - k + 1):
current_sum = current_sum - ord(s[i-1]) + ord(s[i + k - 1])
if... | simplelr_Evol | [
{
"content": "Question:\nCreate a Python function `is_interesting_substring(s: str, k: int) -> bool` that determines if there exists a contiguous substring of length `k` within the given string `s` such that the sum of the ASCII values of its characters is divisible by `k`.\n\n#### Function Signature:\n```pytho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1764,
"level": 1,
"question": "Create a Python function `is_interesting_substring(s: str, k: int) -> bool` that determines if there exists a contiguous substring of length `k` within the given string `s` such that the sum of the ASCII values of its characters is divisible by `k`.\n\... |
import re
def reverse_words_in_string(s):
tokens = re.findall(r'\S+|\s+', s)
reversed_tokens = []
for token in tokens:
if token.strip(): # Check if the token is a word (non-whitespace)
reversed_tokens.append(token[::-1])
else: # The token is whitespace, leave it as is
... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a string as input and returns another string with each word reversed but in its original position. Punctuation should be treated as part of the word. For instance, the word \"don't\" should become \"t'nod\". Spaces should not be altered.\n\nTo make things cle... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1765,
"level": 1,
"question": "Write a function that takes a string as input and returns another string with each word reversed but in its original position. Punctuation should be treated as part of the word. For instance, the word \"don't\" should become \"t'nod\". Spaces should no... |
def min_bonus(ratings):
n = len(ratings)
if n == 0:
return 0
bonus = [1] * n
# Left to right pass
for i in range(1, n):
if ratings[i] > ratings[i-1]:
if bonus[i] <= bonus[i-1]:
bonus[i] = bonus[i-1] + 1
# Right to left pass
for i in ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `ratings` of size `n`, where `ratings[i]` represents the performance rating of the `ith` employee. Each employee is to receive a bonus in the form of additional points based on their performance rating relative to their neighbors. The followin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1766,
"level": 1,
"question": "You are given a **0-indexed** integer array `ratings` of size `n`, where `ratings[i]` represents the performance rating of the `ith` employee. Each employee is to receive a bonus in the form of additional points based on their performance rating relati... |
from typing import List
def add_to_inventory(current_items: List[str], new_items: List[str], max_inventory_size: int) -> List[str]:
current_list = list(current_items)
current_set = set(current_list)
for item in new_items:
if item in current_set:
continue
if len(current_list) >= ... | simplelr_Code_Contests | [
{
"content": "Question:\nRohan is designing a text-based adventure game where characters can collect various items. Each character has a limited inventory size, and they can't carry more items than their inventory allows. Rohan needs help implementing the functionality to add items to a character's inventory.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1767,
"level": 1,
"question": "Rohan is designing a text-based adventure game where characters can collect various items. Each character has a limited inventory size, and they can't carry more items than their inventory allows. Rohan needs help implementing the functionality to add ... |
def calculate(expression):
"""
Evaluates a mathematical expression contained within a string.
Args:
expression (str): The mathematical expression as a string.
Returns:
float: The result of the evaluated expression.
"""
if not isinstance(expression, str):
raise TypeError("Input ... | simplelr_Filter | [
{
"content": "Question:\n### Context\nYou have been tasked with creating a system that can evaluate the expressions contained within a string. The string will contain spaces and can have nested parentheses to group numbers and operators. \n\n### Problem\nWrite a code that can parse the string and evaluate the m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1768,
"level": 1,
"question": "### Context\nYou have been tasked with creating a system that can evaluate the expressions contained within a string. The string will contain spaces and can have nested parentheses to group numbers and operators. \n\n### Problem\nWrite a code that can ... |
def binary_array_to_int(arr):
result = 0
for bit in arr:
result = result * 2 + bit
return result | simplelr_Filter | [
{
"content": "Question:\nHow would you convert a binary number represented as an array of 0s and 1s into an integer in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1769,
"level": 1,
"question": "How would you convert a binary number represented as an array of 0s and 1s into an integer in Python?",
"split": "train"
} |
def frequency_replace(input_list):
freq_dict = {}
for num in input_list:
if num in freq_dict:
freq_dict[num] += 1
else:
freq_dict[num] = 1
result = []
for num in input_list:
result.append(freq_dict[num])
return result | simplelr_Evol | [
{
"content": "Question:\nDesign a function that takes a list of integers and returns a new list with each element replaced by the frequency of that element in the original list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1770,
"level": 1,
"question": "Design a function that takes a list of integers and returns a new list with each element replaced by the frequency of that element in the original list.",
"split": "train"
} |
def modified_fibonacci(n, a, b):
result = [a, b]
if n == 2:
return result
for i in range(2, n):
next_term = result[i-1] + result[i-2]
result.append(next_term)
return result | simplelr_Algorithm | [
{
"content": "Question:\n### Fibonacci Series Modification\n\n#### Problem Statement:\nWrite a function `modified_fibonacci` that returns a list of the first `n` terms of a modified Fibonacci sequence. In this sequence, each term is the sum of the previous term and the term before the previous term, but with th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1771,
"level": 1,
"question": "### Fibonacci Series Modification\n\n#### Problem Statement:\nWrite a function `modified_fibonacci` that returns a list of the first `n` terms of a modified Fibonacci sequence. In this sequence, each term is the sum of the previous term and the term be... |
import logging
import logging.config
import sys
def setup_logging():
config = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'format': '%(asctime)s - %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S',
},
... | simplelr_Docs | [
{
"content": "Question:\n### Advanced Python Logging Configuration\n\nYour task is to set up an advanced logging configuration using the `logging.config.dictConfig` function. You need to create a dictionary configuration that accomplishes the following:\n\n1. Defines two loggers:\n - A root logger that logs a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1772,
"level": 1,
"question": "### Advanced Python Logging Configuration\n\nYour task is to set up an advanced logging configuration using the `logging.config.dictConfig` function. You need to create a dictionary configuration that accomplishes the following:\n\n1. Defines two logge... |
from typing import List, Tuple
def fix_and_sum_revenues(sales: List[int]) -> Tuple[List[int], int]:
corrected = [rev if rev >= 0 else 0 for rev in sales]
total = sum(corrected)
return (corrected, total) | simplelr_Code_Contests | [
{
"content": "Question:\nYou have been tasked with analyzing the sales data of a retail store. The store has kept a record of sales in a list, where each element of the list is the revenue generated in a single day. However, there was an error in recording, and some days might have revenues recorded as a negati... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1773,
"level": 1,
"question": "You have been tasked with analyzing the sales data of a retail store. The store has kept a record of sales in a list, where each element of the list is the revenue generated in a single day. However, there was an error in recording, and some days might... |
def sort_by_third_item(tuples_list):
return sorted(tuples_list, key=lambda x: x[2]) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to sort a list of tuples by the third item in each tuple.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1774,
"level": 1,
"question": "Write a python function to sort a list of tuples by the third item in each tuple.",
"split": "train"
} |
def optimized_triangular_number(n: int) -> int:
if type(n) is not int:
raise TypeError("n must be an integer")
return n * (n + 1) // 2 | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Optimized Triangular Number Calculation\n\nYou are required to implement a function to compute the Nth triangular number using an optimized approach to ensure efficiency. A triangular number is the sum of the natural numbers up to N and is defined as follows:\n- T(0) = 0\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1775,
"level": 1,
"question": "### Question: Optimized Triangular Number Calculation\n\nYou are required to implement a function to compute the Nth triangular number using an optimized approach to ensure efficiency. A triangular number is the sum of the natural numbers up to N and i... |
import re
def is_valid_url(url):
pattern = r'^(https?|ftp)://[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,6}(:\d+)?(/[^?#\s]*)?(\?[a-zA-Z0-9-._~!$&\'()*+,;=:@/?]*)?(#[a-zA-Z0-9-._~!$&\'()*+,;=:@/?]*)?$'
return bool(re.match(pattern, url)) | simplelr_Filter | [
{
"content": "Question:\nHow can I create a function in Python to validate if a given string is a valid URL?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1776,
"level": 1,
"question": "How can I create a function in Python to validate if a given string is a valid URL?",
"split": "train"
} |
from datetime import date
def calculate_overdue_fee(return_date: str, due_date: str,
daily_fee: float = 0.25, grace_period: int = 5) -> float:
"""
Calculate the overdue fees for a rented book based on the return date and due date.
Args:
return_date (str): The date wh... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem:\nYou are asked to develop a feature for a library management system to manage book rentals. Specifically, you need to implement a function that calculates the overdue fees for rented books based on their return dates and predefined rules.\n\nThe library has the following ru... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1777,
"level": 1,
"question": "### Problem:\nYou are asked to develop a feature for a library management system to manage book rentals. Specifically, you need to implement a function that calculates the overdue fees for rented books based on their return dates and predefined rules.\... |
def longest_consecutive_subsequence(lst):
if not lst:
return []
s = set(lst)
sorted_lst = sorted(s)
max_len = 0
best_start = None
for num in sorted_lst:
if (num - 1) not in s:
current = num
current_len = 1
current += 1
whi... | simplelr_Apps | [
{
"content": "Question:\nCreate a function that takes a list of integers as an argument and returns the longest subsequence of consecutive integers that appear in the list, in any order. If two sequences have the same length, return the one that starts with the smallest integer.\n\n## Examples\n```\n[100, 4, 20... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1778,
"level": 1,
"question": "Create a function that takes a list of integers as an argument and returns the longest subsequence of consecutive integers that appear in the list, in any order. If two sequences have the same length, return the one that starts with the smallest intege... |
def sum_of_unique_elements(data: list[int]) -> int:
if not data:
return 0
freq = {}
for num in data:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
sum_unique = 0
for key in freq:
if freq[key] == 1:
sum_unique += key
return ... | simplelr_Algorithm | [
{
"content": "Question:\n**Sum of Unique Elements**\n\n### Context\nGiven a list of integers, you need to calculate the sum of elements that appear exactly once in the list. For instance, in the list [1, 2, 3, 2, 4], the numbers 1, 3, and 4 each appear exactly once, so their sum is 1 + 3 + 4 = 8.\n\n### Task\nW... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1779,
"level": 1,
"question": "**Sum of Unique Elements**\n\n### Context\nGiven a list of integers, you need to calculate the sum of elements that appear exactly once in the list. For instance, in the list [1, 2, 3, 2, 4], the numbers 1, 3, and 4 each appear exactly once, so their s... |
def reverse_string(s):
reversed_str = ""
for i in range(len(s)-1, -1, -1):
reversed_str += s[i]
return reversed_str | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as an input and returns the reverse of that string. For example, if the input is \"hello\", the function should return \"olleh\". You should use a loop to reverse the string and not use any built-in functions like `reverse()` or `[::-1]`.\nAnswer:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1780,
"level": 1,
"question": "Create a function that takes a string as an input and returns the reverse of that string. For example, if the input is \"hello\", the function should return \"olleh\". You should use a loop to reverse the string and not use any built-in functions like ... |
def max_sum_subarray_k_elements(arr, k):
n = len(arr)
if n == 0 or k == 0 or k > n:
return None
current_sum = sum(arr[:k])
max_sum = current_sum
for i in range(1, n - k + 1):
current_sum = current_sum - arr[i - 1] + arr[i + k - 1]
if current_sum > max_sum:
max_sum... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum sum of a subarray that has exactly k elements.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1781,
"level": 1,
"question": "Write a python function to find the maximum sum of a subarray that has exactly k elements.",
"split": "train"
} |
def smallest_subsequence(s):
last_occurrence = {char: idx for idx, char in enumerate(s)}
result = []
in_stack = set()
for i, c in enumerate(s):
if c in in_stack:
continue
# While we can pop from result
while result and c < result[-1] and last_occurrence[result[-1... | simplelr_Apps | [
{
"content": "Question:\nGiven a string s consisting of lowercase English letters, construct the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once. Your answer should be the subsequence that appears first in the string.\n\nExample 1:\nInput: s = \"bcabc\"\nO... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1782,
"level": 1,
"question": "Given a string s consisting of lowercase English letters, construct the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once. Your answer should be the subsequence that appears first in the string.\n\n... |
from datetime import datetime, timedelta
def get_available_time_slots(people_availability, duration):
if not people_availability:
return []
starts = [slot[0] for slot in people_availability]
ends = [slot[1] for slot in people_availability]
max_start = max(starts)
min_end = min(end... | simplelr_Filter | [
{
"content": "Question:\nHere is the code I've got so far. \n\n```python\nfrom datetime import datetime, timedelta\n\ndef get_available_time_slots(start_time, end_time, duration):\n available_time_slots = []\n time = start_time\n while time < end_time:\n end_of_time_slot = time + timedelta(minut... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1783,
"level": 1,
"question": "Here is the code I've got so far. \n\n```python\nfrom datetime import datetime, timedelta\n\ndef get_available_time_slots(start_time, end_time, duration):\n available_time_slots = []\n time = start_time\n while time < end_time:\n end_of... |
def int_to_roman(num):
roman_numerals = [
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(90, 'XC'),
(50, 'L'),
(40, 'XL'),
(10, 'X'),
(9, 'IX'),
(5, 'V'),
(4, 'IV'),
(1, 'I')
]
result = '... | simplelr_Apps | [
{
"content": "Question:\nCreate a function that takes an integer as an argument and returns the integer represented in Roman numerals. The provided number will always be in the range 1 to 3999.\n\nRoman numerals are represented by combinations of the following symbols:\n\n```\nSymbol Value\nI 1\nIV... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1784,
"level": 1,
"question": "Create a function that takes an integer as an argument and returns the integer represented in Roman numerals. The provided number will always be in the range 1 to 3999.\n\nRoman numerals are represented by combinations of the following symbols:\n\n```\... |
def isAutomorphic(n):
if n < 0:
return False
num_digits = len(str(n))
mod_val = 10 ** num_digits
squared = n ** 2
return squared % mod_val == n
| simplelr_Taco | [
{
"content": "Question:\n## Task:\nYou have to create a function `isAutomorphic` to check whether the argument passed is an Automorphic Number and return true if it is & false otherwise.\n\n### Description:\n\n`Automorphic Number` - An automorphic number is a number whose square ends in the same digits as the n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1785,
"level": 1,
"question": "## Task:\nYou have to create a function `isAutomorphic` to check whether the argument passed is an Automorphic Number and return true if it is & false otherwise.\n\n### Description:\n\n`Automorphic Number` - An automorphic number is a number whose squa... |
def repeatedSubstringPattern(s):
n = len(s)
if n == 0:
return False
f = [0] * n
for i in range(1, n):
j = f[i-1]
while j > 0 and s[i] != s[j]:
j = f[j-1]
if s[i] == s[j]:
j += 1
f[i] = j
d = n - f[-1]
return d != 0 and n % d == 0 an... | simplelr_Taco | [
{
"content": "Question:\nGiven a non-empty string s, write a program to check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. If such a method exists, return true, otherwise return false.\n\nExample 1:\nInput:\ns = \"abab\"\nOutput: true\nExplanation... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1786,
"level": 1,
"question": "Given a non-empty string s, write a program to check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. If such a method exists, return true, otherwise return false.\n\nExample 1:\nInput:\ns = ... |
from typing import List, Dict, Any
def filter_catalog(catalog: List[Dict[str, Any]], criteria: Dict[str, Any]) -> List[Dict[str, Any]]:
return [item for item in catalog if all(item.get(k) == v for k, v in criteria.items())] | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are developing a recommendation system for an e-commerce platform. To personalize recommendations, a function is required to filter out items from a catalog based on user-defined criteria. Each item in the catalog is represented by a dictionary containing va... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1787,
"level": 1,
"question": "### Problem Statement\n\nYou are developing a recommendation system for an e-commerce platform. To personalize recommendations, a function is required to filter out items from a catalog based on user-defined criteria. Each item in the catalog is repres... |
def Nora(a, b):
if a <= b:
return a
else:
return b | simplelr_Filter | [
{
"content": "Question:\nIn the context of a programming problem, I need to define a function ` Nora` that takes two integers `a` and `b` as input and returns the minimum value of `a` and `b`. Can you provide the problem statement and an example of how the function should work?\nAnswer:\nLet's think step by ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1788,
"level": 1,
"question": "In the context of a programming problem, I need to define a function ` Nora` that takes two integers `a` and `b` as input and returns the minimum value of `a` and `b`. Can you provide the problem statement and an example of how the function should work... |
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 == current_end:
jumps += 1
... | simplelr_Apps | [
{
"content": "Question:\nYou are given an array of non-negative integers where each element represents the maximum number of steps you can advance in the array. For example, if the element at index `i` is `3`, you can move from index `i` to either `i+1`, `i+2`, or `i+3`. Your goal is to determine the minimum nu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1789,
"level": 1,
"question": "You are given an array of non-negative integers where each element represents the maximum number of steps you can advance in the array. For example, if the element at index `i` is `3`, you can move from index `i` to either `i+1`, `i+2`, or `i+3`. Your ... |
def find_first_occurrence(array: list, query: int) -> int:
"""
Returns the index of the first occurrence of the given element in an array.
The array has to be sorted in increasing order.
"""
if not array:
return -1
left = 0
right = len(array) - 1
result = -1
while l... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nYou are tasked with implementing a function that efficiently finds the first occurrence of a given number in a sorted list of integers. This function will be used as part of a larger application where searching speed is critical, and the list is generally very large but a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1790,
"level": 1,
"question": "#### Scenario\nYou are tasked with implementing a function that efficiently finds the first occurrence of a given number in a sorted list of integers. This function will be used as part of a larger application where searching speed is critical, and the... |
def sort_list(input_list):
return sorted(input_list) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the sorted list in Python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1791,
"level": 1,
"question": "Write a function to find the sorted list in Python.",
"split": "train"
} |
def find_odd(lst):
if not lst:
return None
result = 0
for num in lst:
result ^= num
return result
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, your task is to find the number that appears an odd number of times. There will always be only one number with an odd count in the list. Your function should return this number.\n\nFor example:\n\n```python\nfind_odd([20, 1, 1, 2, 2, 3, 3, 20, 4, 20, 4, 5, 5])\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1792,
"level": 1,
"question": "Given a list of integers, your task is to find the number that appears an odd number of times. There will always be only one number with an odd count in the list. Your function should return this number.\n\nFor example:\n\n```python\nfind_odd([20, 1, 1... |
def inventory_balancing(n, supply, demand):
return sum(supply) == sum(demand) | simplelr_Code_Contests | [
{
"content": "Question:\n**Python: Inventory Balancing**\n\n**problem**\n\nImagine you are managing an inventory system for a warehouse. You have a list of products, each with a specific demand and current supply. Your task is to determine if it is possible to balance the inventory, meaning that each product's ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1793,
"level": 1,
"question": "**Python: Inventory Balancing**\n\n**problem**\n\nImagine you are managing an inventory system for a warehouse. You have a list of products, each with a specific demand and current supply. Your task is to determine if it is possible to balance the inve... |
def word_frequency(s):
words = s.split()
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
return word_counts | simplelr_Filter | [
{
"content": "Question:\nWrite a simple Python function that converts a string containing words separated by spaces into a dictionary, where each key is a word and its value is the number of times it appears in the string. This is also known as creating a word frequency dictionary.\nAnswer:\nLet's think step by... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1794,
"level": 1,
"question": "Write a simple Python function that converts a string containing words separated by spaces into a dictionary, where each key is a word and its value is the number of times it appears in the string. This is also known as creating a word frequency dictio... |
def sort_names(names):
return sorted(names, key=lambda x: x.lower()) | simplelr_Filter | [
{
"content": "Question:\n### Efficient sorting of a list of strings containing only first names.\n\n**Task:**\n\nWrite a function `sort_names(names)` that sorts a list of strings containing only first names in alphabetical order efficiently.\n\n**Note:**\n\n- Each name in the list is separated by a space.\n- Th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1795,
"level": 1,
"question": "### Efficient sorting of a list of strings containing only first names.\n\n**Task:**\n\nWrite a function `sort_names(names)` that sorts a list of strings containing only first names in alphabetical order efficiently.\n\n**Note:**\n\n- Each name in the ... |
def process_student_records(students: list[dict]) -> dict:
total_students = 0
sum_ages = 0
grades_distribution = {}
status_count = {'active': 0, 'inactive': 0}
for student in students:
total_students += 1
sum_ages += student['age']
grade = student['grade']
... | simplelr_Docs | [
{
"content": "Question:\n**Question:**\n\nImplement a function in Python that processes a list of student records and returns a summary based on specific criteria. You are expected to use control flow statements, functions, and proper parameter handling to solve this problem.\n\n### Problem Description\nYou are... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1796,
"level": 1,
"question": "**Question:**\n\nImplement a function in Python that processes a list of student records and returns a summary based on specific criteria. You are expected to use control flow statements, functions, and proper parameter handling to solve this problem.\... |
def return_if_true(bool_param, num_param):
return num_param if bool_param else 0 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a boolean and a number then returns the number if the boolean is true, otherwise it returns 0.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1797,
"level": 1,
"question": "Create a function that takes a boolean and a number then returns the number if the boolean is true, otherwise it returns 0.",
"split": "train"
} |
import os
import shutil
def organize_files_by_extension(directory_path: str) -> dict:
try:
# List all non-hidden files in the directory
files = [entry for entry in os.scandir(directory_path) if entry.is_file() and not entry.name.startswith('.')]
if not files:
return {"success": ... | simplelr_Algorithm | [
{
"content": "Question:\n### File Organizer\n\n**Objective**: Implement a function to organize files in a given directory based on their file extensions, creating subdirectories for each type and moving the files accordingly.\n\n**Scenario**: In a scenario where you need to manage a cluttered directory with dif... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1798,
"level": 1,
"question": "### File Organizer\n\n**Objective**: Implement a function to organize files in a given directory based on their file extensions, creating subdirectories for each type and moving the files accordingly.\n\n**Scenario**: In a scenario where you need to ma... |
def max_profit_days(prices):
if len(prices) < 2:
return (-1, -1)
min_price = prices[0]
min_price_index = 0
max_profit = -float('inf')
best_buy = -1
best_sell = -1
for i in range(1, len(prices)):
current_price = prices[i]
if current_price < min_price:
... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with writing a function to simulate and analyze a sequence of stock prices. The aim is to determine the best day to buy and the best day to sell to maximize profit. If there's no profit to be gained, the function should return (-1, -1).\n\nBelow are the function specifica... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1799,
"level": 1,
"question": "You are tasked with writing a function to simulate and analyze a sequence of stock prices. The aim is to determine the best day to buy and the best day to sell to maximize profit. If there's no profit to be gained, the function should return (-1, -1).\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.