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 strings_with_vowels(strings):
vowels = {'a', 'e', 'i', 'o', 'u'}
result = []
for s in strings:
if any(c.lower() in vowels for c in s):
result.append(s)
return result | simplelr_Evol | [
{
"content": "Question:\nCreate a function in Python that takes a list of strings and returns a new list containing only the strings that have at least one vowel (a, e, i, o, or u). Ensure the function maintains the original order of the strings.\n\nExample:\n\n```python\ndef strings_with_vowels(strings):\n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4900,
"level": 1,
"question": "Create a function in Python that takes a list of strings and returns a new list containing only the strings that have at least one vowel (a, e, i, o, or u). Ensure the function maintains the original order of the strings.\n\nExample:\n\n```python\ndef ... |
def int_to_roman(num):
val = [
(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')
]
res = ''
for (i, r) in val:
while num >= i:
res += r
num ... | simplelr_Apps | [
{
"content": "Question:\nWrite a Python function that takes an integer as input and returns a string representing the Roman numeral equivalent of that integer. The input integer will be in the range from 1 to 3999.\n\nExamples:\n\n```python\nint_to_roman(1) # returns 'I'\nint_to_roman(3999) # returns 'MMMCMXCIX... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4901,
"level": 1,
"question": "Write a Python function that takes an integer as input and returns a string representing the Roman numeral equivalent of that integer. The input integer will be in the range from 1 to 3999.\n\nExamples:\n\n```python\nint_to_roman(1) # returns 'I'\nint_... |
def int_to_binary_string(n):
return format(n, 'b') | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in an integer, n, and returns a binary string representation of that number. The binary string should be the shortest possible, not padded with extra zeros.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4902,
"level": 1,
"question": "Create a function that takes in an integer, n, and returns a binary string representation of that number. The binary string should be the shortest possible, not padded with extra zeros.",
"split": "train"
} |
def evaluate_rpn(tokens):
stack = []
for token in tokens:
if token in '+-*/':
a = stack.pop()
b = stack.pop()
if token == '+':
res = b + a
elif token == '-':
res = b - a
elif token == '*':
res = b... | simplelr_Apps | [
{
"content": "Question:\nCreate a function that evaluates an arithmetic expression in Reverse Polish Notation (RPN).\n\nYour function will receive an array of strings representing the expression.\n\n## Assumptions:\n\n* The array will contain only valid arithmetic expressions.\n* The array will contain integers... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4903,
"level": 1,
"question": "Create a function that evaluates an arithmetic expression in Reverse Polish Notation (RPN).\n\nYour function will receive an array of strings representing the expression.\n\n## Assumptions:\n\n* The array will contain only valid arithmetic expressions.... |
from collections import defaultdict
def count_subarrays_with_sum(arr, k):
count = 0
current_sum = 0
sum_counts = defaultdict(int)
sum_counts[0] = 1 # Initialize with 0 to handle subarrays starting from index 0
for num in arr:
current_sum += num
# Check how many times (current_... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to count the number of subarrays whose sum is exactly equal to a given target sum `k`. The array contains both positive and negative integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4904,
"level": 1,
"question": "Write a Python function to count the number of subarrays whose sum is exactly equal to a given target sum `k`. The array contains both positive and negative integers.",
"split": "train"
} |
from collections import deque
from typing import List, Tuple
def is_reachable(vertex_count: int, edges: List[Tuple[int, int]], source: int, target: int) -> bool:
if source == target:
return True
# Build the adjacency list
adjacency = [[] for _ in range(vertex_count)]
for u, v in edges:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Path Verification in Directed Graph\n\nYou are working on a project involving route planning, and you need to verify connectivity between different locations represented by nodes in a directed graph. Your task is to implement a function to determine if there is a path betw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4905,
"level": 1,
"question": "### Question: Path Verification in Directed Graph\n\nYou are working on a project involving route planning, and you need to verify connectivity between different locations represented by nodes in a directed graph. Your task is to implement a function t... |
def calculate_area(length, width):
return length * width | simplelr_Filter | [
{
"content": "Question:\nThe following code is written in Python. It implements a simple function called `calculate_area` that takes the length and width of a rectangle as input and returns the area.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4906,
"level": 1,
"question": "The following code is written in Python. It implements a simple function called `calculate_area` that takes the length and width of a rectangle as input and returns the area.",
"split": "train"
} |
from typing import List
def count_paths(grid: List[List[int]]) -> int:
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
if n == 0:
return 0
if grid[0][0] == 1:
return 0
dp = [[0 for _ in range(n)] for _ in range(m)]
dp[0][0] = 1
for i in range(m):
for j... | simplelr_Algorithm | [
{
"content": "Question:\n### Navigation Path Finder\n\nYou have been hired to create a navigation system for a futuristic city where people use hovercrafts to move around on a grid. In this city, the hovercrafts can only move right or down. Additionally, certain grid cells may be blocked, and hovercrafts cannot... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4907,
"level": 1,
"question": "### Navigation Path Finder\n\nYou have been hired to create a navigation system for a futuristic city where people use hovercrafts to move around on a grid. In this city, the hovercrafts can only move right or down. Additionally, certain grid cells may... |
import torch
def manipulate_and_validate_tensor(n: int) -> bool:
# Create a tensor filled with ones
t = torch.ones(n)
# Clone the tensor's storage
s1 = t.untyped_storage().clone()
# Fill the cloned storage with zeros
s1.fill_(0)
# Update the tensor to use the new storage
t.set_(s1)
... | simplelr_Docs | [
{
"content": "Question:\n### PyTorch Storage Manipulation and Validation\n\nIn this task, you will implement a function in PyTorch to demonstrate understanding of tensor storage manipulation. The function should perform the following operations:\n\n1. **Create a Tensor:** Create a 1-dimensional tensor of size `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4908,
"level": 1,
"question": "### PyTorch Storage Manipulation and Validation\n\nIn this task, you will implement a function in PyTorch to demonstrate understanding of tensor storage manipulation. The function should perform the following operations:\n\n1. **Create a Tensor:** Crea... |
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True | simplelr_Filter | [
{
"content": "Question:\nDevelop an algorithm in Python that determines if a number is prime, but without using any built-in functions or libraries. The algorithm should have a time complexity of O(sqrt(n)).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4909,
"level": 1,
"question": "Develop an algorithm in Python that determines if a number is prime, but without using any built-in functions or libraries. The algorithm should have a time complexity of O(sqrt(n)).",
"split": "train"
} |
def string_lengths(string_list):
return [len(s) for s in string_list] | simplelr_Filter | [
{
"content": "Question:\nHow can I modify a function to accept a list of strings and return a new list containing the lengths of each string in the original list?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4910,
"level": 1,
"question": "How can I modify a function to accept a list of strings and return a new list containing the lengths of each string in the original list?",
"split": "train"
} |
def max_len_substring(s: str, k: int) -> int:
count = {}
left = 0
max_len = 0
unique = 0
for right in range(len(s)):
char = s[right]
if count.get(char, 0) == 0:
unique += 1
count[char] = count.get(char, 0) + 1
while unique > k:
left_char = s[l... | simplelr_Taco | [
{
"content": "Question:\nYou are given a string `s` of length `n` consisting of lowercase English letters. Your goal is to find the maximum length of a substring that contains no more than `k` distinct characters.\n\nFunction Signature:\n```python\ndef max_len_substring(s: str, k: int) -> int:\n pass\n```\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4911,
"level": 1,
"question": "You are given a string `s` of length `n` consisting of lowercase English letters. Your goal is to find the maximum length of a substring that contains no more than `k` distinct characters.\n\nFunction Signature:\n```python\ndef max_len_substring(s: str... |
def make_palindrome(s):
return s + s[::-1] | simplelr_Filter | [
{
"content": "Question:\nThe problem is:\n\nWrite a Python function called `make_palindrome` that takes a string as input and returns a new string that is the input string made into a palindrome. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward.\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4912,
"level": 1,
"question": "The problem is:\n\nWrite a Python function called `make_palindrome` that takes a string as input and returns a new string that is the input string made into a palindrome. A palindrome is a word, phrase, number, or other sequence of characters which rea... |
import re
def basic_calculator(expression):
pattern = r'^\s*([+-]?(?:\d+\.?\d*|\.\d+))\s*([+\-*/])\s*([+-]?(?:\d+\.?\d*|\.\d+))\s*$'
match = re.match(pattern, expression)
if not match:
raise ValueError("Invalid expression")
a = float(match.group(1))
op = match.group(2)
b = flo... | simplelr_Filter | [
{
"content": "Question:\nDevelop a Python function that simulates the behavior of a basic calculator. This function should be able to handle addition, subtraction, multiplication, and division operations. It should take a string input representing a simple mathematical expression and return the result as a floa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4913,
"level": 1,
"question": "Develop a Python function that simulates the behavior of a basic calculator. This function should be able to handle addition, subtraction, multiplication, and division operations. It should take a string input representing a simple mathematical express... |
from collections import Counter
def are_projects_balanced(projects, k):
counts = Counter(projects)
for count in counts.values():
if count <= k:
return False
return True | simplelr_Leetcode | [
{
"content": "Question:\nA company has `n` employees, each assigned to one of several projects. The employees work in teams, and each team is associated with exactly one project. You are given an array `projects` where `projects[i] = pi` indicates the project to which the `i-th` employee is assigned. To ensure ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4914,
"level": 1,
"question": "A company has `n` employees, each assigned to one of several projects. The employees work in teams, and each team is associated with exactly one project. You are given an array `projects` where `projects[i] = pi` indicates the project to which the `i-t... |
def longest_word(s):
words = s.split()
max_length = 0
max_word = ""
for word in words:
current_length = len(word)
if current_length > max_length:
max_length = current_length
max_word = word
return max_word | simplelr_Evol | [
{
"content": "Question:\nGiven a string comprised of a series of space-separated words, identify the word with the maximum length. In case there are multiple words with the same maximum length, return the first occurrence. Implement this without using built-in max() function or any sorting algorithms.\n\nExampl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4915,
"level": 1,
"question": "Given a string comprised of a series of space-separated words, identify the word with the maximum length. In case there are multiple words with the same maximum length, return the first occurrence. Implement this without using built-in max() function o... |
def common_elements(list1, list2):
return list(set(list1) & set(list2)) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that finds the common elements between two lists, and return them as a new list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4916,
"level": 1,
"question": "Create a function that finds the common elements between two lists, and return them as a new list.",
"split": "train"
} |
def merge_sorted_arrays(arr1: list[int], arr2: list[int]) -> list[int]:
i = j = 0
result = []
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
result.append(arr1[i])
i += 1
else:
result.append(arr2[j])
j += 1
# Add remaining el... | simplelr_Package | [
{
"content": "Question:\n**\n\nCreate a function `merge_sorted_arrays` that takes in two pre-sorted arrays (in non-decreasing order) and returns a single array that contains all the elements from both input arrays, sorted in non-decreasing order. \n\nThe specific requirements are:\n\n- **Input:**\n - `arr1`: A... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4917,
"level": 1,
"question": "**\n\nCreate a function `merge_sorted_arrays` that takes in two pre-sorted arrays (in non-decreasing order) and returns a single array that contains all the elements from both input arrays, sorted in non-decreasing order. \n\nThe specific requirements ... |
def max_sum_subarray(arr, k):
if not arr or k == 0 or k > len(arr):
return None # Handle invalid cases
current_sum = sum(arr[:k])
max_sum = current_sum
for i in range(1, len(arr) - k + 1):
current_sum = current_sum - arr[i - 1] + arr[i + k - 1]
if current_sum > max_sum... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum sum of any continuous subarray of size k. The function should return the maximum sum found.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4918,
"level": 1,
"question": "Write a python function to find the maximum sum of any continuous subarray of size k. The function should return the maximum sum found.",
"split": "train"
} |
def replace_special_chars(input_str):
result = []
for c in input_str:
if c.isalnum() or c == ' ':
result.append(c)
else:
result.append(f'&#{ord(c)};')
return ''.join(result)
print(replace_special_chars("Hello~!@#")) # Outputs: Hello~!@# | simplelr_Filter | [
{
"content": "Question:\nI have an input string that can contain special characters, such as ~, !, @, etc. I want to write a Python function that replaces all special characters with their corresponding HTML entity equivalents.\n\nFor example, if the input string is \"Hello~!@#\", the output should be \"Hello&#... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4919,
"level": 1,
"question": "I have an input string that can contain special characters, such as ~, !, @, etc. I want to write a Python function that replaces all special characters with their corresponding HTML entity equivalents.\n\nFor example, if the input string is \"Hello~!@... |
import pandas as pd
def calculate_total_revenue(file_name):
df = pd.read_csv(file_name)
total_revenue = (df['price'] * df['quantity_sold']).sum()
return total_revenue | simplelr_Package | [
{
"content": "Question:\nYou are given a CSV file containing information about various products in a store. The CSV file has three columns: `product_id` (indicating the unique identifier for each product), `price` (indicating the price of the product), and `quantity_sold` (indicating the number of items sold fo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4920,
"level": 1,
"question": "You are given a CSV file containing information about various products in a store. The CSV file has three columns: `product_id` (indicating the unique identifier for each product), `price` (indicating the price of the product), and `quantity_sold` (ind... |
def count_unique_elements(input_list):
unique = []
for num in input_list:
if num not in unique:
unique.append(num)
return [(num, 1) for num in unique] | simplelr_Evol | [
{
"content": "Question:\nCreate a function that takes in a list of integers and returns a list of tuples. Each tuple should contain two elements: the first being an integer from the original list, and the second being the count of how many times that integer appears in the list after any set of possible duplica... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4921,
"level": 1,
"question": "Create a function that takes in a list of integers and returns a list of tuples. Each tuple should contain two elements: the first being an integer from the original list, and the second being the count of how many times that integer appears in the lis... |
def calculate_total_price(items):
total_price = 0.0
for item in items:
total_price += item['price']
return total_price | simplelr_Filter | [
{
"content": "Question:\nThis is my current progress on my Python project.\n\nI have a list of dictionaries representing items. Each dictionary has keys \"name\" and \"price\".\n\n```python\nitems = [\n {\"name\": \"Apple\", \"price\": 1.00},\n {\"name\": \"Banana\", \"price\": 0.50},\n {\"name\": \"Or... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4922,
"level": 1,
"question": "This is my current progress on my Python project.\n\nI have a list of dictionaries representing items. Each dictionary has keys \"name\" and \"price\".\n\n```python\nitems = [\n {\"name\": \"Apple\", \"price\": 1.00},\n {\"name\": \"Banana\", \"p... |
from collections import deque
from typing import List, Tuple
def find_two_sum_pairs(nums: List[int], target: int) -> List[Tuple[int, int]]:
num_map = {}
for idx, num in enumerate(nums):
if num not in num_map:
num_map[num] = deque()
num_map[num].append(idx)
used = set()
... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are provided with an array of integers and a specific target integer. Your task is to write a function `find_two_sum_pairs` that returns indices of all unique pairs of elements in the array such that they add up to the target. Each input will have multiple solutions, and no element ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4923,
"level": 1,
"question": "You are provided with an array of integers and a specific target integer. Your task is to write a function `find_two_sum_pairs` that returns indices of all unique pairs of elements in the array such that they add up to the target. Each input will have ... |
def swap_stack_pairs(stack):
new_stack = []
for i in range(0, len(stack), 2):
if i + 1 < len(stack):
new_stack.append(stack[i+1])
new_stack.append(stack[i])
else:
new_stack.append(stack[i])
return new_stack | simplelr_Data_Structure | [
{
"content": "Question:\n### Stack Pair-Swap Function Implementation\n\n#### Task\nWrite a function `swap_stack_pairs` which takes a stack as input and swaps each pair of successive elements starting from the bottom of the stack. Use an auxiliary storage structure of your choice (either a stack or a queue) to h... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4924,
"level": 1,
"question": "### Stack Pair-Swap Function Implementation\n\n#### Task\nWrite a function `swap_stack_pairs` which takes a stack as input and swaps each pair of successive elements starting from the bottom of the stack. Use an auxiliary storage structure of your choi... |
def twoSum(arr, target):
seen = {}
for i, num in enumerate(arr):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
# As per problem statement, a solution exists, so this return is a placeholder
return []
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers and a target integer, determine the indices of the two unique numbers in the array that add up to the target. Assume exactly one solution exists, and you may not use the same element twice.\n\nExample 1:\nInput:\narr[] = [2, 7, 11, 15],\ntarget = 9\nOutput: \n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4925,
"level": 1,
"question": "Given an array of integers and a target integer, determine the indices of the two unique numbers in the array that add up to the target. Assume exactly one solution exists, and you may not use the same element twice.\n\nExample 1:\nInput:\narr[] = [2, ... |
def sum_of_integers(n):
if n < 1:
return 0
return n * (n + 1) // 2 | simplelr_Filter | [
{
"content": "Question:\nI need to create a Python function that calculates the sum of all integers from 1 to a given number `n`. The function should take an integer `n` as its parameter and return the sum. How can I do this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4926,
"level": 1,
"question": "I need to create a Python function that calculates the sum of all integers from 1 to a given number `n`. The function should take an integer `n` as its parameter and return the sum. How can I do this?",
"split": "train"
} |
def sum_of_list(numbers):
total = 0
for number in numbers:
total += number
return total | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum of all numbers in a given list. In Python, the built-in function `sum()` can be used for this purpose, but let's write a function from scratch. The function should accept a list of integers and return the sum of these integers.\nAnswer:\nLet's think... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4927,
"level": 1,
"question": "Write a function to calculate the sum of all numbers in a given list. In Python, the built-in function `sum()` can be used for this purpose, but let's write a function from scratch. The function should accept a list of integers and return the sum of th... |
def min_shelves(books, shelf_height):
shelves = 0
current_sum = 0
for book in books:
if current_sum + book > shelf_height:
shelves += 1
current_sum = book
else:
current_sum += book
if current_sum > 0:
shelves += 1
return shelves
| simplelr_Taco | [
{
"content": "Question:\nYou are the manager of a burgeoning bookstore, and you want to arrange books on the shelves in a particular order. Each book has a unique height, and each shelf can hold books up to a certain total height. Your aim is to place books such that the height of the books on each shelf adhere... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4928,
"level": 1,
"question": "You are the manager of a burgeoning bookstore, and you want to arrange books on the shelves in a particular order. Each book has a unique height, and each shelf can hold books up to a certain total height. Your aim is to place books such that the heigh... |
def merge_and_sort(arr1, arr2):
merged = arr1 + arr2
merged.sort()
return merged | simplelr_Filter | [
{
"content": "Question:\nWrite a piece of code to merge two arrays into one, ensuring that the resulting array is sorted in ascending order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4929,
"level": 1,
"question": "Write a piece of code to merge two arrays into one, ensuring that the resulting array is sorted in ascending order.",
"split": "train"
} |
def can_make_equal(s, t):
if len(s) != len(t):
return False
return sorted(s) == sorted(t) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings `s` and `t`. You are allowed to perform any number of operations on `s` where in each operation you can swap any two characters within `s`. Return `true` if you can make `s` equal to `t` after performing the operations, and `false` otherwise.\nAnswer:\nLet's th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4930,
"level": 1,
"question": "You are given two strings `s` and `t`. You are allowed to perform any number of operations on `s` where in each operation you can swap any two characters within `s`. Return `true` if you can make `s` equal to `t` after performing the operations, and `f... |
def calculate_lcs(str1, str2):
m = len(str1)
n = len(str2)
# Create a DP table of size (m+1) x (n+1)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i-1] == str2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n**Title**: Implement Longest Common Subsequence (LCS) Calculation\n\n**Context**:\nYou are developing a text comparison tool that highlights differences between two sequences of text. One of the crucial aspects of this tool is to compute the Longest Com... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4931,
"level": 1,
"question": "### Coding Assessment Question\n\n**Title**: Implement Longest Common Subsequence (LCS) Calculation\n\n**Context**:\nYou are developing a text comparison tool that highlights differences between two sequences of text. One of the crucial aspects of this... |
import re
def get_sorted_authors(post):
# Extract all names, stripping whitespace and excluding empty strings
names = [name.strip() for name in re.findall(r'\[(.*?)\]', post) if name.strip()]
# Remove duplicates by converting to a set and then back to a list
unique_names = list(set(names))
# Sort t... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `get_sorted_authors` that takes a string representing the body of a post on a forum, and returns a sorted list of unique author names who have posted in the thread. The author names are assumed to be enclosed within square brackets `[name]` in the post body.\nAns... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4932,
"level": 1,
"question": "Write a Python function `get_sorted_authors` that takes a string representing the body of a post on a forum, and returns a sorted list of unique author names who have posted in the thread. The author names are assumed to be enclosed within square brack... |
def reverse_words(sentence):
words = sentence.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse the order of words in a given sentence. The words in the sentence are separated by spaces. Each word consists of English alphabetic characters. The function should preserve the original case of each letter.\nAnswer:\nLet's think step by step.\n",
"role": ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4933,
"level": 1,
"question": "Write a function to reverse the order of words in a given sentence. The words in the sentence are separated by spaces. Each word consists of English alphabetic characters. The function should preserve the original case of each letter.",
"split": "tra... |
def sort_tuples_by_second_element(tuples_list):
return sorted(tuples_list, key=lambda x: x[1], reverse=True) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to sort a list of tuples based on the second element of each tuple in descending order. You can use any programming language.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4934,
"level": 1,
"question": "Write a function to sort a list of tuples based on the second element of each tuple in descending order. You can use any programming language.",
"split": "train"
} |
def filter_even_numbers(numbers):
even_numbers = [num for num in numbers if num % 2 == 0]
return even_numbers | simplelr_Filter | [
{
"content": "Question:\nThis code defines a function that takes a list of integers as input and returns a new list containing only the even numbers from the input list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4935,
"level": 1,
"question": "This code defines a function that takes a list of integers as input and returns a new list containing only the even numbers from the input list.",
"split": "train"
} |
def reorder_even_odd(nums):
evens = [x for x in nums if x % 2 == 0]
odds = [x for x in nums if x % 2 == 1]
res = []
e_idx = o_idx = 0
for i in range(len(nums)):
if i % 2 == 0:
res.append(evens[e_idx])
e_idx += 1
else:
res.append(odds[o_idx])
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of unique integers `nums` that contains elements ranging from `1` to `n` (both inclusive) in random order. Your task is to **reorder** the elements in `nums` such that all even-indexed positions (`0, 2, 4, ...`) contain even integers and all odd-indexed positions (`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4936,
"level": 1,
"question": "You are given a list of unique integers `nums` that contains elements ranging from `1` to `n` (both inclusive) in random order. Your task is to **reorder** the elements in `nums` such that all even-indexed positions (`0, 2, 4, ...`) contain even intege... |
import string
def word_frequency(text):
frequency = {}
for word in text.split():
cleaned = word.strip(string.punctuation)
if not cleaned:
continue
cleaned = cleaned.lower()
frequency[cleaned] = frequency.get(cleaned, 0) + 1
return frequency | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string of text and returns the frequency of each word in the string. The function should handle punctuation and be case-insensitive.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4937,
"level": 1,
"question": "Create a function that takes a string of text and returns the frequency of each word in the string. The function should handle punctuation and be case-insensitive.",
"split": "train"
} |
def isValid(s: str) -> bool:
if len(s) % 2 != 0:
return False
stack = []
closing_to_opening = {')': '(', '}': '{', ']': '['}
for char in s:
if char in closing_to_opening.values():
stack.append(char)
else:
if not stack:
return Fals... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Problem Statement:\n\nYou are given a string `s` consisting of only the characters '(', ')', '{', '}', '[' and ']', and you need to decide if the string forms a valid set of nested parentheses. A string is considered valid if:\n1. Open brackets mus... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4938,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Problem Statement:\n\nYou are given a string `s` consisting of only the characters '(', ')', '{', '}', '[' and ']', and you need to decide if the string forms a valid set of nested parentheses. A string is conside... |
def min_add_to_make_valid(s: str) -> int:
required_open = 0
balance = 0
for c in s:
if c == '(':
balance += 1
else:
balance -= 1
if balance < 0:
required_open += (-balance)
balance = 0
required_close = balance
return required_op... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nA coding competition is held where participants are given a sequence of bracket symbols, consisting of open and close round brackets, and are required to balance them by inserting the fewest number of additional bracket symbols. \n\nThe task is to determine the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4939,
"level": 1,
"question": "### Problem Statement\n\nA coding competition is held where participants are given a sequence of bracket symbols, consisting of open and close round brackets, and are required to balance them by inserting the fewest number of additional bracket symbols... |
from collections import deque
def nodes_on_same_level(tree):
n = len(tree)
if n == 0:
return []
result = [0] * n
queue = deque([0])
while queue:
level_size = len(queue)
for _ in range(level_size):
node = queue.popleft()
result[node] = level_size
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a binary tree with `n` nodes. Return a list of length `n`, where the `i-th` entry in the list is the number of nodes that are on the same level as the `i-th node` in a level-order traversal. Each node in the tree has a unique value from `0` to `n-1`, and the tree is repres... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4940,
"level": 1,
"question": "You are given a binary tree with `n` nodes. Return a list of length `n`, where the `i-th` entry in the list is the number of nodes that are on the same level as the `i-th node` in a level-order traversal. Each node in the tree has a unique value from `... |
def greet_names(names):
"""
Prints a greeting message for each name in the provided list.
Args:
names (list): A list of names.
Returns:
None
"""
for name in names:
print(f"Hello, {name}!")
# Example usage:
# print_greetings(["Alice", "Bob", "Charlie"])
# Output:
# Hell... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to print a greeting message to a list of names. The function should take the list of names as input and print a greeting message for each name in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4941,
"level": 1,
"question": "Write a python function to print a greeting message to a list of names. The function should take the list of names as input and print a greeting message for each name in the list.",
"split": "train"
} |
import bisect
def longest_subarray_length(arr, d):
if not arr:
return 0
arr.sort()
max_len = 0
n = len(arr)
for left in range(n):
target = arr[left] + d
right = bisect.bisect_right(arr, target) - 1
current_len = right - left + 1
if current_len > max_len:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr` and an integer `d`, you must choose elements from the array such that the difference between the maximum and minimum elements in the chosen subset is at most `d`. Return _the length of the longest such subset you can form_. All elements in the subset mus... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4942,
"level": 1,
"question": "Given an array of integers `arr` and an integer `d`, you must choose elements from the array such that the difference between the maximum and minimum elements in the chosen subset is at most `d`. Return _the length of the longest such subset you can fo... |
from typing import List
def max_contiguous_subsequence_sum(expenses: List[int]) -> int:
arr_size = len(expenses)
if arr_size == 0:
return 0
max_till_now = expenses[0]
curr_sub_sum = expenses[0]
for i in range(1, arr_size):
curr_sub_sum = max(expenses[i], curr_sub_sum ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Context\nYou are given an array of integers representing stock prices where each element in the array represents the stock price on a given day. Your task is to write a function to find the maximum sum of a contiguous subsequence of stock prices.\n\n### Task\nImplement the function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4943,
"level": 1,
"question": "### Context\nYou are given an array of integers representing stock prices where each element in the array represents the stock price on a given day. Your task is to write a function to find the maximum sum of a contiguous subsequence of stock prices.\n... |
def replace_first_row_with_col_max(arr):
if not arr:
return arr
# Transpose the array to process columns as rows
transposed = zip(*arr)
# Compute the maximum for each column
max_row = [max(column) for column in transposed]
# Replace the first row with the max_row
arr[0] = max_row
... | simplelr_Filter | [
{
"content": "Question:\nI have a 2D array of size (m x n), and I need to perform an operation on it where each element in the first row is replaced by the maximum value from the column it belongs to. So, for example, if I have the following 2D array:\n```\n[[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n```\nI would li... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4944,
"level": 1,
"question": "I have a 2D array of size (m x n), and I need to perform an operation on it where each element in the first row is replaced by the maximum value from the column it belongs to. So, for example, if I have the following 2D array:\n```\n[[1, 2, 3],\n [4, 5... |
def is_strobogrammatic_number(number: str) -> bool:
rotation_map = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
# Check each digit in the number for validity
for c in number:
if c not in rotation_map:
return False
n = len(number)
for i in range(n):
j = n -... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question \n\n#### Scenario\n\nA student has recently learned about strobogrammatic numbers and the intriguing properties of certain numbers that retain their appearance even when flipped 180 degrees. To test their understanding, you design a problem to validate if numbers are strobo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4945,
"level": 1,
"question": "### Question \n\n#### Scenario\n\nA student has recently learned about strobogrammatic numbers and the intriguing properties of certain numbers that retain their appearance even when flipped 180 degrees. To test their understanding, you design a proble... |
from collections import Counter
def count_pairs_with_sum(arr, target):
freq = Counter(arr)
processed = set()
count = 0
for num in freq:
if num in processed:
continue
complement = target - num
if complement not in freq:
continue
if complement == nu... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` and an integer `target`. You need to count the number of pairs in the array whose sum is equal to the `target`. Each element in the array can only be used once for forming a pair. Return _the number of such pairs in the array_.\nAnswer:\nLet's th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4946,
"level": 1,
"question": "You are given an array of integers `arr` and an integer `target`. You need to count the number of pairs in the array whose sum is equal to the `target`. Each element in the array can only be used once for forming a pair. Return _the number of such pair... |
def is_palindrome(s: str) -> bool:
"""
This function determines whether a string is a palindrome or not.
Parameters:
s (str): The input string.
Returns:
bool: True if the string is a palindrome, False otherwise.
"""
# Remove spaces and punctuation, and convert to lower cas... | simplelr_Filter | [
{
"content": "Question:\nBased on the string recommendation, write a Python function that determines whether a string is a palindrome or not. A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation and capitalization). \n\nE... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4947,
"level": 1,
"question": "Based on the string recommendation, write a Python function that determines whether a string is a palindrome or not. A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, pun... |
def polygon_area(vertices):
"""Computes the area of a polygon given its vertices.
Args:
vertices: A list of tuples, where each tuple represents a vertex (x, y).
Returns:
The area of the polygon.
"""
if len(vertices) < 3:
return 0.0
sum1 = 0
sum2 = 0
n = len(vert... | simplelr_Filter | [
{
"content": "Question:\nThe problem is to find the area of a polygon. It is defined by its vertices. Given a list of vertices, compute the area of the polygon.\n\nFor example:\n\nInput:\n\n```\nvertices = [(0, 0), (4, 0), (4, 4), (0, 4)]\n```\n\nOutput:\n\n```\n16\n```\n\nI need to write code to solve this pro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4948,
"level": 1,
"question": "The problem is to find the area of a polygon. It is defined by its vertices. Given a list of vertices, compute the area of the polygon.\n\nFor example:\n\nInput:\n\n```\nvertices = [(0, 0), (4, 0), (4, 4), (0, 4)]\n```\n\nOutput:\n\n```\n16\n```\n\nI n... |
def quicksort(arr):
# Base case: If the array has 1 or fewer elements, it is already sorted
if len(arr) <= 1:
return arr
# Select the pivot as the middle element to avoid worst-case scenarios
pivot = arr[len(arr) // 2]
# Divide the array into elements less than, equal to, and greater than ... | simplelr_Filter | [
{
"content": "Question:\nI have a technical question about a computer science or programming topic. I'm trying to implement a sorting algorithm, specifically a quicksort algorithm, in a programming language. \n\nHere is my code so far: \n\n```python\ndef quicksort(arr):\n # Base case: If the array has 1 or f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4949,
"level": 1,
"question": "I have a technical question about a computer science or programming topic. I'm trying to implement a sorting algorithm, specifically a quicksort algorithm, in a programming language. \n\nHere is my code so far: \n\n```python\ndef quicksort(arr):\n #... |
import heapq
def shortest_path(edges, num_nodes, source):
# Initialize the distances to all nodes as infinity except the source
distances = [float('inf')] * num_nodes
distances[source] = 0
# Build the adjacency list
adj = [[] for _ in range(num_nodes)]
for u, v, w in edges:
adj[u].appe... | simplelr_Package | [
{
"content": "Question:\nYou are given a list of weighted edges that represent a directed graph, and your task is to implement a function called `shortest_path` that computes the shortest path from a given source node to all other nodes in the graph using Dijkstra's algorithm. The function should return a dicti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4950,
"level": 1,
"question": "You are given a list of weighted edges that represent a directed graph, and your task is to implement a function called `shortest_path` that computes the shortest path from a given source node to all other nodes in the graph using Dijkstra's algorithm.... |
def fibonacci(n): f = [0,1]; [f.append(f[-1]+f[-2]) for _ in range(n-2)]; return f[:n] | simplelr_Filter | [
{
"content": "Question:\nPropose a one-line Python script that generates the Fibonacci sequence for a given range, starting from 0 and 1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4951,
"level": 1,
"question": "Propose a one-line Python script that generates the Fibonacci sequence for a given range, starting from 0 and 1.",
"split": "train"
} |
def calculate_total_price(items=None):
"""Calculate the total price of items.
Args:
items (list, optional): A list of dictionaries. Each dictionary should have 'price' key.
Defaults to None. If None, treats as empty list.
Returns:
float: The total pric... | simplelr_Filter | [
{
"content": "Question:\nI have a list of items and their prices. I want to create a function that will calculate the total price of all the items in the list.\n\nHere is an example of the input list:\n\n```python\nitems = [\n {\"name\": \"apple\", \"price\": 1.00},\n {\"name\": \"banana\", \"price\": 0.5... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4952,
"level": 1,
"question": "I have a list of items and their prices. I want to create a function that will calculate the total price of all the items in the list.\n\nHere is an example of the input list:\n\n```python\nitems = [\n {\"name\": \"apple\", \"price\": 1.00},\n {\... |
import math
def sum_of_even_numbers_and_print_sqrt(n):
total = 0
for i in range(2, n + 1, 2):
total += i
print(math.sqrt(i))
return total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as an input and returns the sum of all the even numbers between 1 and that integer (inclusive). Additionally, for each even number, print the square root of the even number.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4953,
"level": 1,
"question": "Create a function that takes an integer as an input and returns the sum of all the even numbers between 1 and that integer (inclusive). Additionally, for each even number, print the square root of the even number.",
"split": "train"
} |
def longestEqualSubarray(nums):
sum_map = {0: -1}
current_sum = 0
max_length = 0
for i, num in enumerate(nums):
current_sum += 1 if num == 1 else -1
if current_sum in sum_map:
length = i - sum_map[current_sum]
if length > max_length:
max_length = l... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums`, find the length of the longest contiguous subarray with an equal number of `0`s and `1`s. Return the length of this subarray. Implement a function `longestEqualSubarray(nums)` to solve this problem. \n\nFor example: \n- `nums = [0,1,0]`, the function shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4954,
"level": 1,
"question": "Given an integer array `nums`, find the length of the longest contiguous subarray with an equal number of `0`s and `1`s. Return the length of this subarray. Implement a function `longestEqualSubarray(nums)` to solve this problem. \n\nFor example: \n- `... |
def common_elements(list1, list2):
# Create a dictionary for elements in list2 for O(1) lookups
list2_dict = {}
for num in list2:
list2_dict[num] = True # Using True as a placeholder value
result = []
for num in list1:
if num in list2_dict:
if num not in result:
... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes two lists of integers as arguments and returns a list that contains only the elements that appear in both lists without duplicates. The elements in the resulting list should be arranged in the same order they appear in the first list. Do not use any built-in ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4955,
"level": 1,
"question": "Write a function that takes two lists of integers as arguments and returns a list that contains only the elements that appear in both lists without duplicates. The elements in the resulting list should be arranged in the same order they appear in the f... |
def convert_to_12_hour_format(time_str):
hour_str, min_str = time_str.split(':')
hour = int(hour_str)
if hour == 0:
period = "AM"
twelve_hour = 12
elif 1 <= hour < 12:
period = "AM"
twelve_hour = hour
elif hour == 12:
period = "PM"
twelve_hour = 12
... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that receives a time in 24-hour format (\"HH:MM\") and converts it to a string in 12-hour format with AM/PM.\n\nExample 1:\n\nInput: \"14:30\"\nOutput: \"02:30 PM\"\n\nExample 2:\n\nInput: \"23:15\"\nOutput: \"11:15 PM\"\n\nExample 3:\n\nInput: \"00:00\"\nOutput: \"12:0... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4956,
"level": 1,
"question": "Write a function that receives a time in 24-hour format (\"HH:MM\") and converts it to a string in 12-hour format with AM/PM.\n\nExample 1:\n\nInput: \"14:30\"\nOutput: \"02:30 PM\"\n\nExample 2:\n\nInput: \"23:15\"\nOutput: \"11:15 PM\"\n\nExample 3:\... |
import re
from typing import List
def extract_hashtags(posts: List[str]) -> List[str]:
"""
Extracts unique hashtags from a list of social media posts.
:param posts: List of strings representing social media posts.
:return: List of unique hashtags in the order of their first occurrence.
"""
res... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are developing a text processing tool that includes functionality for identifying and extracting hashtags from social media posts. Hashtags in these posts always start with a '#' symbol and consist of a sequence of alphanumeric characters.\n\n### Task\nImplement a func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4957,
"level": 1,
"question": "### Scenario\nYou are developing a text processing tool that includes functionality for identifying and extracting hashtags from social media posts. Hashtags in these posts always start with a '#' symbol and consist of a sequence of alphanumeric charac... |
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 () | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two arguments, an array of integers and a target integer. The function should return a tuple containing the indices of the two numbers such that they add up to the target. If there are no two numbers that add up to the target, the function should return an e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4958,
"level": 1,
"question": "Create a function that takes two arguments, an array of integers and a target integer. The function should return a tuple containing the indices of the two numbers such that they add up to the target. If there are no two numbers that add up to the targ... |
def reverse_words(sentence):
words = sentence.split()
words.reverse()
return ' '.join(words) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse the order of words in a given sentence. For example, if the input is \"Hello world from Alibaba\", the output should be \"Alibaba from world Hello\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4959,
"level": 1,
"question": "Write a function to reverse the order of words in a given sentence. For example, if the input is \"Hello world from Alibaba\", the output should be \"Alibaba from world Hello\".",
"split": "train"
} |
def sublist_between_indices(lst, start, end):
actual_start = min(start, end)
actual_end = max(start, end)
return lst[actual_start : actual_end + 1] | simplelr_Filter | [
{
"content": "Question:\nImplement a function that takes a list of numbers and two indices, and returns the sub-list between the two indices (inclusive).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4960,
"level": 1,
"question": "Implement a function that takes a list of numbers and two indices, and returns the sub-list between the two indices (inclusive).",
"split": "train"
} |
def calculate_total_cost(cart):
total = 0.0
for item in cart:
total += item['price'] * item['quantity']
return total | simplelr_Filter | [
{
"content": "Question:\nYou've been tasked with implementing a function to calculate the total cost of items in a shopping cart. The function should take a list of dictionaries, where each dictionary contains information about a single item in the cart. Each dictionary should have the following keys: 'name', '... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4961,
"level": 1,
"question": "You've been tasked with implementing a function to calculate the total cost of items in a shopping cart. The function should take a list of dictionaries, where each dictionary contains information about a single item in the cart. Each dictionary should... |
from collections import Counter
def is_anagram_of_palindrome(s):
counts = Counter(s)
odd_count = sum(1 for v in counts.values() if v % 2)
return odd_count == (len(s) % 2) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string as input and checks if it's an anagram of a palindrome. The function should return `True` if the string is an anagram of a palindrome, and `False` otherwise.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4962,
"level": 1,
"question": "Write a Python function that takes a string as input and checks if it's an anagram of a palindrome. The function should return `True` if the string is an anagram of a palindrome, and `False` otherwise.",
"split": "train"
} |
import requests
import json
from typing import Dict, List, Union
def department_sales_report(url: str, department: str) -> Dict[str, Union[float, List[Dict[str, Union[str, float]]]]]:
response = requests.get(url)
response.raise_for_status()
data = json.loads(response.text)
filtered_employees = [em... | simplelr_Package | [
{
"content": "Question:\nIn this problem, you will create a function to dynamically generate a report based on employee performance data stored in a JSON file fetched from the internet. The data consists of employee names, departments, and monthly sales figures. The goal is to filter the data by department and ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4963,
"level": 1,
"question": "In this problem, you will create a function to dynamically generate a report based on employee performance data stored in a JSON file fetched from the internet. The data consists of employee names, departments, and monthly sales figures. The goal is to... |
def calculateRewards(tasks):
rewards = []
for task in tasks:
if task % 2 == 0:
rewards.append(task // 2)
else:
rewards.append(task * 2)
return rewards
| simplelr_Taco | [
{
"content": "Question:\nA company wants to reward its employees who have delivered exceptional performance throughout the year. The performance of employees can be represented as an array of integers where each element indicates the number of tasks completed by an employee.\n\nThe company wants to reward emplo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4964,
"level": 1,
"question": "A company wants to reward its employees who have delivered exceptional performance throughout the year. The performance of employees can be represented as an array of integers where each element indicates the number of tasks completed by an employee.\n... |
def most_frequent_element(lst):
if not lst:
return None # Return None for an empty list
# Create a frequency dictionary
freq = {}
for elem in lst:
if elem in freq:
freq[elem] += 1
else:
freq[elem] = 1
# Find the most frequent element
max... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the element that appears most frequently in a list. If multiple elements have the same highest frequency, return the one that appears first in the list. The function should handle any list of hashable elements.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4965,
"level": 1,
"question": "Write a Python function to find the element that appears most frequently in a list. If multiple elements have the same highest frequency, return the one that appears first in the list. The function should handle any list of hashable elements.",
"spli... |
def trap_rainwater(height):
if not height:
return 0
n = len(height)
if n < 3:
return 0
left_max = [0] * n
current_max = 0
for i in range(n):
left_max[i] = current_max
if height[i] > current_max:
current_max = height[i]
right_max = [0] * n... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of non-negative integers representing the amount of rainwater trapped after it rains over a series of bars, where each element represents a bar's elevation on a 2D grid. Write a function that calculates the total amount of rainwater trapped. \n\n* For example, given... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4966,
"level": 1,
"question": "You are given a list of non-negative integers representing the amount of rainwater trapped after it rains over a series of bars, where each element represents a bar's elevation on a 2D grid. Write a function that calculates the total amount of rainwate... |
def find_contiguous_subarray(arr, n):
m = len(arr)
if m == 0 or n > m:
return []
current_sum = sum(arr[:n])
max_sum = current_sum
max_start = 0
for i in range(1, m - n + 1):
current_sum = current_sum - arr[i-1] + arr[i + n -1]
if current_sum > max_sum:
max_sum... | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers `arr` and an integer `n`, write a function `find_contiguous_subarray(arr, n)` that returns a contiguous subarray of length `n` with the maximum sum. If there are multiple subarrays with the same maximum sum, return the one that appears first.\n\nFor example:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4967,
"level": 1,
"question": "Given an array of integers `arr` and an integer `n`, write a function `find_contiguous_subarray(arr, n)` that returns a contiguous subarray of length `n` with the maximum sum. If there are multiple subarrays with the same maximum sum, return the one th... |
def count_ones(n: int) -> int:
count = 0
while n:
count += 1
n &= n - 1
return count | simplelr_Data_Structure | [
{
"content": "Question:\n### Context\nCount the number of 1 bits (Hamming weight) in the binary representation of a given unsigned integer using efficient bit manipulation techniques.\n\n### Function Signature\n```python\ndef count_ones(n: int) -> int:\n pass\n```\n\n### Input\n- `n`: an unsigned integer (0 ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4968,
"level": 1,
"question": "### Context\nCount the number of 1 bits (Hamming weight) in the binary representation of a given unsigned integer using efficient bit manipulation techniques.\n\n### Function Signature\n```python\ndef count_ones(n: int) -> int:\n pass\n```\n\n### In... |
from collections import Counter
def frequent_element(lst):
count = Counter(lst)
max_freq = max(count.values())
max_elements = [k for k, v in count.items() if v == max_freq]
return min(max_elements)
| simplelr_Taco | [
{
"content": "Question:\nCreate a function `frequent_element` that takes a list of integers and returns the integer which appears most frequently in the list. If multiple integers have the highest frequency, return the smallest one among them. Assume the list is non-empty. Look at the examples below for more de... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4969,
"level": 1,
"question": "Create a function `frequent_element` that takes a list of integers and returns the integer which appears most frequently in the list. If multiple integers have the highest frequency, return the smallest one among them. Assume the list is non-empty. Loo... |
def binary_to_decimal(binary_str):
if binary_str.startswith('-'):
sign = -1
binary_str = binary_str[1:]
else:
sign = 1
decimal = 0
for bit in binary_str:
decimal = decimal * 2 + int(bit)
return sign * decimal | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to convert a number from binary to decimal in Python. You should handle both positive and negative binary numbers. How would you structure the function to manage both cases?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4970,
"level": 1,
"question": "Write a function to convert a number from binary to decimal in Python. You should handle both positive and negative binary numbers. How would you structure the function to manage both cases?",
"split": "train"
} |
from typing import List
def find_max_subarray_sum(nums: List[int]) -> int:
if not nums:
return 0 # Though the problem states the list has at least one element, this is just a safeguard
current_max = global_max = nums[0]
for num in nums[1:]:
current_max = max(num, current_max + nu... | simplelr_Data_Structure | [
{
"content": "Question:\n### Maximum Subarray Sum\n\n**Scenario**: \nYou are given a list of integers that represent daily stock price changes. To maximize your financial gain from these changes, you wish to find the maximum sum of any contiguous subarray within this list.\n\n**Task**: \nWrite a function `find_... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4971,
"level": 1,
"question": "### Maximum Subarray Sum\n\n**Scenario**: \nYou are given a list of integers that represent daily stock price changes. To maximize your financial gain from these changes, you wish to find the maximum sum of any contiguous subarray within this list.\n\n... |
def minOperations(s):
counts = [0] * 26 # Initialize a list to count each character's frequency
for char in s:
index = ord(char) - ord('a')
counts[index] += 1
max_count = max(counts)
return len(s) - max_count
| simplelr_Taco | [
{
"content": "Question:\nGiven a string `s` consisting of lowercase English alphabets, find the minimum number of operations needed to make all characters of the string the same. In one operation, you can select any character in the string and change it to any other lowercase English character.\n\n**Example 1:*... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4972,
"level": 1,
"question": "Given a string `s` consisting of lowercase English alphabets, find the minimum number of operations needed to make all characters of the string the same. In one operation, you can select any character in the string and change it to any other lowercase ... |
def count_distinct_substrings(S):
substrings = set()
n = len(S)
for i in range(n):
for j in range(i + 1, n + 1):
substrings.add(S[i:j])
return len(substrings) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to calculate the total number of distinct substrings in a given string `S`. The function should take a single string `S` as input and return the total number of distinct substrings.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4973,
"level": 1,
"question": "Write a Python function to calculate the total number of distinct substrings in a given string `S`. The function should take a single string `S` as input and return the total number of distinct substrings.",
"split": "train"
} |
from typing import List
def collect_treasures(grid: List[List[int]]) -> int:
if not grid:
return 0
n = len(grid)
m = len(grid[0]) if n > 0 else 0
if n == 0:
return 0
if n == 1:
return max(grid[0])
prev = grid[0][:] # Initialize previous row with the first row of th... | simplelr_Taco | [
{
"content": "Question:\nIn a magical land, there lies a maze with hidden treasures. Elara is an adventurer and needs your help to collect the maximum value of treasures. The maze is represented as a 2D grid of size n x m where each cell contains a certain amount of treasure. Elara can start at any cell in the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4974,
"level": 1,
"question": "In a magical land, there lies a maze with hidden treasures. Elara is an adventurer and needs your help to collect the maximum value of treasures. The maze is represented as a 2D grid of size n x m where each cell contains a certain amount of treasure. ... |
from typing import List
def generate_sublists(arr: List[int], sublist_length: int) -> List[List[int]]:
if sublist_length <= 0 or sublist_length > len(arr):
return []
result = []
for i in range(len(arr) - sublist_length + 1):
sublist = arr[i:i+sublist_length]
result.append(sublist)
... | simplelr_Code_Contests | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a new list containing all the contiguous sublists (sublists made up of consecutive elements) of a length you specify. Each sublist should be in the same order as in the input list. \n\nFor example, if given the list [1, 2, 3, 4... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4975,
"level": 1,
"question": "Create a function that takes a list of integers and returns a new list containing all the contiguous sublists (sublists made up of consecutive elements) of a length you specify. Each sublist should be in the same order as in the input list. \n\nFor exa... |
from collections import Counter
def count_words(text):
"""Counts the occurrences of words in a string.
Args:
text: The string to analyze.
Returns:
A dictionary where keys are unique words and values are their counts.
"""
return Counter(text.lower().split()) | simplelr_Filter | [
{
"content": "Question:\nThe goal is to create a Python function that takes a string as input and returns a dictionary where the keys are the unique words in the string and the values are the number of times each word appears in the string.\n\nHere's my attempt:\n\n```python\ndef count_words(text):\n \"\"\"Cou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4976,
"level": 1,
"question": "The goal is to create a Python function that takes a string as input and returns a dictionary where the keys are the unique words in the string and the values are the number of times each word appears in the string.\n\nHere's my attempt:\n\n```python\n... |
def product_except_self(nums):
n = len(nums)
if n == 0:
return []
prefix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]
suffix = [1] * n
for i in range(n-2, -1, -1):
suffix[i] = suffix[i+1] * nums[i+1]
result = [prefix[i] * suffix[i... | simplelr_Evol | [
{
"content": "Question:\nCreate a function in Python that takes a list of integers as input and returns the product of all elements in the list except the element at the current position without using division. Ensure that the solution operates with a time complexity of O(n). For example, given the list [1, 2, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4977,
"level": 1,
"question": "Create a function in Python that takes a list of integers as input and returns the product of all elements in the list except the element at the current position without using division. Ensure that the solution operates with a time complexity of O(n). ... |
from typing import List
def count_divisible_by_3(lst: List[int]) -> int:
return sum(1 for num in lst if num % 2 != 0 and num % 3 == 0)
| simplelr_Taco | [
{
"content": "Question:\nAlex has a list of integers and he wants to write a program that filters out all the even numbers from his list and counts how many numbers are divisible by 3. The program should first filter out the even numbers from the list and then count the remaining numbers that are divisible by 3... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4978,
"level": 1,
"question": "Alex has a list of integers and he wants to write a program that filters out all the even numbers from his list and counts how many numbers are divisible by 3. The program should first filter out the even numbers from the list and then count the remain... |
from collections import deque
def find_shortest_path(graph, start, end):
if start == end:
return [start]
visited = set()
queue = deque()
queue.append(start)
visited.add(start)
parent = {start: None}
while queue:
current = queue.popleft()
for n... | simplelr_Apps | [
{
"content": "Question:\nCreate a function `find_shortest_path` that determines the shortest path between two nodes in an unweighted graph, using a Breadth-First Search (BFS) algorithm. \n\nThe function should take in three parameters:\n1. A dictionary representing the graph, where keys are node names and value... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4979,
"level": 1,
"question": "Create a function `find_shortest_path` that determines the shortest path between two nodes in an unweighted graph, using a Breadth-First Search (BFS) algorithm. \n\nThe function should take in three parameters:\n1. A dictionary representing the graph, ... |
from typing import List
def power_set(nums: List[int]) -> List[List[int]]:
power = [ [] ]
for num in nums:
temp = []
for subset in power:
temp.append(subset + [num])
power += temp
return power | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nCreate a function that calculates the power set of a given list of unique integers. The power set is a set of all subsets, including the empty set and the given set itself.\n\n### Function Signature\n```python\ndef power_set(nums: List[int]) -> List[List[int]]:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4980,
"level": 1,
"question": "### Problem Statement\n\nCreate a function that calculates the power set of a given list of unique integers. The power set is a set of all subsets, including the empty set and the given set itself.\n\n### Function Signature\n```python\ndef power_set(nu... |
from collections import deque
def min_time_to_reach_end(heights, k):
n = len(heights)
if n == 0:
return 0 # Assuming 0 is acceptable if no buildings, else adjust accordingly
max_jumps = k
visited = [[False] * (max_jumps + 1) for _ in range(n)]
queue = deque()
queue.append((0, 0))
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `heights` representing the heights of buildings, and an integer `k`. You are currently on the roof of building `0`, and every second you can either move to the next building on your right or use one of your `k` jumps to move to any building in range `[i-k,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4981,
"level": 1,
"question": "You are given an integer array `heights` representing the heights of buildings, and an integer `k`. You are currently on the roof of building `0`, and every second you can either move to the next building on your right or use one of your `k` jumps to m... |
def group_by_owners(input_data):
grouped = {}
for filename, owner in input_data.items():
if owner in grouped:
grouped[owner].append(filename)
else:
grouped[owner] = [filename]
return grouped | simplelr_Apps | [
{
"content": "Question:\nWrite a function called `group_by_owners` that takes a dictionary where the keys are filenames and the values are the corresponding owners' names. The function should return a dictionary where the keys are owners' names and the values are lists of filenames they own (in any order).\n\n#... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4982,
"level": 1,
"question": "Write a function called `group_by_owners` that takes a dictionary where the keys are filenames and the values are the corresponding owners' names. The function should return a dictionary where the keys are owners' names and the values are lists of file... |
def findWinners(matches):
data = {}
for match in matches:
p, o, r = match
winner = p if r == 1 else o
for player in [p, o]:
if player not in data:
data[player] = {'wins': 0, 'matches': 0}
data[player]['matches'] += 1
if player == winner... | simplelr_Leetcode | [
{
"content": "Question:\nWrite a function `findWinners` to determine the winners of a gaming competition. You are given an array of arrays, where each sub-array consists of three elements: [player_id, opponent_id, result]. The `player_id` and `opponent_id` are IDs of the players who competed in a match, and `re... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4983,
"level": 1,
"question": "Write a function `findWinners` to determine the winners of a gaming competition. You are given an array of arrays, where each sub-array consists of three elements: [player_id, opponent_id, result]. The `player_id` and `opponent_id` are IDs of the playe... |
import string
def count_word_occurrences(filename):
# Initialize an empty dictionary to store word counts
word_counts = {}
try:
# Open and read the file
with open(filename, 'r') as file:
text = file.read()
# Convert text to lowercase
text = text.lower()
... | simplelr_Evol | [
{
"content": "Question:\nCreate a function in Python that reads a text file and counts the occurrences of each word in the file. The function should ignore case, punctuation, and any whitespace. Your solution should include a step-by-step explanation of the process, as well as sample data and expected output.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4984,
"level": 1,
"question": "Create a function in Python that reads a text file and counts the occurrences of each word in the file. The function should ignore case, punctuation, and any whitespace. Your solution should include a step-by-step explanation of the process, as well as... |
def move_zeros(array: list) -> None:
write_ptr = 0
for i in range(len(array)):
element = array[i]
# Check if the element is an integer zero (exclude bool)
if isinstance(element, int) and type(element) is int and element == 0:
continue
# Swap with the write_ptr element... | simplelr_Data_Structure | [
{
"content": "Question:\n**Question**:\nYou are given an array that can contain various data types including integers, booleans, strings, etc. Your task is to implement a function `move_zeros` that moves all zero-valued elements to the end of the array while preserving the order of non-zero elements. \n\nHoweve... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4985,
"level": 1,
"question": "**Question**:\nYou are given an array that can contain various data types including integers, booleans, strings, etc. Your task is to implement a function `move_zeros` that moves all zero-valued elements to the end of the array while preserving the ord... |
import random
def exclusive_randint(start, end):
return random.randrange(start, end) | simplelr_Filter | [
{
"content": "Question:\nThe `randint` function from the `random` module in Python is commonly used to generate a random integer within a specified range. However, it includes both endpoints of the range. I need a function that generates a random integer within a range but excludes the upper bound. How can I ac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4986,
"level": 1,
"question": "The `randint` function from the `random` module in Python is commonly used to generate a random integer within a specified range. However, it includes both endpoints of the range. I need a function that generates a random integer within a range but exc... |
import keyword
def is_valid_variable_name(variable_name: str) -> bool:
if not variable_name:
return False
first_char = variable_name[0]
if not (first_char.isalpha() or first_char == '_'):
return False
for c in variable_name[1:]:
if not (c.isalnum() or c == '_'):
retu... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes in a string and returns True if the string is a valid variable name in Python, and False otherwise. The function should adhere to the following rules for a valid variable name:\n- Must start with a letter (a-z, A-Z) or underscore (_).\n- Can only conta... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4987,
"level": 1,
"question": "Write a Python function that takes in a string and returns True if the string is a valid variable name in Python, and False otherwise. The function should adhere to the following rules for a valid variable name:\n- Must start with a letter (a-z, A-Z) o... |
def findUniqueElement(arr):
res = 0
for num in arr:
res ^= num
return res | simplelr_Codeforces | [
{
"content": "Question:\nYou are given an unsorted array of integers where every element appears twice except for one element which appears only once. Your task is to identify the element that appears only once.\n\nImplement a function `findUniqueElement` that takes an array of integers as input and returns the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4988,
"level": 1,
"question": "You are given an unsorted array of integers where every element appears twice except for one element which appears only once. Your task is to identify the element that appears only once.\n\nImplement a function `findUniqueElement` that takes an array o... |
def max_subarray_sum(arr):
if not arr:
return 0 # or raise an appropriate error if empty arrays are not expected
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_current
retu... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the maximum sum of a subarray in an array of integers using Kadane's algorithm. Can you also explain the algorithm with an example?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4989,
"level": 1,
"question": "Write a Python function to find the maximum sum of a subarray in an array of integers using Kadane's algorithm. Can you also explain the algorithm with an example?",
"split": "train"
} |
def product_except_self(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]
return [prefix[i] * suffix[i] for ... | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function to compute the product of all elements in an array except the current one, for a given array of integers. This function should take an array of integers as input and return a new array where each element is the product of all other elements except itself. The so... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4990,
"level": 1,
"question": "Design a Python function to compute the product of all elements in an array except the current one, for a given array of integers. This function should take an array of integers as input and return a new array where each element is the product of all o... |
def find_pair_with_zero_sum(arr):
seen = set()
for num in arr:
if -num in seen:
return True
seen.add(num)
return False
| simplelr_Taco | [
{
"content": "Question:\nYou are given a list of integers. Your task is to write a function that checks if the list contains a pair of numbers (distinct) whose sum is zero. If such a pair exists, return True; otherwise, return False.\n\nFunction Description\n\nComplete the find_pair_with_zero_sum function in th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4991,
"level": 1,
"question": "You are given a list of integers. Your task is to write a function that checks if the list contains a pair of numbers (distinct) whose sum is zero. If such a pair exists, return True; otherwise, return False.\n\nFunction Description\n\nComplete the fin... |
def remove_consecutive_duplicates(lst: list) -> list:
if not isinstance(lst, list):
raise TypeError("Input must be a list")
for element in lst:
if type(element) is not int:
raise TypeError("All elements must be integers")
result = []
for element in lst:
if not result ... | simplelr_Algorithm | [
{
"content": "Question:\n### Consecutive Element Remover\n\nYou are assigned the task of removing consecutive duplicate elements from a given list such that only the first occurrence of each group of consecutive duplicates is preserved.\n\n**Function Signature**:\n```python\ndef remove_consecutive_duplicates(ls... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4992,
"level": 1,
"question": "### Consecutive Element Remover\n\nYou are assigned the task of removing consecutive duplicate elements from a given list such that only the first occurrence of each group of consecutive duplicates is preserved.\n\n**Function Signature**:\n```python\nd... |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, KBinsDiscretizer
from sklearn.naive_bayes import GaussianNB, MultinomialNB
from sklearn.metrics import accuracy_score, classification_report, precision_scor... | simplelr_Docs | [
{
"content": "Question:\n### Question: Naive Bayes Classifier Implementation and Comparison\n\nYou are provided with a dataset consisting of various features and a target variable. Your task is to write a Python function that preprocesses the data, applies at least two different Naive Bayes classifiers, and com... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4993,
"level": 1,
"question": "### Question: Naive Bayes Classifier Implementation and Comparison\n\nYou are provided with a dataset consisting of various features and a target variable. Your task is to write a Python function that preprocesses the data, applies at least two differe... |
def average_salary(employees, department):
"""
Calculates the average salary of the employees in the specified department.
Parameters:
- employees: List of employee dictionaries, where each dictionary includes 'name', 'department', and 'salary' keys.
- department: The department name (string) f... | simplelr_Evol | [
{
"content": "Question:\nYou are given a list of dictionaries representing employees in a company. Each dictionary contains the `name`, `department`, and `salary` of an employee. Write a function `average_salary` that takes two arguments, a list of employee dictionaries and a department name. The function shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4994,
"level": 1,
"question": "You are given a list of dictionaries representing employees in a company. Each dictionary contains the `name`, `department`, and `salary` of an employee. Write a function `average_salary` that takes two arguments, a list of employee dictionaries and a ... |
def max_diff_increasing_subsequence(nums):
if len(nums) < 2:
return 0
min_so_far = nums[0]
max_diff = 0
for i in range(1, len(nums)):
current = nums[i]
if current > min_so_far:
diff = current - min_so_far
if diff > max_diff:
max_diff = diff... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums`, return the maximum difference between any increasing subsequence of length 2. If no such subsequence exists, return `0`. For example, given `nums = [4, 5, 1, 3, 2, 10]`, the output should be `9` because the maximum difference is between the numbers `1` and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4995,
"level": 1,
"question": "Given an integer array `nums`, return the maximum difference between any increasing subsequence of length 2. If no such subsequence exists, return `0`. For example, given `nums = [4, 5, 1, 3, 2, 10]`, the output should be `9` because the maximum differ... |
def longest_substring_without_repeating_characters(s):
max_length = 0
left = 0
last_seen = {}
for right in range(len(s)):
current_char = s[right]
if current_char in last_seen and last_seen[current_char] >= left:
left = last_seen[current_char] + 1
last_seen[curren... | simplelr_Filter | [
{
"content": "Question:\nThese are the instructions for a code challenge I am facing.\n\n**Challenge:**\n\nGiven a string containing only lowercase letters, find the length of the longest substring without repeating characters.\n\n**Example:**\n\n```\nInput: \"abcabcbb\"\nOutput: 3\nExplanation: The longest sub... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4996,
"level": 1,
"question": "These are the instructions for a code challenge I am facing.\n\n**Challenge:**\n\nGiven a string containing only lowercase letters, find the length of the longest substring without repeating characters.\n\n**Example:**\n\n```\nInput: \"abcabcbb\"\nOutp... |
def transpose(matrix):
return [list(row) for row in zip(*matrix)] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a two-dimensional array as argument and returns the transpose of the array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4997,
"level": 1,
"question": "Create a function that takes a two-dimensional array as argument and returns the transpose of the array.",
"split": "train"
} |
def merge_intervals(intervals):
if not intervals:
return []
# First, check for intervals that cannot be ordered
for i in range(len(intervals)):
for j in range(len(intervals)):
if i == j:
continue
i_start, i_end = intervals[i]
j_start, j_en... | simplelr_Filter | [
{
"content": "Question:\nGiven a set of intervals that each have the following format: `[start, end]` where `start` and `end` are non-negative integers. The task is to merge the overlapping intervals and return a new set of merged intervals. If the given intervals cannot be ordered (i.e., there exists an interv... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4998,
"level": 1,
"question": "Given a set of intervals that each have the following format: `[start, end]` where `start` and `end` are non-negative integers. The task is to merge the overlapping intervals and return a new set of merged intervals. If the given intervals cannot be or... |
def longest_increasing_sequence(nums):
if not nums:
return 0
nums = set(nums)
max_length = 0
for num in nums:
current_length = 1
current = num + 1
while current in nums:
current_length += 1
current += 1
if current_length > max_length:
... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns the length of the longest consecutive sequence. The sequence must be strictly increasing, and you can assume that all integers in the list are unique.\n\nFor example:\n\n```python\nlongest_increasing_sequence([1, 9, 3, 10, 2, 20... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4999,
"level": 1,
"question": "Write a function that takes a list of integers and returns the length of the longest consecutive sequence. The sequence must be strictly increasing, and you can assume that all integers in the list are unique.\n\nFor example:\n\n```python\nlongest_incr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.