target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
from typing import List
def apply_discount(prices: List[float], discount: float) -> List[float]:
return [round(price * (1 - discount / 100), 2) for price in prices] | simplelr_Evol | [
{
"content": "Question:\nAn online retailer is offering a discount on certain products. You are provided with a list of product prices and a discount percentage. Write a Python function `apply_discount` that takes in the list of prices and the discount percentage, and returns a new list where each price is redu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7400,
"level": 1,
"question": "An online retailer is offering a discount on certain products. You are provided with a list of product prices and a discount percentage. Write a Python function `apply_discount` that takes in the list of prices and the discount percentage, and returns ... |
def unique_elements(data):
unique = []
seen = []
for element in data:
key = (type(element), element)
if key not in seen:
unique.append(element)
seen.append(key)
return unique | simplelr_Evol | [
{
"content": "Question:\nCreate a function in Python that takes in a list of mixed data types (integers, floats, and strings) and returns a new list where only the unique elements are kept, maintaining the original order. If an element appears more than once, only its first occurrence should be retained.\n\n**R... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7401,
"level": 1,
"question": "Create a function in Python that takes in a list of mixed data types (integers, floats, and strings) and returns a new list where only the unique elements are kept, maintaining the original order. If an element appears more than once, only its first oc... |
def common_elements(list1, list2):
# Determine the smaller and larger lists
if len(list1) <= len(list2):
smaller = list1
larger = list2
else:
smaller = list2
larger = list1
# Create a frequency dictionary of the smaller list
freq = {}
for num in smaller:
... | simplelr_Filter | [
{
"content": "Question:\nWrite a code that takes two lists of integers as input and returns a new list which contains only the common elements between the two lists, without using any built-in Python functions (e.g. set(), intersect(), etc.). The code should be implemented with time complexity in mind.\nAnswer:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7402,
"level": 1,
"question": "Write a code that takes two lists of integers as input and returns a new list which contains only the common elements between the two lists, without using any built-in Python functions (e.g. set(), intersect(), etc.). The code should be implemented wit... |
def edit_distance(s: str, t: str) -> int:
m = len(s)
n = len(t)
# Create a 2D list with (m+1) rows and (n+1) columns initialized to 0
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Initialize the first row and column
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou need to create a function that determines the minimum number of operations required to convert a given string `s` into another string `t`, where both strings consist of only lowercase letters. The allowed operations are:\n\n1. Inserting a character\n2. Delet... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7403,
"level": 1,
"question": "### Problem Statement\n\nYou need to create a function that determines the minimum number of operations required to convert a given string `s` into another string `t`, where both strings consist of only lowercase letters. The allowed operations are:\n\... |
def can_form_palindrome(s: str, k: int) -> bool:
if k == 0:
return s == s[::-1]
else:
freq = {}
for c in s:
if c in freq:
freq[c] += 1
else:
freq[c] = 1
odd_counts = sum(1 for count in freq.values() if count % 2 != 0)
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are given a string `s` consisting of lowercase letters and an integer `k`. You need to determine if you can form a palindrome by rearranging the string `s` exactly `k` times. Each rearrangement allows you to move each character to a different position, but you... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7404,
"level": 1,
"question": "### Problem Statement\nYou are given a string `s` consisting of lowercase letters and an integer `k`. You need to determine if you can form a palindrome by rearranging the string `s` exactly `k` times. Each rearrangement allows you to move each charact... |
from typing import List
def min_max_normalize(data: List[float], new_min: float, new_max: float) -> List[float]:
if not data:
return []
data_min = min(data)
data_max = max(data)
if data_min == data_max:
return [new_min] * len(data)
else:
range_data = data_max - data_min
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\n\nYou are implementing a feature that normalizes a given set of numerical data to a specified range for use in a machine learning model. Specifically, you need to create a function that takes in a list of real numbers and two parameters, `new_min` and `new_max`, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7405,
"level": 1,
"question": "### Problem Statement:\n\nYou are implementing a feature that normalizes a given set of numerical data to a specified range for use in a machine learning model. Specifically, you need to create a function that takes in a list of real numbers and two pa... |
import re
def extract_phone_numbers(text):
# Define the regex pattern to match the specified phone number formats
pattern = re.compile(r'''
# Match +1 (XXX) XXX-XXXX
\+1\s\(\d{3}\)\s\d{3}-\d{4}
|
# Match +1 XXX XXX XXXX
\+1\s\d{3}\s\d{3}\s\d{4}
|
# Match ... | simplelr_Filter | [
{
"content": "Question:\nThis problem is to write a Python script to identify and extract phone numbers from a given text string. The script should handle various common phone number formats.\n\n**Requirements:**\n\n* Input: A single line of text containing a phone number.\n* Output: A list containing all the p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7406,
"level": 1,
"question": "This problem is to write a Python script to identify and extract phone numbers from a given text string. The script should handle various common phone number formats.\n\n**Requirements:**\n\n* Input: A single line of text containing a phone number.\n* ... |
def find_first_duplicate(nums):
"""
This function finds the first duplicate in a given list of integers.
Args:
nums (list): A list of integers.
Returns:
int or None: The first duplicate in the list, or None if there are no duplicates.
"""
seen = set()
for num in nums:
... | simplelr_Filter | [
{
"content": "Question:\nI have been working on this problem and I've made some progress, but I've gotten stuck. \nWrite a function that takes in a list of integers and returns the first duplicate in the list. \n\nFor example, given the list [2, 1, 3, 5, 3, 2], the function should return 3 because it's the firs... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7407,
"level": 1,
"question": "I have been working on this problem and I've made some progress, but I've gotten stuck. \nWrite a function that takes in a list of integers and returns the first duplicate in the list. \n\nFor example, given the list [2, 1, 3, 5, 3, 2], the function sh... |
import math
def lcm(a, b):
if a == 0 or b == 0:
return 0
return abs(a * b) // math.gcd(a, b) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the smallest common multiple (SCM) or least common multiple (LCM) of two numbers. The function should take two integers as input and return the LCM of these integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7408,
"level": 1,
"question": "Write a python function to find the smallest common multiple (SCM) or least common multiple (LCM) of two numbers. The function should take two integers as input and return the LCM of these integers.",
"split": "train"
} |
def count_digits(n: int) -> int:
if n == 0:
return 1
return len(str(abs(n))) | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Counting Digits in Large Numbers\n\nYou have been hired as a software developer at a financial analytics company. One of your tasks is to develop a function to analyze large numeric data efficiently. One step in this analysis involves quickly computing the number of digits... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7409,
"level": 1,
"question": "### Question: Counting Digits in Large Numbers\n\nYou have been hired as a software developer at a financial analytics company. One of your tasks is to develop a function to analyze large numeric data efficiently. One step in this analysis involves qui... |
def maximum_product_of_three_numbers(x):
sorted_x = sorted(x)
product1 = sorted_x[-1] * sorted_x[-2] * sorted_x[-3]
product2 = sorted_x[0] * sorted_x[1] * sorted_x[-1]
return max(product1, product2) | simplelr_Apps | [
{
"content": "Question:\nYou are given an array of integers (x). Write a function to find the maximum product of any three numbers from the array. Your function should handle both positive and negative numbers, and the result should be the highest possible product of any triplet in the array.\n\nFor example:\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7410,
"level": 1,
"question": "You are given an array of integers (x). Write a function to find the maximum product of any three numbers from the array. Your function should handle both positive and negative numbers, and the result should be the highest possible product of any tripl... |
def shortest_to_char(s: str, c: str) -> list[int]:
n = len(s)
distances = [n] * n # Initialize with a value larger than any possible distance
# Left to right pass
last_seen = -1
for i in range(n):
if s[i] == c:
last_seen = i
distances[i] = 0
else:
... | simplelr_Apps | [
{
"content": "Question:\nGiven a string `s` consisting of lowercase alphabets and a character `c`, you need to construct a new string where each character in the new string is the shortest distance from that character in the input string to the character `c`. The distance between two indices `i` and `j` is `|i ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7411,
"level": 1,
"question": "Given a string `s` consisting of lowercase alphabets and a character `c`, you need to construct a new string where each character in the new string is the shortest distance from that character in the input string to the character `c`. The distance betw... |
def hasPairWithSum(A, K):
seen = set()
for num in A:
complement = K - num
if complement in seen:
return "True"
seen.add(num)
return "False"
| simplelr_Taco | [
{
"content": "Question:\nYou are given an array of integers, $A$, and an integer, $K$. Write a program to determine if there are two distinct indices $i$ and $j$ in the array such that $A[i] + A[j] = K$.\n\nFunction Description\n\nComplete the `hasPairWithSum` function in the editor below.\n\n`hasPairWithSum` h... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7412,
"level": 1,
"question": "You are given an array of integers, $A$, and an integer, $K$. Write a program to determine if there are two distinct indices $i$ and $j$ in the array such that $A[i] + A[j] = K$.\n\nFunction Description\n\nComplete the `hasPairWithSum` function in the ... |
from collections import defaultdict
def subarray_sum(arr, target):
sum_counts = defaultdict(int)
sum_counts[0] = 1 # Initialize with 0 to handle subarrays starting from index 0
current_sum = 0
count = 0
for num in arr:
current_sum += num
# Check how many times (current_sum - target... | simplelr_Package | [
{
"content": "Question:\nWrite a function `subarray_sum` that calculates the number of continuous subarrays whose sum equals a given target value. A subarray is a contiguous part of an array.\n\n#### Function Specification\n- Function Name: `subarray_sum`\n- Parameters:\n - `arr` (List[int]): A list of integer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7413,
"level": 1,
"question": "Write a function `subarray_sum` that calculates the number of continuous subarrays whose sum equals a given target value. A subarray is a contiguous part of an array.\n\n#### Function Specification\n- Function Name: `subarray_sum`\n- Parameters:\n - `... |
def third_largest_unique(A):
unique = list(set(A))
unique.sort(reverse=True)
if len(unique) < 3:
return unique[0]
else:
return unique[2]
| simplelr_Taco | [
{
"content": "Question:\nYou are given an array of integers. Write a function that returns the third largest unique value in the array. If the array has less than three unique values, return the largest unique value.\n\n-----Input-----\n- An array of integers, $A$, where $1 \\leq \\text{length of } A \\leq 10^5... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7414,
"level": 1,
"question": "You are given an array of integers. Write a function that returns the third largest unique value in the array. If the array has less than three unique values, return the largest unique value.\n\n-----Input-----\n- An array of integers, $A$, where $1 \\... |
def longest_word(sentence):
words = sentence.split()
if not words:
return ''
longest = words[0]
max_length = len(longest)
for word in words[1:]:
current_length = len(word)
if current_length > max_length:
longest = word
max_length = current_length
r... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the longest word in a given sentence. If there are multiple words with the same maximum length, return the one that appears first in the sentence.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7415,
"level": 1,
"question": "Write a function to find the longest word in a given sentence. If there are multiple words with the same maximum length, return the one that appears first in the sentence.",
"split": "train"
} |
def most_frequent_element(arr):
if not arr:
return None # or raise ValueError("Array is empty")
freq = {}
for num in arr:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
return max(freq, key=freq.get) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer array as input and returns the array element that occurred the most number of times.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7416,
"level": 1,
"question": "Create a function that takes an integer array as input and returns the array element that occurred the most number of times.",
"split": "train"
} |
def mostFrequentEven(nums):
even_counts = {}
for num in nums:
if num % 2 == 0:
if num in even_counts:
even_counts[num] += 1
else:
even_counts[num] = 1
if not even_counts:
return -1
max_freq = max(even_counts.values())
candidates... | simplelr_Leetcode | [
{
"content": "Question:\nWrite a function `mostFrequentEven` that takes in a list of integers `nums` and returns the most frequent even element in the list. If there is a tie, return the smallest even element among the tied elements. If there are no even elements in the list, return -1.\n\nFor example:\n- Given... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7417,
"level": 1,
"question": "Write a function `mostFrequentEven` that takes in a list of integers `nums` and returns the most frequent even element in the list. If there is a tie, return the smallest even element among the tied elements. If there are no even elements in the list, ... |
def filter_range(arr, start, end):
lower = min(start, end)
higher = max(start, end)
result = [num for num in arr if lower <= num <= higher]
result.sort()
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes three arguments: an array of integers, and two integers representing a range. The function should return a list of all integers from the array that fall within the specified range, inclusive. Ensure that the returned list is sorted in ascending order.\nAnswe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7418,
"level": 1,
"question": "Create a function that takes three arguments: an array of integers, and two integers representing a range. The function should return a list of all integers from the array that fall within the specified range, inclusive. Ensure that the returned list i... |
def sort_strings(words_list, reverse=False):
return sorted(words_list, reverse=reverse) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to sort a list of strings. The function should take two parameters: `words_list` (a list of strings) and `reverse` (a boolean indicating whether to sort the list in descending order). If `reverse` is False, the function should return the list sorted in ascending ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7419,
"level": 1,
"question": "Write a python function to sort a list of strings. The function should take two parameters: `words_list` (a list of strings) and `reverse` (a boolean indicating whether to sort the list in descending order). If `reverse` is False, the function should r... |
import math
def num_digits(n: int) -> int:
if n == 0:
return 1
n_abs = abs(n)
return int(math.floor(math.log10(n_abs)) + 1) | simplelr_Data_Structure | [
{
"content": "Question:\nSuppose you are given an integer. Write a function to determine the number of digits in the integer using logarithmic methods. Your function should handle both positive and negative integers gracefully. You should ensure that zero is also accounted for correctly.\n\n**Function Signature... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7420,
"level": 1,
"question": "Suppose you are given an integer. Write a function to determine the number of digits in the integer using logarithmic methods. Your function should handle both positive and negative integers gracefully. You should ensure that zero is also accounted for... |
from typing import List, Tuple
def text_editor(operations: List[Tuple[str, str]]) -> str:
stack = []
for op, value in operations:
if op == "add":
stack.append(value)
elif op == "undo" and stack:
stack.pop()
return ''.join(stack) | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nWrite a function that simulates a simple text editor capable of recognizing and performing text deletion and undo operations. The text editor should only support two operations: \"add\" to add a string of text at the end, and \"undo\" to undo the last operation pe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7421,
"level": 1,
"question": "### Problem Statement\nWrite a function that simulates a simple text editor capable of recognizing and performing text deletion and undo operations. The text editor should only support two operations: \"add\" to add a string of text at the end, and \"u... |
def selection_sort(numbers):
numbers_copy = numbers.copy()
for i in range(len(numbers_copy)):
min_index = i
for j in range(i + 1, len(numbers_copy)):
if numbers_copy[j] < numbers_copy[min_index]:
min_index = j
numbers_copy[i], numbers_copy[min_index] = numbers... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program to sort a list of numbers in ascending order using the selection sort algorithm. The program should take a list of integers as input and return the sorted list. Additionally, include a brief explanation of how the selection sort algorithm works.\nAnswer:\nLet's th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7422,
"level": 1,
"question": "Write a Python program to sort a list of numbers in ascending order using the selection sort algorithm. The program should take a list of integers as input and return the sorted list. Additionally, include a brief explanation of how the selection sort ... |
def isProductiveDay(t, m):
consecutive_ws = 0
for char in t:
if char == 'W':
consecutive_ws += 1
if consecutive_ws > m:
return False
else:
consecutive_ws = 0
return True
| simplelr_Taco | [
{
"content": "Question:\nA recent study suggests keeping track of daily activities to improve productivity. Activities are categorized into 'W' (for work) and 'R' (for rest). Given a string `t` representing a sequence of activities throughout the day and an integer `m` representing the maximum number of consecu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7423,
"level": 1,
"question": "A recent study suggests keeping track of daily activities to improve productivity. Activities are categorized into 'W' (for work) and 'R' (for rest). Given a string `t` representing a sequence of activities throughout the day and an integer `m` represe... |
def filter_long_strings(lst):
return [s for s in lst if len(s) > 5] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of strings and returns a new list containing only the strings that have more than 5 characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7424,
"level": 1,
"question": "Create a function that takes a list of strings and returns a new list containing only the strings that have more than 5 characters.",
"split": "train"
} |
def repeat_string(s, n):
if n < 1:
return
for _ in range(n):
print(s) | simplelr_Filter | [
{
"content": "Question:\nBuild a Python function that takes a string and an integer as input and prints the string the number of times specified by the integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7425,
"level": 1,
"question": "Build a Python function that takes a string and an integer as input and prints the string the number of times specified by the integer.",
"split": "train"
} |
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return (seen[complement], i)
seen[num] = i
return None | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums` and an integer `target`, find two distinct indices `i` and `j` in the array such that `nums[i] + nums[j] = target`. Return the indices `(i, j)` as a tuple. If no such indices exist, return `None`.\nAnswer:\nLet's think step by step.\n",
"role": "use... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7426,
"level": 1,
"question": "Given an array of integers `nums` and an integer `target`, find two distinct indices `i` and `j` in the array such that `nums[i] + nums[j] = target`. Return the indices `(i, j)` as a tuple. If no such indices exist, return `None`.",
"split": "train"
... |
def rotate_matrix_right(arr, steps):
if not arr:
return arr
rotated = []
for row in arr:
if not row:
rotated.append(row)
continue
n = len(row)
k = steps % n
if k == 0:
rotated.append(row.copy())
else:
rotated_row... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python program that rotates the elements of a two-dimensional array to the right by a given number of steps.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7427,
"level": 1,
"question": "Create a Python program that rotates the elements of a two-dimensional array to the right by a given number of steps.",
"split": "train"
} |
from typing import List
def max_subarray_sum(arr: List[int]) -> int:
if not arr:
return 0 # According to the problem statement, the array is non-empty, so this case is redundant but included for safety.
current_max = max_so_far = arr[0]
for num in arr[1:]:
current_max = max(num, ... | simplelr_Taco | [
{
"content": "Question:\nEmma is working on a project that involves processing a large amount of numerical data. She needs to identify the largest contiguous subarray within a one-dimensional array of numbers that has the maximum sum. However, due to constraints on memory, Emma needs a solution that operates wi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7428,
"level": 1,
"question": "Emma is working on a project that involves processing a large amount of numerical data. She needs to identify the largest contiguous subarray within a one-dimensional array of numbers that has the maximum sum. However, due to constraints on memory, Emm... |
def find_min_max(nums):
if not nums:
return (None, None)
return (min(nums), max(nums)) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `find_min_max` that takes a list of integers and returns a tuple containing the minimum and maximum values from the list. If the list is empty, the function should return `(None, None)`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7429,
"level": 1,
"question": "Write a Python function `find_min_max` that takes a list of integers and returns a tuple containing the minimum and maximum values from the list. If the list is empty, the function should return `(None, None)`.",
"split": "train"
} |
def filter_less_than(numbers, x):
return [num for num in numbers if num < x] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two parameters: a list of numbers and a number 'x'. The function should return a new list that contains only the elements from the original list that are less than 'x'.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7430,
"level": 1,
"question": "Create a function that takes two parameters: a list of numbers and a number 'x'. The function should return a new list that contains only the elements from the original list that are less than 'x'.",
"split": "train"
} |
def concatenate_words(words):
if not words:
return ""
return ' '.join(words) | simplelr_Evol | [
{
"content": "Question:\nGiven a list of words, write a Python function that will concatenate all the words into a single string, with each word separated by a single space. If the list is empty, the function should return an empty string.\n\nSample Input:\n```\n['hello', 'world']\n```\nSample Output:\n```\n'he... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7431,
"level": 1,
"question": "Given a list of words, write a Python function that will concatenate all the words into a single string, with each word separated by a single space. If the list is empty, the function should return an empty string.\n\nSample Input:\n```\n['hello', 'wor... |
def length_of_longest_substring(s):
start = 0
max_len = 0
max_start = 0
char_dict = {}
for end, char in enumerate(s):
if char in char_dict:
# Update start to be the maximum of current start or one past the last occurrence of char
start = max(start, char_dict[char] + ... | simplelr_Filter | [
{
"content": "Question:\nGiven a string, find the longest substring with no repeating characters.\n\nExample:\n\nInput: \"abcabcbb\"\nOutput: \"abc\"\n\nInput: \"bbbbb\"\nOutput: \"\"\n\nInput: \"pwwkew\"\nOutput: \"pwk\"\n\nInput: \"abcdefghijklmnopqrstuvwxyz\"\nOutput: \"abcdefghijklmnopqrstuvwxyz\"\n\nHere i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7432,
"level": 1,
"question": "Given a string, find the longest substring with no repeating characters.\n\nExample:\n\nInput: \"abcabcbb\"\nOutput: \"abc\"\n\nInput: \"bbbbb\"\nOutput: \"\"\n\nInput: \"pwwkew\"\nOutput: \"pwk\"\n\nInput: \"abcdefghijklmnopqrstuvwxyz\"\nOutput: \"abc... |
def sum_distinct_even_numbers(numbers: list[int]) -> int:
"""
Sums the distinct even numbers from the given list of integers.
Parameters:
numbers (list of int): A list of integers which may contain duplicates and odd numbers.
Returns:
int: The sum of distinct even numbers.
Rai... | simplelr_Algorithm | [
{
"content": "Question:\n### Implementation Question: Advanced List Processing for Summation of Distinct Even Numbers\n\n**Problem Statement**:\nYou are given a list of integers. Write a function named `sum_distinct_even_numbers` that sums up the distinct even numbers from the list. The function should ensure t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7433,
"level": 1,
"question": "### Implementation Question: Advanced List Processing for Summation of Distinct Even Numbers\n\n**Problem Statement**:\nYou are given a list of integers. Write a function named `sum_distinct_even_numbers` that sums up the distinct even numbers from the... |
from typing import List, Tuple, Optional
def one_sparse(stream: List[Tuple[int, str]]) -> Optional[int]:
counts = {}
for num, sign in stream:
if sign == '+':
counts[num] = counts.get(num, 0) + 1
else:
counts[num] = counts.get(num, 0) - 1
non_zero = [k for k, v in cou... | simplelr_Data_Structure | [
{
"content": "Question:\n### 1-Sparse Stream Processor Challenge\n\n**Background**:\n\nYou are provided with a continuous stream of tuples. Each tuple contains a non-negative integer and a sign ('+' or '-'). The objective is to process this stream to determine if the stream is 1-sparse, meaning that after cance... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7434,
"level": 1,
"question": "### 1-Sparse Stream Processor Challenge\n\n**Background**:\n\nYou are provided with a continuous stream of tuples. Each tuple contains a non-negative integer and a sign ('+' or '-'). The objective is to process this stream to determine if the stream is... |
def find_over_neighbor_vertices(g, nt):
result = []
for i in range(len(g)):
if len(g[i]) > nt:
result.append(i)
return result | simplelr_Filter | [
{
"content": "Question:\nWe are given an adjacency list representation `g` of a graph and a positive integer `nt`. Let's assume that `g` is a collection of sets, where `g[i]` is a set of all vertices directly connected to vertex `i`. We want to find all the vertices that have more neighbors than `nt`. We will c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7435,
"level": 1,
"question": "We are given an adjacency list representation `g` of a graph and a positive integer `nt`. Let's assume that `g` is a collection of sets, where `g[i]` is a set of all vertices directly connected to vertex `i`. We want to find all the vertices that have ... |
import csv
def calculate_average_scores(file_path: str) -> dict:
result = {}
try:
with open(file_path, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip the header row
for row in reader:
name = row[0]
scores = row[1:]
... | simplelr_Algorithm | [
{
"content": "Question:\n## Task\nWrite a Python function that reads in a CSV (Comma Separated Values) file containing student names and their respective scores across various subjects, then calculates and returns the average score for each student.\n\n## Input\n* A string representing the file path to a CSV fi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7436,
"level": 1,
"question": "## Task\nWrite a Python function that reads in a CSV (Comma Separated Values) file containing student names and their respective scores across various subjects, then calculates and returns the average score for each student.\n\n## Input\n* A string rep... |
def move_zeros(array: list) -> list:
non_zeros = []
zeros = []
for item in array:
if isinstance(item, (int, float)) and item == 0 and not isinstance(item, bool):
zeros.append(item)
else:
non_zeros.append(item)
return non_zeros + zeros | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with implementing a function that rearranges an input list by moving all zero elements to the end of the list, while preserving the order of the other elements. This task involves straight-forward list manipulation but requires careful management of different data types a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7437,
"level": 1,
"question": "You are tasked with implementing a function that rearranges an input list by moving all zero elements to the end of the list, while preserving the order of the other elements. This task involves straight-forward list manipulation but requires careful m... |
from collections import deque
def longest_contiguous_segment(heights, h):
if not heights:
return 0
max_deque = deque()
min_deque = deque()
left = 0
max_len = 0
for right in range(len(heights)):
# Update max_deque
while max_deque and heights[right] >= heights[ma... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `heights` where `heights[i]` represents the height of the `i-th` building in a row of buildings. You want to select a contiguous segment of buildings such that the difference between the maximum height and the minimum height in that segment is minimize... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7438,
"level": 1,
"question": "You are given an array of integers `heights` where `heights[i]` represents the height of the `i-th` building in a row of buildings. You want to select a contiguous segment of buildings such that the difference between the maximum height and the minimum... |
def missingNumber(nums):
n = len(nums)
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` containing `n` distinct numbers in the range `[0, n]`. Implement a function to return the only number in the range that is missing from the array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7439,
"level": 1,
"question": "You are given an integer array `nums` containing `n` distinct numbers in the range `[0, n]`. Implement a function to return the only number in the range that is missing from the array.",
"split": "train"
} |
def count_occurrences(elements: list) -> dict:
"""
Returns a dictionary with the counts of each unique element in the given list.
"""
occurrence_dict = {}
for element in elements:
if element in occurrence_dict:
occurrence_dict[element] += 1
else:
occurrence_di... | simplelr_Algorithm | [
{
"content": "Question:\n### Number Occurrence Counting Function\n\n#### Context:\nIn various programming scenarios, analyzing the frequency of elements in a list can be valuable. Whether it's counting votes, tracking survey responses, or analyzing repeated elements, understanding how often each item appears is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7440,
"level": 1,
"question": "### Number Occurrence Counting Function\n\n#### Context:\nIn various programming scenarios, analyzing the frequency of elements in a list can be valuable. Whether it's counting votes, tracking survey responses, or analyzing repeated elements, understan... |
def sum_of_even_numbers(numbers):
total = 0
for num in numbers:
if num % 2 == 0:
total += num
return total | simplelr_Filter | [
{
"content": "Question:\nThis problem requires you to write a Python function that takes a list of integers as input and returns the sum of all the even numbers in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7441,
"level": 1,
"question": "This problem requires you to write a Python function that takes a list of integers as input and returns the sum of all the even numbers in the list.",
"split": "train"
} |
def reverse_string(s):
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse a string in Python. The function should take a string `s` as input and return the reversed string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7442,
"level": 1,
"question": "Write a function to reverse a string in Python. The function should take a string `s` as input and return the reversed string.",
"split": "train"
} |
import bisect
def max_valid_lineup(heights):
tails = []
for x in heights:
idx = bisect.bisect_left(tails, x)
if idx == len(tails):
tails.append(x)
else:
tails[idx] = x
return len(tails) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array `heights` of n integers, where `heights[i]` represents the height of the `ith` person. A group of people standing in a row where each person is strictly taller than the person in front forms a valid lineup. Find the maximum number of people that can form a valid l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7443,
"level": 1,
"question": "You are given an array `heights` of n integers, where `heights[i]` represents the height of the `ith` person. A group of people standing in a row where each person is strictly taller than the person in front forms a valid lineup. Find the maximum numbe... |
def product_except_self(nums):
n = len(nums)
if n == 0:
return []
left = [1] * n
for i in range(1, n):
left[i] = left[i-1] * nums[i-1]
right = [1] * n
for i in range(n-2, -1, -1):
right[i] = right[i+1] * nums[i+1]
result = [left[i] * right[i] for i in r... | simplelr_Filter | [
{
"content": "Question:\nGiven a list of integers, write a Python function to calculate the product of all elements in the list except for the element at the current index. The solution should not use division and should have a time complexity of O(n). For example, if the input list is [1, 2, 3, 4], the output ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7444,
"level": 1,
"question": "Given a list of integers, write a Python function to calculate the product of all elements in the list except for the element at the current index. The solution should not use division and should have a time complexity of O(n). For example, if the inpu... |
def optimalRelayRace(speeds, laps):
n = len(speeds)
robots = []
for i in range(n):
t = laps[i] / speeds[i]
robots.append((t, i))
robots.sort()
order = [i + 1 for (t, i) in robots]
return order
| simplelr_Taco | [
{
"content": "Question:\nA robotics team is organizing a relay race. Each robot is assigned a speed rating and needs to complete a specified number of laps around a track in the minimum total time. However, the track can only accommodate one robot at a time.\n\nGiven the speed ratings of the robots and the numb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7445,
"level": 1,
"question": "A robotics team is organizing a relay race. Each robot is assigned a speed rating and needs to complete a specified number of laps around a track in the minimum total time. However, the track can only accommodate one robot at a time.\n\nGiven the speed... |
def is_anagram(s, t):
if len(s) != len(t):
return False
return sorted(s) == sorted(t) | simplelr_Filter | [
{
"content": "Question:\nGiven two strings, s and t, write a Python program to check if t is an anagram of s.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7446,
"level": 1,
"question": "Given two strings, s and t, write a Python program to check if t is an anagram of s.",
"split": "train"
} |
import time
import numpy as np
def analyze_model_performance(models, X_train, y_train, X_test, y_test):
performance = {}
for model_info in models:
model = model_info['model']
model_name = model_info['name']
# Train the model
model.fit(X_train, y_train)
... | simplelr_Docs | [
{
"content": "Question:\n**Objective**: The goal of this assessment is to evaluate your understanding of scikit-learn's computational performance and your ability to implement a function that optimizes and measures prediction latency and throughput.\n\n### Problem Statement\n\nYou are required to implement a Py... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7447,
"level": 1,
"question": "**Objective**: The goal of this assessment is to evaluate your understanding of scikit-learn's computational performance and your ability to implement a function that optimizes and measures prediction latency and throughput.\n\n### Problem Statement\n\... |
def filter_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0] | simplelr_Filter | [
{
"content": "Question:\nI need help with a Python function that processes a list of integers and returns a new list containing only the even numbers from the original list. How can I achieve this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7448,
"level": 1,
"question": "I need help with a Python function that processes a list of integers and returns a new list containing only the even numbers from the original list. How can I achieve this?",
"split": "train"
} |
from collections import Counter
from typing import List
def most_frequent_words(document: str, stop_words: List[str]) -> List[str]:
stop_words_set = set(stop_words)
words = document.split()
filtered_words = []
for word in words:
lower_word = word.lower()
if lower_word not in stop_words_... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are developing a system for analyzing and categorizing text documents. One common task in this process is to determine the most frequently occurring words in a document after removing a set of \"stop words.\" Stop words are common words that are often remove... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7449,
"level": 1,
"question": "### Problem Statement\n\nYou are developing a system for analyzing and categorizing text documents. One common task in this process is to determine the most frequently occurring words in a document after removing a set of \"stop words.\" Stop words are... |
def sum_of_digits(n):
return sum(int(d) for d in str(abs(n))) | simplelr_Filter | [
{
"content": "Question:\nCan you provide an example of a Python function that calculates the sum of digits of an integer?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7450,
"level": 1,
"question": "Can you provide an example of a Python function that calculates the sum of digits of an integer?",
"split": "train"
} |
def calculate_statistics(numbers: list[int]) -> dict:
# Calculate the mean
mean = sum(numbers) / len(numbers)
# Calculate the median
sorted_nums = sorted(numbers)
n = len(sorted_nums)
if n % 2 == 1:
median = sorted_nums[n // 2]
else:
median = (sorted_nums[n // 2 - 1] + s... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with writing a function named `calculate_statistics` that processes a list of integers and returns a dictionary containing the mean, median, and mode of the list. The function should handle cases where there can be more than one mode (multiple values that appear with the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7451,
"level": 1,
"question": "You are tasked with writing a function named `calculate_statistics` that processes a list of integers and returns a dictionary containing the mean, median, and mode of the list. The function should handle cases where there can be more than one mode (mu... |
def remove_odd_indices(s):
return s[::2] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns a new string with the characters at odd indices removed.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7452,
"level": 1,
"question": "Write a Python function that takes a string as input and returns a new string with the characters at odd indices removed.",
"split": "train"
} |
def length_of_longest_substring(s):
char_map = {}
left = 0
max_length = 0
n = len(s)
for right in range(n):
char = s[right]
if char in char_map and char_map[char] >= left:
left = char_map[char] + 1
char_map[char] = right
current_length = right - left + 1
... | simplelr_Leetcode | [
{
"content": "Question:\nImplement a function that takes a string `s` and returns the length of the longest substring that contains only unique characters. For example, given the string `\"abcabcbb\"`, the function should return `3` because the longest substring with all unique characters is `\"abc\"`. If the s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7453,
"level": 1,
"question": "Implement a function that takes a string `s` and returns the length of the longest substring that contains only unique characters. For example, given the string `\"abcabcbb\"`, the function should return `3` because the longest substring with all uniqu... |
def three_sum(nums, target):
nums.sort()
n = len(nums)
for i in range(n - 2):
left = i + 1
right = n - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
if current_sum == target:
return True
elif current_sum < t... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers `nums` and an integer `target`. Your task is to determine if there exist three distinct elements in `nums` such that the sum of the three elements is equal to `target`. Return `true` if such a combination exists, otherwise return `false`.\nAnswer:\nLet's... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7454,
"level": 1,
"question": "You are given a list of integers `nums` and an integer `target`. Your task is to determine if there exist three distinct elements in `nums` such that the sum of the three elements is equal to `target`. Return `true` if such a combination exists, otherw... |
def common_words(titles):
if not titles:
return []
# Split each title into words, convert to lowercase, and store as a set
word_sets = []
for title in titles:
words = title.split()
lower_words = [word.lower() for word in words]
word_sets.append(set(lower_words))
... | simplelr_Apps | [
{
"content": "Question:\nYou are given a list of strings, each representing a book title. Your task is to write a function `common_words(titles)` that takes this list as input and returns a list of words that are common in all the given book titles. Only whole words should be considered, and the case should be ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7455,
"level": 1,
"question": "You are given a list of strings, each representing a book title. Your task is to write a function `common_words(titles)` that takes this list as input and returns a list of words that are common in all the given book titles. Only whole words should be ... |
def find_target_index(lst, target):
for index, value in enumerate(lst):
if value == target:
return index
return "Target not found" | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts two arguments: a list of integers and a target integer. The function should return the index of the target if it is found in the list. If the target is not found, the function should return \"Target not found\".\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7456,
"level": 1,
"question": "Create a function that accepts two arguments: a list of integers and a target integer. The function should return the index of the target if it is found in the list. If the target is not found, the function should return \"Target not found\".",
"spli... |
def sort_tuples(tuples):
return sorted(tuples, key=lambda x: (-x[0], x[1])) | simplelr_Filter | [
{
"content": "Question:\nConsidering a list of tuples as the input where each tuple contains two integers, your task is to write a Python function that sorts this list of tuples in descending order based on the first value of each tuple, but in the case of a tie, it should sort the tuples based on the second va... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7457,
"level": 1,
"question": "Considering a list of tuples as the input where each tuple contains two integers, your task is to write a Python function that sorts this list of tuples in descending order based on the first value of each tuple, but in the case of a tie, it should sor... |
def sum_adjacent_pairs(arr):
if len(arr) <= 1:
return []
result = []
for i in range(len(arr) - 1):
result.append(arr[i] + arr[i + 1])
return result | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes an array of integers and returns an array containing the sum of each pair of adjacent integers. If the input array has a length of 1 or less, return an empty array.\n\nExample: `[4, 2, 6, 3]` should return `[6, 8, 9]`\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7458,
"level": 1,
"question": "Write a function that takes an array of integers and returns an array containing the sum of each pair of adjacent integers. If the input array has a length of 1 or less, return an empty array.\n\nExample: `[4, 2, 6, 3]` should return `[6, 8, 9]`",
"s... |
from typing import List
def shell_sort(arr: List[int]) -> List[int]:
n = len(arr)
if n == 0:
return arr
gaps = []
h = 1
while h < n:
gaps.append(h)
h = 3 * h + 1
gaps.reverse()
for gap in gaps:
for i in range(gap, n):
temp = arr[i]
... | simplelr_Data_Structure | [
{
"content": "Question:\nShell Sort Implementation\n\n**Scenario**:\n\nYou are part of a team developing a high-performance custom sorting library for a financial application. You are tasked with implementing an efficient sorting algorithm that can handle nearly sorted datasets with a mixture of numerical value... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7459,
"level": 1,
"question": "Shell Sort Implementation\n\n**Scenario**:\n\nYou are part of a team developing a high-performance custom sorting library for a financial application. You are tasked with implementing an efficient sorting algorithm that can handle nearly sorted dataset... |
import os
import shutil
def move_file(source, destination):
"""
Moves a file from the source path to the destination directory.
Args:
source (str): The path to the file to be moved.
destination (str): The directory where the file will be moved.
Raises:
FileNotFoundErro... | simplelr_Filter | [
{
"content": "Question:\nI want to create a Python function that moves a file from one directory to another while handling exceptions. How can I do this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7460,
"level": 1,
"question": "I want to create a Python function that moves a file from one directory to another while handling exceptions. How can I do this?",
"split": "train"
} |
def reverse_string_to_list(s):
# Reverse the string using slicing
reversed_str = s[::-1]
# Convert the reversed string into a list of characters
return list(reversed_str)
# Example usage:
print(reverse_string_to_list("hello")) # Output: ['o', 'l', 'l', 'e', 'h'] | simplelr_Filter | [
{
"content": "Question:\nI have a Python programming project and I'm struggling with a specific function. The function is supposed to reverse a string and then convert it into a list of characters, but I'm not sure if I'm doing it right. Can you help me write a Python function that takes a string as input, reve... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7461,
"level": 1,
"question": "I have a Python programming project and I'm struggling with a specific function. The function is supposed to reverse a string and then convert it into a list of characters, but I'm not sure if I'm doing it right. Can you help me write a Python function... |
def binary_search_first_occurrence(arr, target):
low = 0
high = len(arr) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
result = mid
high = mid - 1 # Continue searching left for earlier occurrence
elif arr[mid] < target:... | simplelr_Filter | [
{
"content": "Question:\nLet's say we have an array of integers sorted in ascending order, `[1, 2, 3, 4, 5, 6, 7, 8, 9]`. We want to find the index of the first occurrence of a given number, say `5`, in the array. If the element is not found, return `-1`. \n\nCan you implement a binary search algorithm to accom... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7462,
"level": 1,
"question": "Let's say we have an array of integers sorted in ascending order, `[1, 2, 3, 4, 5, 6, 7, 8, 9]`. We want to find the index of the first occurrence of a given number, say `5`, in the array. If the element is not found, return `-1`. \n\nCan you implement... |
import torch
def batched_euclidean_norm(tensor: torch.Tensor, dtype: torch.dtype = torch.float32) -> torch.Tensor:
"""
Computes the Euclidean norm (L2 norm) for each vector in a batch,
handling different numerical precisions.
Args:
tensor (torch.Tensor): Input tensor of shape (batch_size, num_... | simplelr_Docs | [
{
"content": "Question:\nHandling Numerical Stability in Batched Tensor Computations\n\n#### Objective\n\nYour task is to write a PyTorch function that computes the Euclidean norm (L2 norm) of batched vectors, ensuring numerical stability for both small and large values in the vectors. Additionally, you should ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7463,
"level": 1,
"question": "Handling Numerical Stability in Batched Tensor Computations\n\n#### Objective\n\nYour task is to write a PyTorch function that computes the Euclidean norm (L2 norm) of batched vectors, ensuring numerical stability for both small and large values in the... |
def find_keyword(s):
keywords = [('Cloud', 5), ('SaaS', 4), ('PaaS', 4)]
for i in range(len(s)):
for keyword, length in keywords:
if i + length > len(s):
continue
if s[i:i+length] == keyword:
return (keyword, i)
return "No match" | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to check for the existence of any one of the three keywords 'Cloud', 'SaaS', or 'PaaS' in a given string. The function should return the first occurring keyword and its index in the string. If none of the keywords are found, the function should return \"No match\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7464,
"level": 1,
"question": "Write a Python function to check for the existence of any one of the three keywords 'Cloud', 'SaaS', or 'PaaS' in a given string. The function should return the first occurring keyword and its index in the string. If none of the keywords are found, the... |
def num_rolls_to_target(n, target):
min_sum = n
max_sum = 6 * n
if target < min_sum or target > max_sum:
return 0
dp = [0] * (max_sum + 1)
dp[0] = 1 # Base case: 0 dice, sum 0
for _ in range(n):
next_dp = [0] * (max_sum + 1)
for current_sum in range(len(dp)):
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven two integers `n` and `target`, write a function to compute the number of ways to roll `n` six-sided dice so that the sum of the numbers on the dice is exactly `target`. Each die roll results in an integer between `1` and `6` (inclusive). The function should return the number of po... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7465,
"level": 1,
"question": "Given two integers `n` and `target`, write a function to compute the number of ways to roll `n` six-sided dice so that the sum of the numbers on the dice is exactly `target`. Each die roll results in an integer between `1` and `6` (inclusive). The func... |
from typing import List, Optional, Dict
def calculate_total(prices: List[float], discount: Optional[Dict[str, float]] = None) -> float:
total = sum(prices)
if discount is not None:
if 'amount' in discount:
total -= discount['amount']
elif 'percentage' in discount:
discou... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are developing an e-commerce platform, and one of the features is to calculate the total price of items in a shopping cart, considering potential discounts. Users can apply discount coupons, which may either take a fixed amount off the cart total or reduce the total pr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7466,
"level": 1,
"question": "### Scenario\nYou are developing an e-commerce platform, and one of the features is to calculate the total price of items in a shopping cart, considering potential discounts. Users can apply discount coupons, which may either take a fixed amount off th... |
def max_subarray_sum(arr):
if not arr:
return 0 # Handles empty array case, assuming 0 is the expected return value
max_current = max_global = arr[0]
for num in arr[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_cur... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum subarray sum in a given array of integers. Use Kadane's algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7467,
"level": 1,
"question": "Write a python function to find the maximum subarray sum in a given array of integers. Use Kadane's algorithm.",
"split": "train"
} |
from typing import List
import itertools
def generate_words(alphabets: List[str], n: int) -> List[str]:
"""
This function generates all possible n-letter words using the given array
of unique alphabets in dictionary order.
Args:
alphabets (List[str]): List of unique alphabets.
n (int): The... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are assigned to create a function that generates all possible n-letter words from a given array of unique alphabets. The generated words must follow dictionary ordering.\n\n### Function Specification\n\nImplement the following function:\n```python\ndef gener... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7468,
"level": 1,
"question": "### Problem Statement\n\nYou are assigned to create a function that generates all possible n-letter words from a given array of unique alphabets. The generated words must follow dictionary ordering.\n\n### Function Specification\n\nImplement the follow... |
def longest_palindromic_substring(s):
if not s:
return ""
max_length = 1
max_start = 0
n = len(s)
for i in range(n):
# Odd length palindromes
l, r = i, i
while l >= 0 and r < n and s[l] == s[r]:
if r - l + 1 > max_length:
max_leng... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that accepts a string and returns the longest palindromic substring within that string. A palindrome is a sequence of characters which reads the same backward as forward. If the string is empty or there's no palindromic substring, return an empty string.\n\nYour functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7469,
"level": 1,
"question": "Write a function that accepts a string and returns the longest palindromic substring within that string. A palindrome is a sequence of characters which reads the same backward as forward. If the string is empty or there's no palindromic substring, retu... |
def elementwise_multiplication(A, B):
if len(A) != len(B):
raise ValueError("Arrays must be of the same length.")
return [a * b for a, b in zip(A, B)] | simplelr_Filter | [
{
"content": "Question:\nDesign a computational routine that accepts a pair of numerical arrays as input and generates a fresh array. The output array should encoded the product of each element from the two input arrays, respectively. This routine should incorporate an element-wise multiplication operation perf... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7470,
"level": 1,
"question": "Design a computational routine that accepts a pair of numerical arrays as input and generates a fresh array. The output array should encoded the product of each element from the two input arrays, respectively. This routine should incorporate an element... |
def isPatternValid(s: str, p: list[int]) -> bool:
n = len(s)
freq = [0] * 26
current_unique = 0
for i in range(n):
c = s[i]
idx = ord(c) - ord('a')
if freq[idx] == 0:
current_unique += 1
freq[idx] += 1
if current_unique != p[i]:
return Fal... | simplelr_Taco | [
{
"content": "Question:\nGiven a string s and an array p of the same length. The array p indicates the number of unique characters that should be in the substring starting from the beginning of s for that length of the substring. \nYour task is to determine whether the string s meets the conditions described by... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7471,
"level": 1,
"question": "Given a string s and an array p of the same length. The array p indicates the number of unique characters that should be in the substring starting from the beginning of s for that length of the substring. \nYour task is to determine whether the string ... |
def highest_spending_users(transactions):
if not transactions:
return []
max_amount = max(amt for _, amt in transactions)
users = set()
for user, amt in transactions:
if amt == max_amount:
users.add(user)
return sorted(users) | simplelr_Code_Contests | [
{
"content": "Question:\nA popular e-commerce company wishes to analyze the shopping patterns of its users. They maintain a record of user transactions in a list where each element is a tuple containing a user ID and the amount spent on a purchase. The company wants to reward the users who spend the highest amo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7472,
"level": 1,
"question": "A popular e-commerce company wishes to analyze the shopping patterns of its users. They maintain a record of user transactions in a list where each element is a tuple containing a user ID and the amount spent on a purchase. The company wants to reward ... |
from collections import deque
def min_time_to_exit(grid):
if not grid or not grid[0]:
return -1
m = len(grid)
n = len(grid[0])
q = deque()
dist = [[-1 for _ in range(n)] for _ in range(m)]
# Collect all exit positions and initialize queue
for i in range(m):
fo... | simplelr_Taco | [
{
"content": "Question:\nIn a grid of size `m x n`, each cell in the grid can have one of three values: `0` representing an empty cell, `1` representing an occupant, or `2` representing an exit. \n\nAn occupant can move in four possible directions: up, down, left, or right. Each move to an adjacent cell costs 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7473,
"level": 1,
"question": "In a grid of size `m x n`, each cell in the grid can have one of three values: `0` representing an empty cell, `1` representing an occupant, or `2` representing an exit. \n\nAn occupant can move in four possible directions: up, down, left, or right. Ea... |
def process_string(s):
result = []
present = set()
for c in s:
if c in present:
result.remove(c)
present.remove(c)
else:
result.append(c)
present.add(c)
return ''.join(result) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters. You need to create a new string based on the following rules:\n1. Traverse the string `s` from left to right.\n2. For each character `c` encountered in the string:\n - If `c` is not already in the new string, append `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7474,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters. You need to create a new string based on the following rules:\n1. Traverse the string `s` from left to right.\n2. For each character `c` encountered in the string:\n - If `c` is not ... |
import numpy as np
def generate_frames(imgs):
output = imgs.copy()
output[:, 0, :] = 255
output[:, -1, :] = 255
output[:, :, 0] = 255
output[:, :, -1] = 255
return output | simplelr_Filter | [
{
"content": "Question:\nIn this problem, you will write a function generate-frames that takes a small set of input images. The function should take as input a 3D numpy array with a shape of (n_images, height, width), representing n_images images, each of size height x width pixels. The input images are graysca... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7475,
"level": 1,
"question": "In this problem, you will write a function generate-frames that takes a small set of input images. The function should take as input a 3D numpy array with a shape of (n_images, height, width), representing n_images images, each of size height x width p... |
def merge_sorted_lists(list1, list2):
i = j = 0
result = []
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
result.append(list1[i])
i += 1
else:
result.append(list2[j])
j += 1
# Add the remaining elements of list1 and list... | simplelr_Evol | [
{
"content": "Question:\nDesign a function named `merge_sorted_lists` that takes two parameters: `list1` and `list2`, both of which are lists containing integers sorted in ascending order. The function should merge these two lists into a single sorted list and return it. Ensure your solution has a linear runtim... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7476,
"level": 1,
"question": "Design a function named `merge_sorted_lists` that takes two parameters: `list1` and `list2`, both of which are lists containing integers sorted in ascending order. The function should merge these two lists into a single sorted list and return it. Ensur... |
def productExceptSelf(arr):
n = len(arr)
if n == 0:
return []
prefix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * arr[i-1]
suffix = [1] * n
for i in range(n-2, -1, -1):
suffix[i] = suffix[i+1] * arr[i+1]
result = [prefix[i] * suffix[i] for ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` of length `n`. Your task is to return an array of the same length where each element at index `i` is the product of all elements in the original array except the one at `i`. Write a function `productExceptSelf(arr)` that takes in an array of inte... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7477,
"level": 1,
"question": "You are given an array of integers `arr` of length `n`. Your task is to return an array of the same length where each element at index `i` is the product of all elements in the original array except the one at `i`. Write a function `productExceptSelf(a... |
def remove_stop_words(stop_words, word_counts):
stop_words_set = set(stop_words)
result = {}
for word, count in word_counts.items():
if word not in stop_words_set:
result[word] = count
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes two arguments: `stop_words` and `word_counts`. `stop_words` is a list of words that should be removed from `word_counts`. `word_counts` is a dictionary where keys are words and values are their respective counts. The function should return a new dictio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7478,
"level": 1,
"question": "Write a Python function that takes two arguments: `stop_words` and `word_counts`. `stop_words` is a list of words that should be removed from `word_counts`. `word_counts` is a dictionary where keys are words and values are their respective counts. The ... |
def longest_unique_substring(s: str) -> str:
char_index_map = {}
start = 0
max_len = 0
max_substr = ""
for i, char in enumerate(s):
if char in char_index_map and char_index_map[char] >= start:
start = char_index_map[char] + 1
char_index_map[char] = i
if i - s... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with implementing a function to perform string manipulation operations to determine the longest substring consisting of non-repeating characters. This exercise will help you enhance your string manipulation skills and ability to work with different data structures in Pyth... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7479,
"level": 1,
"question": "You are tasked with implementing a function to perform string manipulation operations to determine the longest substring consisting of non-repeating characters. This exercise will help you enhance your string manipulation skills and ability to work wit... |
def count_skybridges(grid, k):
if not grid:
return 0
rows = len(grid)
cols = len(grid[0])
count = 0
for i in range(rows):
for j in range(cols):
# Check right neighbor
if j + 1 < cols:
diff = abs(grid[i][j] - grid[i][j+1])
if dif... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a 2D grid of integers `grid` representing a structured city layout, where each cell within the grid represents a building with a specific height. Each building has a unique height and the city authorities want to construct skybridges between the buildings. A skybridge can ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7480,
"level": 1,
"question": "You are given a 2D grid of integers `grid` representing a structured city layout, where each cell within the grid represents a building with a specific height. Each building has a unique height and the city authorities want to construct skybridges betw... |
def rotate_in_place(mat):
if not mat:
return
n = len(mat)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
# Reverse each row
for row in mat:
row.reverse() | simplelr_Data_Structure | [
{
"content": "Question:\n### Matrix Rotation Coding Question\n\nYou are given an `n x n` 2D matrix `mat` representing an image. Your task is to write a function `rotate_in_place(mat)` that rotates the image by 90 degrees clockwise in-place. Ensure that your solution is efficient both in terms of time and space ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7481,
"level": 1,
"question": "### Matrix Rotation Coding Question\n\nYou are given an `n x n` 2D matrix `mat` representing an image. Your task is to write a function `rotate_in_place(mat)` that rotates the image by 90 degrees clockwise in-place. Ensure that your solution is efficie... |
def repeat_string_with_char(s, n, c):
return c.join([s] * n) if n > 0 else '' | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes three parameters - a string, a number n, and a character. The function should return a new string where the given string is repeated n times and the character is placed between each repetition.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7482,
"level": 1,
"question": "Create a function that takes three parameters - a string, a number n, and a character. The function should return a new string where the given string is repeated n times and the character is placed between each repetition.",
"split": "train"
} |
from typing import List
def find_missing_number(nums: List[int]) -> int:
n = len(nums) + 1
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum | simplelr_Algorithm | [
{
"content": "Question:\n### Find the Missing Number in a Sequence\n\n#### Objective\nWrite a function that finds the missing number in a sequence from 1 to n.\n\n#### Function Signature\n```python\ndef find_missing_number(nums: List[int]) -> int:\n```\n\n#### Parameters\n* `nums` (List[int]): A list of unique ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7483,
"level": 1,
"question": "### Find the Missing Number in a Sequence\n\n#### Objective\nWrite a function that finds the missing number in a sequence from 1 to n.\n\n#### Function Signature\n```python\ndef find_missing_number(nums: List[int]) -> int:\n```\n\n#### Parameters\n* `n... |
def is_anagram_of_substring(s1: str, s2: str) -> bool:
s1 = s1.lower()
s2 = s2.lower()
len_s1, len_s2 = len(s1), len(s2)
if len_s2 == 0:
return True
if len_s2 > len_s1:
return False
# Frequency arrays for s2 and the current window in s1
freq_s2 = [0] * 26
f... | simplelr_Filter | [
{
"content": "Question:\nGiven two strings s1 and s2, how can you check if s2 is an anagram of any substring of s1? Your solution should have a time complexity of O(n) and a space complexity of O(1). It should also handle cases where both strings contain uppercase and lowercase letters. In addition, assume that... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7484,
"level": 1,
"question": "Given two strings s1 and s2, how can you check if s2 is an anagram of any substring of s1? Your solution should have a time complexity of O(n) and a space complexity of O(1). It should also handle cases where both strings contain uppercase and lowercas... |
def intersect(list1, list2):
return [element for element in list1 if element in list2]
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
print(intersect(list1, list2)) | simplelr_Filter | [
{
"content": "Question:\ndef intersect(list1, list2):\n return [element for element in list1 if element in list2]\n\nlist1 = [1, 2, 3, 4, 5]\nlist2 = [4, 5, 6, 7, 8]\nprint(intersect(list1, list2))\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7485,
"level": 1,
"question": "def intersect(list1, list2):\n return [element for element in list1 if element in list2]\n\nlist1 = [1, 2, 3, 4, 5]\nlist2 = [4, 5, 6, 7, 8]\nprint(intersect(list1, list2))",
"split": "train"
} |
import heapq
from typing import List
def dijkstra_min_heap(graph: List[List[int]], src: int) -> List[int]:
"""
Implement an enhanced version of Dijkstra's algorithm using a min-heap to find the shortest paths from a source vertex to all other vertices.
Args:
graph: A 2D list representing the adjacency... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Implement Enhanced Dijkstra's Algorithm Using Min-Heap\n\n#### Context\nDijkstra's algorithm is a popular shortest path algorithm widely used in networking and pathfinding. The basic O(V^2) implementation, though easier to understand and implement, can be inefficient for l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7486,
"level": 1,
"question": "### Question: Implement Enhanced Dijkstra's Algorithm Using Min-Heap\n\n#### Context\nDijkstra's algorithm is a popular shortest path algorithm widely used in networking and pathfinding. The basic O(V^2) implementation, though easier to understand and ... |
def rank_students(students):
students.sort(key=lambda x: (-x[1], x[0].lower()))
return [student[0] for student in students]
# Example usages
print(rank_students([("Alice", 91), ("Bob", 88), ("Charlie", 88), ("Dave", 91)]))
# Output: ['Alice', 'Dave', 'Bob', 'Charlie']
print(rank_students([("Elena", 95), ("Fay... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\nWrite a function `rank_students` that processes a list of student names and their corresponding grades, then returns a list of student names sorted by their grades in descending order. If two students have the same grade, they should be sorted alphabetically by their names... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7487,
"level": 1,
"question": "### Question\nWrite a function `rank_students` that processes a list of student names and their corresponding grades, then returns a list of student names sorted by their grades in descending order. If two students have the same grade, they should be s... |
import urllib.request
import urllib.parse
from urllib.error import HTTPError, URLError
def fetch_url(url: str, method: str = "GET", data: dict = None, headers: dict = None) -> str:
method = method.upper()
headers = headers or {}
if method == 'POST':
if data is not None:
data = urll... | simplelr_Docs | [
{
"content": "Question:\n### URL Fetching and Error Handling\n\nYou are required to implement a Python function `fetch_url`, which retrieves the content of the given URL. This function should support both GET and POST requests and allow custom headers to be specified. Additionally, the function should handle di... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7488,
"level": 1,
"question": "### URL Fetching and Error Handling\n\nYou are required to implement a Python function `fetch_url`, which retrieves the content of the given URL. This function should support both GET and POST requests and allow custom headers to be specified. Addition... |
def cumulative_sum(nums: list) -> list:
total = 0
result = []
for num in nums:
total += num
result.append(total)
return result
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of integers as an input and returns a new list where each element is the sum of itself and all previous elements in the original list. This process is often called a 'cumulative sum'.\n\nFor example, given the list `[1, 2, 3, 4]`, the function should r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7489,
"level": 1,
"question": "Write a function that takes a list of integers as an input and returns a new list where each element is the sum of itself and all previous elements in the original list. This process is often called a 'cumulative sum'.\n\nFor example, given the list `[... |
def extract_odd_numbers(numbers):
return [num for num in numbers if num % 2 != 0] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to extract the odd numbers from a list of integers and return them in a new list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7490,
"level": 1,
"question": "Write a python function to extract the odd numbers from a list of integers and return them in a new list.",
"split": "train"
} |
def occupied_rooms(reservations, date):
count = 0
for check_in, check_out in reservations:
if check_in <= date <= check_out:
count += 1
return count | simplelr_Codeforces | [
{
"content": "Question:\nA famous hotel management system stores reservations in an array of tuples, where each tuple contains two integers: the check-in day and the check-out day (both inclusive). Given a specific date, determine the total number of rooms occupied on that day.\n\nYour task is to write a functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7491,
"level": 1,
"question": "A famous hotel management system stores reservations in an array of tuples, where each tuple contains two integers: the check-in day and the check-out day (both inclusive). Given a specific date, determine the total number of rooms occupied on that day... |
def minIncrements(T):
if not T:
return 0
total = 0
for i in range(1, len(T)):
if T[i] < T[i-1]:
needed = T[i-1] - T[i]
total += needed
T[i] = T[i-1]
return total
| simplelr_Taco | [
{
"content": "Question:\nYou are a tax collector in a city where people live in a row of houses numbered from 1 to N. Every day you collect taxes from these houses. The tax amount for each house is represented by an array T where $T[i]$ is the tax at the house numbered $i$. You are required to ensure that the c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7492,
"level": 1,
"question": "You are a tax collector in a city where people live in a row of houses numbered from 1 to N. Every day you collect taxes from these houses. The tax amount for each house is represented by an array T where $T[i]$ is the tax at the house numbered $i$. Yo... |
from collections import Counter
def have_same_elements(list1, list2):
return Counter(list1) == Counter(list2) | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python to check if two lists have the same elements regardless of their order. The elements in the lists will be strings consisting of lowercase letters only, and each element will have a length between 1 and 20 characters inclusive. The lists can have at most 1000 e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7493,
"level": 1,
"question": "Write a function in Python to check if two lists have the same elements regardless of their order. The elements in the lists will be strings consisting of lowercase letters only, and each element will have a length between 1 and 20 characters inclusive... |
def sort_dict_by_value(input_dict):
items = list(input_dict.items())
sorted_items = sorted(items, key=lambda x: x[1])
return sorted_items | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function `sort_dict_by_value` that takes a dictionary as input and returns a list of tuples. Each tuple should contain a key-value pair from the dictionary, and the resulting list should be sorted by its values in ascending order. This function helps you prac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7494,
"level": 1,
"question": "You are required to write a function `sort_dict_by_value` that takes a dictionary as input and returns a list of tuples. Each tuple should contain a key-value pair from the dictionary, and the resulting list should be sorted by its values in ascending ... |
def filter_products(products, min_price, max_price, category, in_stock):
filtered = []
for product in products:
if (product['price'] >= min_price and product['price'] <= max_price and
(category is None or product['category'] == category) and
product['in_stock'] == in_stock):
... | simplelr_Package | [
{
"content": "Question:\nYou are asked to write a function that processes a list of dictionaries containing information about various products and filters the list based on specific criteria. The function should return a new list containing only the dictionaries that meet the given conditions. Here are the deta... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7495,
"level": 1,
"question": "You are asked to write a function that processes a list of dictionaries containing information about various products and filters the list based on specific criteria. The function should return a new list containing only the dictionaries that meet the ... |
def can_be_sorted(nums):
return True | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums` of length `n` where all elements are unique, you are allowed to perform the following operations on the array:\n\n* Swap any two elements.\n* Reverse any subarray of the array.\n\nYou need to determine if it is possible to sort the array `nums` in ascending... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7496,
"level": 1,
"question": "Given an integer array `nums` of length `n` where all elements are unique, you are allowed to perform the following operations on the array:\n\n* Swap any two elements.\n* Reverse any subarray of the array.\n\nYou need to determine if it is possible to... |
def longest_substring_k_distinct(s: str) -> int:
if not s:
return 0
freq = {}
left = 0
max_length = 0
for right in range(len(s)):
char = s[right]
freq[char] = freq.get(char, 0) + 1
# If the number of distinct characters exceeds 2, shrink the window
... | simplelr_Algorithm | [
{
"content": "Question:\n**Problem Statement**:\nGiven a string consisting of lowercase English letters, you are tasked with finding the length of the longest substring that contains at most two distinct characters. Write a function to implement this logic efficiently.\n\n**Function Signature**:\n```python\ndef... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7497,
"level": 1,
"question": "**Problem Statement**:\nGiven a string consisting of lowercase English letters, you are tasked with finding the length of the longest substring that contains at most two distinct characters. Write a function to implement this logic efficiently.\n\n**Fu... |
def min_bounding_box(points):
if not points:
return None
first = points[0]
dim = len(first)
mins = list(first)
maxs = list(first)
for p in points[1:]:
for i in range(dim):
if p[i] < mins[i]:
mins[i] = p[i]
elif p[i] > maxs[i]:
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to compute the Minimum Bounding Box (MBB) for a set of points in 2D or 3D space. The function should take a list of points as input and return the smallest rectangle or parallelepiped that encloses all the points.\nAnswer:\nLet's think step by step.\n",
"role": "use... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7498,
"level": 1,
"question": "Write a function to compute the Minimum Bounding Box (MBB) for a set of points in 2D or 3D space. The function should take a list of points as input and return the smallest rectangle or parallelepiped that encloses all the points.",
"split": "train"
... |
import re
import keyword
def is_valid_function_definition(s):
pattern = r'^def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\):$'
match = re.match(pattern, s)
if match:
func_name = match.group(1)
if not keyword.iskeyword(func_name):
return True
return False | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as an argument and checks if it is a valid Python function definition. A valid function definition should start with the `def` keyword, followed by a valid function name, and include a set of parentheses with any valid arguments. The function defini... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7499,
"level": 1,
"question": "Create a function that takes a string as an argument and checks if it is a valid Python function definition. A valid function definition should start with the `def` keyword, followed by a valid function name, and include a set of parentheses with any v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.