target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
from collections import Counter
def is_palindromic_permutation(s: str) -> bool:
# Clean the string by removing non-alphanumeric characters and converting to lowercase
cleaned = [c.lower() for c in s if c.isalnum()]
# Count the frequency of each character
counts = Counter(cleaned)
# Count ... | simplelr_Package | [
{
"content": "Question:\nWrite a function `is_palindromic_permutation(s: str) -> bool` that determines if any permutation of the input string `s` forms a palindrome. \n\nA palindrome is a word or phrase that is the same forwards and backwards (ignoring spaces, punctuation, and case). For instance, \"racecar\" i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2500,
"level": 1,
"question": "Write a function `is_palindromic_permutation(s: str) -> bool` that determines if any permutation of the input string `s` forms a palindrome. \n\nA palindrome is a word or phrase that is the same forwards and backwards (ignoring spaces, punctuation, and... |
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n - 1) | simplelr_Filter | [
{
"content": "Question:\nHello! I need some help with understanding a recursive function in Python. I have a code snippet that calculates the factorial of a number using recursion, but I'm having trouble grasping how it works. Can you explain it to me?\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2501,
"level": 1,
"question": "Hello! I need some help with understanding a recursive function in Python. I have a code snippet that calculates the factorial of a number using recursion, but I'm having trouble grasping how it works. Can you explain it to me?",
"split": "train"
} |
def sum_even_numbers(numbers):
total = 0
for number in numbers:
if number % 2 == 0:
total += number
return total
# Example usage:
# print(sum_even_numbers([1, 2, 3, 4])) # Output: 6
# print(sum_even_numbers([-2, -4, 6])) # Output: 0
# print(sum_even_numbers([])) # Output... | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that calculates the sum of all even numbers in a given list? If the list does not contain any even numbers, the function should return 0. Can you provide a code snippet?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2502,
"level": 1,
"question": "How can I create a Python function that calculates the sum of all even numbers in a given list? If the list does not contain any even numbers, the function should return 0. Can you provide a code snippet?",
"split": "train"
} |
def count_lines_in_file(filename):
with open(filename, 'r') as file:
count = 0
for line in file:
count += 1
return count | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the number of lines in a file.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2503,
"level": 1,
"question": "Write a python function to find the number of lines in a file.",
"split": "train"
} |
def reverse_string(s):
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to output a given string in reverse order. Your function should have a time complexity of O(n), where n is the length of the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2504,
"level": 1,
"question": "Write a function to output a given string in reverse order. Your function should have a time complexity of O(n), where n is the length of the string.",
"split": "train"
} |
from typing import List
def containsNearbyAlmostDuplicate(nums: List[int], k: int, t: int) -> bool:
n = len(nums)
if n < 2 or k <= 0:
return False
for i in range(n):
for j in range(i + 1, min(i + k + 1, n)):
if abs(nums[i] - nums[j]) <= t:
return True
return ... | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers, you need to find out whether there are two distinct indices `i` and `j` in the array such that the absolute difference between `nums[i]` and `nums[j]` is at most `k`, and the absolute difference between `i` and `j` is at most `t`. Implement a function that ac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2505,
"level": 1,
"question": "Given an array of integers, you need to find out whether there are two distinct indices `i` and `j` in the array such that the absolute difference between `nums[i]` and `nums[j]` is at most `k`, and the absolute difference between `i` and `j` is at mos... |
import heapq
def dijkstra(graph: dict, start: int) -> dict:
# Initialize the distances dictionary with infinity for all nodes except the start node
distances = {node: float('infinity') for node in graph}
distances[start] = 0
# Priority queue: (distance, node)
heap = [(0, start)]
while heap:
... | simplelr_Algorithm | [
{
"content": "Question:\n## New Question\n\n\n\nYou are tasked with developing a system to find the shortest paths from a library's main entrance to different sections of the library using Dijkstra's Algorithm. The library is represented as a graph where nodes correspond to different sections, and edges with we... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2506,
"level": 1,
"question": "## New Question\n\n\n\nYou are tasked with developing a system to find the shortest paths from a library's main entrance to different sections of the library using Dijkstra's Algorithm. The library is represented as a graph where nodes correspond to di... |
def StringReorder(s, indices):
n = len(s)
res = [''] * n
for i in range(n):
res[indices[i]] = s[i]
return ''.join(res) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters and an array `indices` of the same length as `s`. The `indices` array is a permutation of `[0, 1, ..., len(s) - 1]`. Your task is to reorder the characters in `s` such that the `i-th` character moves to `indices[i]` in t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2507,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters and an array `indices` of the same length as `s`. The `indices` array is a permutation of `[0, 1, ..., len(s) - 1]`. Your task is to reorder the characters in `s` such that the `i-th` c... |
def word_pattern(pattern: str, text: str) -> bool:
words = text.split()
if len(pattern) != len(words):
return False
p_to_w = {}
w_to_p = {}
for p, w in zip(pattern, words):
if p in p_to_w:
if p_to_w[p] != w:
return False
else:
... | simplelr_Data_Structure | [
{
"content": "Question:\n**Problem Statement**:\n\nYou are given a pattern string and a text string, and you need to determine if the text follows the same pattern. The conformance means a full match where there is a bijection (one-to-one correspondence) between characters in the pattern and non-empty words in ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2508,
"level": 1,
"question": "**Problem Statement**:\n\nYou are given a pattern string and a text string, and you need to determine if the text follows the same pattern. The conformance means a full match where there is a bijection (one-to-one correspondence) between characters in ... |
def double_store(arr):
for i in range(len(arr)-1, -1, -1):
arr.insert(i+1, arr[i]) | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that takes an array and double-stores every element, modifying the input array in place? For instance, if I have an input array of [1, 2, 3, 4], the function should change it to [1, 1, 2, 2, 3, 3, 4, 4] without creating any additional arrays or using l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2509,
"level": 1,
"question": "How can I create a Python function that takes an array and double-stores every element, modifying the input array in place? For instance, if I have an input array of [1, 2, 3, 4], the function should change it to [1, 1, 2, 2, 3, 3, 4, 4] without creati... |
def absolute_value(n):
return abs(n) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as input and returns its absolute value.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2510,
"level": 1,
"question": "Create a function that takes an integer as input and returns its absolute value.",
"split": "train"
} |
from typing import List
def majority_element(nums: List[int]) -> int:
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count = 1
else:
if num == candidate:
count += 1
else:
count -= 1
... | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function `majority_element` that takes a list of integers as input and returns the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times in the list, where n is the length of the list. You can assume that the majority element always exists in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2511,
"level": 1,
"question": "Write a function `majority_element` that takes a list of integers as input and returns the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times in the list, where n is the length of the list. You can assume that th... |
def sort_books_by_year(books):
return sorted(books, key=lambda x: x['published_year']) | simplelr_Algorithm | [
{
"content": "Question:\n### Sorting Books by Published Year\n\nYou are provided with a list of dictionaries, where each dictionary represents a book with different attributes including \"title\" and \"published_year\".\n\n#### Objective:\nYour task is to implement a function called `sort_books_by_year()` which... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2512,
"level": 1,
"question": "### Sorting Books by Published Year\n\nYou are provided with a list of dictionaries, where each dictionary represents a book with different attributes including \"title\" and \"published_year\".\n\n#### Objective:\nYour task is to implement a function ... |
def calculate_min_coins(coins, amount):
if amount == 0:
return 0
coins = [c for c in coins if c > 0]
if not coins:
return -1
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for j in range(coin, amount + 1):
if dp[j - coin] + 1 < dp[j]:
... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that calculates the minimum number of coins needed to make a specified amount of change. You are given a list of the denominations of the coins available. \n\nFor example:\n\n```python\ncalculate_min_coins([1, 5, 10, 25], 36) -> 3 (25 + 10 + 1)\ncalculate_min_coins([1, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2513,
"level": 1,
"question": "Write a function that calculates the minimum number of coins needed to make a specified amount of change. You are given a list of the denominations of the coins available. \n\nFor example:\n\n```python\ncalculate_min_coins([1, 5, 10, 25], 36) -> 3 (25 ... |
def intersect(a, b):
"""Return common elements of two lists as a list."""
return [value for value in a if value in b]
a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]
print(intersect(a, b)) | simplelr_Filter | [
{
"content": "Question:\ndef intersect(a, b):\n \"\"\"Return common elements of two lists as a list.\"\"\"\n return [value for value in a if value in b]\n\na = [1, 2, 3, 4, 5]\nb = [4, 5, 6, 7, 8]\nprint(intersect(a, b))\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2514,
"level": 1,
"question": "def intersect(a, b):\n \"\"\"Return common elements of two lists as a list.\"\"\"\n return [value for value in a if value in b]\n\na = [1, 2, 3, 4, 5]\nb = [4, 5, 6, 7, 8]\nprint(intersect(a, b))",
"split": "train"
} |
def strange_sort_list(lst):
sorted_list = sorted(lst)
result = []
left = 0
right = len(sorted_list) - 1
take_min = True
while left <= right:
if take_min:
result.append(sorted_list[left])
left += 1
else:
result.append(sorted_list[right])
... | simplelr_Filter | [
{
"content": "Question:\nImplement a strange function 'strange_sort_list(lst)' which takes a list of integers, and sorts them in a peculiar manner. The peculiarity of this sort is first taking the smallest number, then the largest of the rest, then the smallest of the rest and so on.\nAnswer:\nLet's think step ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2515,
"level": 1,
"question": "Implement a strange function 'strange_sort_list(lst)' which takes a list of integers, and sorts them in a peculiar manner. The peculiarity of this sort is first taking the smallest number, then the largest of the rest, then the smallest of the rest and... |
def minAddToMakeValid(s: str) -> int:
balance = 0
missing = 0
for char in s:
if char == '(':
balance += 1
else:
balance -= 1
if balance < 0:
missing += 1
balance = 0
return missing + balance | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string containing just the characters '(' and ')'. Your task is to determine the minimum number of parentheses to add to make the string valid. A string is considered valid if it is the empty string, or if it can be written as AB (A concatenated with B), where A and B ar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2516,
"level": 1,
"question": "You are given a string containing just the characters '(' and ')'. Your task is to determine the minimum number of parentheses to add to make the string valid. A string is considered valid if it is the empty string, or if it can be written as AB (A con... |
from collections import defaultdict, deque
def index_mapping(nums1, nums2):
index_map = defaultdict(deque)
for idx, num in enumerate(nums2):
index_map[num].append(idx)
mapping = []
for num in nums1:
mapping.append(index_map[num].popleft())
return mapping | simplelr_Leetcode | [
{
"content": "Question:\n**Question 4**: You are given two integer arrays, `nums1` and `nums2`, where `nums2` is a permutation of `nums1`. You need to find an index mapping `mapping` such that `mapping[i] = j` which means the `i-th` element in `nums1` appears in `nums2` at index `j`. Return the array `mapping`.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2517,
"level": 1,
"question": "**Question 4**: You are given two integer arrays, `nums1` and `nums2`, where `nums2` is a permutation of `nums1`. You need to find an index mapping `mapping` such that `mapping[i] = j` which means the `i-th` element in `nums1` appears in `nums2` at ind... |
def max_perimeter_triangle(nums):
nums.sort(reverse=True)
n = len(nums)
for i in range(n - 2):
if nums[i] < nums[i+1] + nums[i+2]:
return nums[i] + nums[i+1] + nums[i+2]
return 0 | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums`, each representing a stick length, return the maximum perimeter of a triangle that can be formed with three of these stick lengths. If no valid triangle can be formed, return 0. To form a valid triangle, the sum of any two sides must be greater than the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2518,
"level": 1,
"question": "Given an array of integers `nums`, each representing a stick length, return the maximum perimeter of a triangle that can be formed with three of these stick lengths. If no valid triangle can be formed, return 0. To form a valid triangle, the sum of any... |
def setup_and_translate(domain: str, localedir: str, message: str, languages: list) -> dict:
import gettext
translations = {}
for lang in languages:
# Create a translation object for the given language with fallback enabled
translation = gettext.translation(domain, localedir=localedir, lang... | simplelr_Docs | [
{
"content": "Question:\n### **Programming Assessment: Implementing Internationalization with the gettext Module**\n\n#### Objective:\nYour task is to implement a small program that demonstrates the use of the \"gettext\" module for internationalization and localization, utilizing both the GNU **gettext** API a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2519,
"level": 1,
"question": "### **Programming Assessment: Implementing Internationalization with the gettext Module**\n\n#### Objective:\nYour task is to implement a small program that demonstrates the use of the \"gettext\" module for internationalization and localization, utili... |
def update_stock(stock, transactions):
updated_stock = stock.copy()
for item, quantity in transactions:
if item in updated_stock:
updated_stock[item] -= quantity
return updated_stock
| simplelr_Taco | [
{
"content": "Question:\nCreate a function that takes a dictionary `stock` and a list of lists `transactions` as inputs. The `stock` dictionary contains items as keys and their current stock numbers as values. Each element in the `transactions` list is a list of an item and the quantity sold in a transaction. T... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2520,
"level": 1,
"question": "Create a function that takes a dictionary `stock` and a list of lists `transactions` as inputs. The `stock` dictionary contains items as keys and their current stock numbers as values. Each element in the `transactions` list is a list of an item and th... |
import contextvars
def record_user_action(context, actions):
# Initialize context variables from the initial context dictionary
variables = {}
for var_name, value in context.items():
variables[var_name] = contextvars.ContextVar(var_name, default=value)
# Dictionary to keep track of tokens ... | simplelr_Docs | [
{
"content": "Question:\n### Context Management in Python with `contextvars`\n\nIn Python, context variables allow you to manage context-specific data in applications, such as values that should be unique and independent across different parts of a program or even different threads. Your task is to implement a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2521,
"level": 1,
"question": "### Context Management in Python with `contextvars`\n\nIn Python, context variables allow you to manage context-specific data in applications, such as values that should be unique and independent across different parts of a program or even different th... |
def add_and_subtract(a: int, b: int) -> tuple:
"""
This function returns a tuple containing the sum and difference of two integers.
Parameters:
a (int): The first integer.
b (int): The second integer.
Returns:
tuple: A tuple containing the sum (a + b) and difference (a - b) of the ... | simplelr_Docs | [
{
"content": "Question:\n**Objective:**\nDemonstrate your understanding of how to interact between Python and C by embedding a Python script in a C application.\n\n**Problem Statement:**\n\nYou will first write a Python script that contains a specific function required for an embedded C application. Then you wi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2522,
"level": 1,
"question": "**Objective:**\nDemonstrate your understanding of how to interact between Python and C by embedding a Python script in a C application.\n\n**Problem Statement:**\n\nYou will first write a Python script that contains a specific function required for an ... |
from typing import List
def interpolation_search_records(records: List[int], search_key: int) -> int:
if not records:
return -1
low = 0
high = len(records) - 1
while low <= high and records[low] <= search_key <= records[high]:
if records[low] == records[high]:
retu... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\n\nYou are hired by a database management company to help optimize their record search operations. The company stores its records in sorted arrays and typically handles large amounts of data. Your task is to implement an efficient search algorithm suitable for this use case... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2523,
"level": 1,
"question": "### Question\n\nYou are hired by a database management company to help optimize their record search operations. The company stores its records in sorted arrays and typically handles large amounts of data. Your task is to implement an efficient search a... |
def square_elements(lst):
return [x ** 2 for x in lst] | simplelr_Filter | [
{
"content": "Question:\nWrite a function \"square_elements\" that takes a list of integers as input and returns a new list with each element squared.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2524,
"level": 1,
"question": "Write a function \"square_elements\" that takes a list of integers as input and returns a new list with each element squared.",
"split": "train"
} |
import numpy as np
def matrix_multiplication(matrix_a, matrix_b):
return np.dot(matrix_a, matrix_b) | simplelr_Package | [
{
"content": "Question:\nYou are required to implement a function that performs matrix multiplication on two given 2D arrays. Matrix multiplication is a fundamental operation in various domains including computer graphics, machine learning, and scientific computing.\n\nUsing specific libraries and functions, im... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2525,
"level": 1,
"question": "You are required to implement a function that performs matrix multiplication on two given 2D arrays. Matrix multiplication is a fundamental operation in various domains including computer graphics, machine learning, and scientific computing.\n\nUsing s... |
def find_maximum(lst):
if not lst:
return None
current_max = lst[0]
for number in lst[1:]:
if number > current_max:
current_max = number
return current_max | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes in a list of integers and returns the maximum value. However, you are not allowed to use any built-in Python functions or methods that directly find the maximum value in a list, such as max() or sort(). You must implement your own algorithm to find the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2526,
"level": 1,
"question": "Write a Python function that takes in a list of integers and returns the maximum value. However, you are not allowed to use any built-in Python functions or methods that directly find the maximum value in a list, such as max() or sort(). You must imple... |
def restore_string(s, indices):
n = len(s)
result = [''] * n
for i in range(n):
result[indices[i]] = s[i]
return ''.join(result) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` and an array of indices `indices` of the same length. The string `s` is a **shuffled** version of a given string that has its characters randomly scrambled. Reorder the `s` string such that the character at the `ith` position moves to the index specified by `i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2527,
"level": 1,
"question": "You are given a string `s` and an array of indices `indices` of the same length. The string `s` is a **shuffled** version of a given string that has its characters randomly scrambled. Reorder the `s` string such that the character at the `ith` position... |
def is_valid_ipv4_address(ip):
parts = ip.split('.')
if len(parts) != 4:
return False
for part in parts:
if not part.isdigit():
return False
if len(part) > 1 and part[0] == '0':
return False
num = int(part)
if num < 0 or num > 255:
... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code snippet to check if a string is a valid IPv4 address?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2528,
"level": 1,
"question": "Can you provide a Python code snippet to check if a string is a valid IPv4 address?",
"split": "train"
} |
def merge_sorted_lists(list1: list[int], list2: list[int]) -> list[int]:
result = []
i = j = 0
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 any r... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nImplement a function that merges two sorted lists into one sorted list. The two input lists are sorted in non-decreasing order, and you must ensure the resultant list is also sorted in non-decreasing order.\n\n### Function Signature\n\n```python\ndef merge_sorte... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2529,
"level": 1,
"question": "### Problem Statement\n\nImplement a function that merges two sorted lists into one sorted list. The two input lists are sorted in non-decreasing order, and you must ensure the resultant list is also sorted in non-decreasing order.\n\n### Function Sign... |
import struct
def modify_binary_data(data: bytes, target: int, replacement: int) -> bytes:
# Extract the integer and string parts from the binary data
integer_bytes = data[:20]
string_bytes = data[20:]
# Unpack the integer bytes into a tuple of integers
integers = struct.unpack('>5I', integer_... | simplelr_Docs | [
{
"content": "Question:\n**Coding Assessment Question**\n\n### Objective:\nImplement a function that combines manipulating packed binary data and encoding/decoding operations. Your task is to decode a given binary data stream, modify specific data within it, and then re-encode it back to a binary format.\n\n###... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2530,
"level": 1,
"question": "**Coding Assessment Question**\n\n### Objective:\nImplement a function that combines manipulating packed binary data and encoding/decoding operations. Your task is to decode a given binary data stream, modify specific data within it, and then re-encode... |
def maximizeProfit(prices):
if len(prices) < 2:
return 0
min_price = prices[0]
max_profit = 0
for price in prices[1:]:
current_profit = price - min_price
if current_profit > max_profit:
max_profit = current_profit
if price < min_price:
min_price = ... | simplelr_Taco | [
{
"content": "Question:\nYou are given an array representing the stock prices of a company in chronological order. Write a function `maximizeProfit(prices)` that returns the maximum profit that can be achieved by buying one stock and then selling it later. If no profit can be achieved, return 0. The purchase mu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2531,
"level": 1,
"question": "You are given an array representing the stock prices of a company in chronological order. Write a function `maximizeProfit(prices)` that returns the maximum profit that can be achieved by buying one stock and then selling it later. If no profit can be ... |
def length_of_longest_subarray(nums):
last_seen = {}
max_length = 0
left = 0
for right in range(len(nums)):
num = nums[right]
if num in last_seen and last_seen[num] >= left:
left = last_seen[num] + 1
last_seen[num] = right
current_length = right - left + 1
... | simplelr_Apps | [
{
"content": "Question:\nCreate a function that takes an array of integers as input and returns the length of the longest contiguous subarray that contains no duplicate numbers. The array may contain both positive and negative numbers. Write the function to solve this problem.\n\n```if:shell\nIn bash, the scrip... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2532,
"level": 1,
"question": "Create a function that takes an array of integers as input and returns the length of the longest contiguous subarray that contains no duplicate numbers. The array may contain both positive and negative numbers. Write the function to solve this problem.... |
def has_two_sum(arr, target):
seen = set()
for num in arr:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes an array of integers and a target integer, and determines if there are two distinct elements in the array, whose sum is equal to the target integer. Return a boolean (True or False).\n\nExample 1:\nInput: [2, 7, 11, 15], 9\nOutput: True (because 2 + 7 = 9)\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2533,
"level": 1,
"question": "Write a function that takes an array of integers and a target integer, and determines if there are two distinct elements in the array, whose sum is equal to the target integer. Return a boolean (True or False).\n\nExample 1:\nInput: [2, 7, 11, 15], 9\n... |
import torch
def stable_batched_matrix_multiplication(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
"""
Args:
A: A 3D tensor of shape (batch_size, m, n)
B: A 3D tensor of shape (batch_size, n, p)
Returns:
A 3D tensor of shape (batch_size, m, p) resulting from the matri... | simplelr_Docs | [
{
"content": "Question:\n**Problem Statement:**\n\nIn this coding assessment, you are required to implement a custom PyTorch function that performs numerically stable batched matrix multiplication. The implementation should account for potential issues such as overflow with extremal values, and ensure consisten... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2534,
"level": 1,
"question": "**Problem Statement:**\n\nIn this coding assessment, you are required to implement a custom PyTorch function that performs numerically stable batched matrix multiplication. The implementation should account for potential issues such as overflow with ex... |
from typing import List
def rotate_matrix(matrix: List[List[int]]) -> None:
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse()
| simplelr_Taco | [
{
"content": "Question:\nGiven an n x n matrix, create a function that rotates the matrix by 90 degrees clockwise. The rotation should be done in-place, meaning you should modify the input matrix directly without using any extra memory. \n\nFunction Signature: `def rotate_matrix(matrix: List[List[int]]) -> None... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2535,
"level": 1,
"question": "Given an n x n matrix, create a function that rotates the matrix by 90 degrees clockwise. The rotation should be done in-place, meaning you should modify the input matrix directly without using any extra memory. \n\nFunction Signature: `def rotate_matr... |
import heapq
def find_shortest_paths(n, edges, source):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
distances = [float("inf")] * n
distances[source] = 0
heap = []
heapq.heappush(heap, (0, source))
while heap:
current_dist, u = heap... | simplelr_Data_Structure | [
{
"content": "Question:\n### Dijkstra's Modified Assessment\n\nYou are working as a software engineer at a delivery company. Your task is to develop a software module that finds the shortest delivery routes between warehouses in a city. Each warehouse is identified by a unique ID, and routes between them are re... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2536,
"level": 1,
"question": "### Dijkstra's Modified Assessment\n\nYou are working as a software engineer at a delivery company. Your task is to develop a software module that finds the shortest delivery routes between warehouses in a city. Each warehouse is identified by a unique... |
def reverse_sentence(s):
return ' '.join(s.split()[::-1])
| simplelr_Taco | [
{
"content": "Question:\nYou are given a string that represents a sentence. Write a function that returns a new string with the words in reverse order. Punctuation and capitalization should remain in their original positions.\n\n### Examples\n```python\nreverse_sentence(\"Hello, world!\") --> \"world! Hello,\"\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2537,
"level": 1,
"question": "You are given a string that represents a sentence. Write a function that returns a new string with the words in reverse order. Punctuation and capitalization should remain in their original positions.\n\n### Examples\n```python\nreverse_sentence(\"Hell... |
def is_valid_matrix(matrix):
m = len(matrix)
if m == 0:
return True
n = len(matrix[0])
# Check each row is non-decreasing
for row in matrix:
for i in range(n - 1):
if row[i] > row[i + 1]:
return False
# Check each column is non-decreasing
... | simplelr_Taco | [
{
"content": "Question:\nGiven an m x n matrix filled with integers, write a function to determine whether the matrix meets the following requirements:\n\n1. Every element in the matrix satisfies the condition that it is greater than or equal to every element below it in the same column.\n2. Every element in th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2538,
"level": 1,
"question": "Given an m x n matrix filled with integers, write a function to determine whether the matrix meets the following requirements:\n\n1. Every element in the matrix satisfies the condition that it is greater than or equal to every element below it in the s... |
def length_of_last_word(s):
words = s.split()
if not words:
return 0
return len(words[-1]) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the length of the last word of a given string. The last word is defined as the last sequence of characters separated by spaces. For example, if the input string is \"Hello World\", the function should return 5, as \"World\" has 5 characters. If there are ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2539,
"level": 1,
"question": "Write a python function to find the length of the last word of a given string. The last word is defined as the last sequence of characters separated by spaces. For example, if the input string is \"Hello World\", the function should return 5, as \"Worl... |
import heapq
def merge_k_sorted_lists(lists):
heap = []
for list_idx, lst in enumerate(lists):
if lst:
heapq.heappush(heap, (lst[0], list_idx, 0))
result = []
while heap:
current_val, list_idx, current_pos = heapq.heappop(heap)
result.append(current_val)
... | simplelr_Codeforces | [
{
"content": "Question:\nWrite a program that simulates the merging of multiple sorted lists into a single sorted list.\n\nGiven a list of k sorted integer lists, your task is to merge these k lists into a single sorted list.\n\nYou need to implement a function that takes a single argument:\n- A list of k sorte... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2540,
"level": 1,
"question": "Write a program that simulates the merging of multiple sorted lists into a single sorted list.\n\nGiven a list of k sorted integer lists, your task is to merge these k lists into a single sorted list.\n\nYou need to implement a function that takes a si... |
def num_of_splits(nums):
n = len(nums)
if n < 2:
return 0
max_left = [0] * n
max_left[0] = nums[0]
for i in range(1, n):
max_left[i] = max(max_left[i-1], nums[i])
min_right = [0] * n
min_right[-1] = nums[-1]
for i in range(n-2, -1, -1):
min_right[i] = mi... | simplelr_Leetcode | [
{
"content": "Question:\nAn array `nums` of length `n` contains positive integers. A **split** of the array is defined as dividing the array into two contiguous subarrays such that each element in the first subarray is **less than** or **equal to** each element in the second subarray. The goal is to determine t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2541,
"level": 1,
"question": "An array `nums` of length `n` contains positive integers. A **split** of the array is defined as dividing the array into two contiguous subarrays such that each element in the first subarray is **less than** or **equal to** each element in the second s... |
def generate_leaderboard(sessions):
total = {}
for session in sessions:
for name, score in session.items():
total[name] = total.get(name, 0) + score
# Sort by descending score and ascending name for ties
leaders = sorted(total.items(), key=lambda x: (-x[1], x[0]))
return leaders | simplelr_Package | [
{
"content": "Question:\nYou are developing a simple online game and need to track the scores of players. Each game session produces a dictionary containing the names of the players and their corresponding scores. You need to combine the scores from multiple game sessions to generate a cumulative leaderboard.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2542,
"level": 1,
"question": "You are developing a simple online game and need to track the scores of players. Each game session produces a dictionary containing the names of the players and their corresponding scores. You need to combine the scores from multiple game sessions to g... |
def power_set(s):
elements = list(s)
n = len(elements)
subsets = []
for i in range(2 ** n):
subset = set()
for j in range(n):
if (i >> j) & 1:
subset.add(elements[j])
subsets.append(subset)
return subsets | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to generate the power set of a given set. The power set of a set is the set of all subsets of the set, including the empty set and the set itself.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2543,
"level": 1,
"question": "Write a python function to generate the power set of a given set. The power set of a set is the set of all subsets of the set, including the empty set and the set itself.",
"split": "train"
} |
def max_subarray_sum(arr):
if not arr:
return 0
current_max = max_so_far = arr[0]
for num in arr[1:]:
current_max = max(num, current_max + num)
max_so_far = max(max_so_far, current_max)
return max_so_far | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers, find the maximum sum of a contiguous subarray.\n\nThe array may contain both positive and negative integers and the solution should have a time complexity of O(n).\n\nExample:\n\nInput: [-2,1,-3,4,-1,2,1,-5,4]\n\nOutput: 6\n\nExplanation: The contiguous subar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2544,
"level": 1,
"question": "Given an array of integers, find the maximum sum of a contiguous subarray.\n\nThe array may contain both positive and negative integers and the solution should have a time complexity of O(n).\n\nExample:\n\nInput: [-2,1,-3,4,-1,2,1,-5,4]\n\nOutput: 6\n... |
def filter_people(people):
result = []
for person in people:
if 'name' in person and 'age' in person:
age = person['age']
if isinstance(age, int) and age > 0:
result.append({'name': person['name'], 'age': age})
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of dictionaries representing people and returns a list of dictionaries with only the 'name' and 'age' keys. The function should filter out any other keys and also remove any entries where the 'age' key is missing or not a positive integer.\nAnsw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2545,
"level": 1,
"question": "Write a Python function that takes a list of dictionaries representing people and returns a list of dictionaries with only the 'name' and 'age' keys. The function should filter out any other keys and also remove any entries where the 'age' key is missi... |
import math
def min_trials(n: int, k: int) -> int:
m = 0
while True:
m += 1
current = 0
for i in range(1, k + 1):
if i > m:
break
current += math.comb(m, i)
if current >= n:
break
if current >= n:
re... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are to implement a function that determines the minimum number of moves required to find the critical floor in the worst case with the given number of eggs and floors. The critical floor is the highest floor from which eggs can be dropped without breaking.\n\n### Inputs:\n1. **n** (... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2546,
"level": 1,
"question": "You are to implement a function that determines the minimum number of moves required to find the critical floor in the worst case with the given number of eggs and floors. The critical floor is the highest floor from which eggs can be dropped without b... |
def longestCommonSubstring(A, B):
m = len(A)
n = len(B)
dp = [[0] * (n + 1) for _ in range(m + 1)]
max_len = 0
end_i = 0 # Ending index of the longest common substring in A
for i in range(1, m + 1):
for j in range(1, n + 1):
if A[i-1] == B[j-1]:
dp[i][j] = d... | simplelr_Apps | [
{
"content": "Question:\nYou are given two strings A and B of lengths m and n respectively. Your task is to find the longest substring that appears in both A and B. The substring must occur contiguously in both strings.\n\nWrite a function `longestCommonSubstring` that takes two strings, A and B, and returns th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2547,
"level": 1,
"question": "You are given two strings A and B of lengths m and n respectively. Your task is to find the longest substring that appears in both A and B. The substring must occur contiguously in both strings.\n\nWrite a function `longestCommonSubstring` that takes t... |
def process_strings(strings: list) -> dict:
# Filter out empty or whitespace-only strings
filtered = list(filter(lambda s: s.strip(), strings))
# Create a dictionary mapping each string to the hash of its ASCII representation
return {s: hash(ascii(s)) for s in filtered}
| simplelr_Docs | [
{
"content": "Question:\nYou are tasked with implementing a function that processes a list of strings and performs several operations using Python's built-in functions. The function should:\n\n1. Filter out strings that are empty or contain only whitespace.\n2. Convert all non-empty strings to their ASCII repre... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2548,
"level": 1,
"question": "You are tasked with implementing a function that processes a list of strings and performs several operations using Python's built-in functions. The function should:\n\n1. Filter out strings that are empty or contain only whitespace.\n2. Convert all non... |
def fibonacciSum(n):
if n <= 0:
return 0
total = 0
f1, f2 = 0, 1
for _ in range(n):
total += f1
next_f = f1 + f2
f1, f2 = f2, next_f
return total
| simplelr_Taco | [
{
"content": "Question:\n**Write a function named `fibonacciSum` that takes a single integer `n` and returns the sum of the first `n` Fibonacci numbers. The Fibonacci sequence is characterized by the fact that every number after the first two is the sum of the two preceding ones, starting with 0 and 1.**\nAnswe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2549,
"level": 1,
"question": "**Write a function named `fibonacciSum` that takes a single integer `n` and returns the sum of the first `n` Fibonacci numbers. The Fibonacci sequence is characterized by the fact that every number after the first two is the sum of the two preceding on... |
def hasPairWithSum(arr, sumValue):
seen = set()
for num in arr:
complement = sumValue - num
if complement in seen:
return "Yes"
seen.add(num)
return "No"
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers and a sum value. The task is to determine if there are any two distinct elements in the array whose sum is equal to the given sum value. If such a pair exists, return \"Yes\", otherwise return \"No\".\nNote: Use a time-efficient approach with O(N) complexity a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2550,
"level": 1,
"question": "Given an array of integers and a sum value. The task is to determine if there are any two distinct elements in the array whose sum is equal to the given sum value. If such a pair exists, return \"Yes\", otherwise return \"No\".\nNote: Use a time-effici... |
def convert_and_format_string_list(input_list):
# Remove empty strings
non_empty = [s for s in input_list if s]
# Remove duplicates
unique = list(set(non_empty))
# Sort in descending order
sorted_unique = sorted(unique, reverse=True)
# Add parentheses and join
return ', '.join([f'({s})' ... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that converts a given list of strings to a single string, where each element is separated by a comma and a space. The function should also add parentheses around each string element. Additionally, the function should ignore any empty strings in the list and shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2551,
"level": 1,
"question": "Write a Python function that converts a given list of strings to a single string, where each element is separated by a comma and a space. The function should also add parentheses around each string element. Additionally, the function should ignore any ... |
def smallest_and_largest(numbers):
if not numbers:
return None
min_val = max_val = numbers[0]
for num in numbers[1:]:
if num < min_val:
min_val = num
if num > max_val:
max_val = num
return (min_val, max_val) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to compute both the smallest and the largest values in a list of numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2552,
"level": 1,
"question": "Write a function to compute both the smallest and the largest values in a list of numbers.",
"split": "train"
} |
def recursive_sum(lst):
if not lst:
return 0
else:
return lst[0] + recursive_sum(lst[1:]) | simplelr_Filter | [
{
"content": "Question:\nGiven a list of integers, create a function that recursively calculates the sum of all elements without using any built-in sum functions. Additionally, the function should have a time complexity of O(n). The function should be able to handle negative numbers as well as duplicate numbers... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2553,
"level": 1,
"question": "Given a list of integers, create a function that recursively calculates the sum of all elements without using any built-in sum functions. Additionally, the function should have a time complexity of O(n). The function should be able to handle negative n... |
def find_palindromes(lst):
result = []
for s in lst:
lower_s = s.lower()
if lower_s == lower_s[::-1]:
result.append(s)
return result | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes in a list of strings and returns a new list containing all the strings that are palindromes. A palindrome is a string that reads the same forwards and backwards, ignoring case. An empty list or a list with no palindromes should result in an empty list being r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2554,
"level": 1,
"question": "Write a function that takes in a list of strings and returns a new list containing all the strings that are palindromes. A palindrome is a string that reads the same forwards and backwards, ignoring case. An empty list or a list with no palindromes sho... |
def find_peak_element(nums: list[int]) -> int:
low = 0
high = len(nums) - 1
while low < high:
mid = (low + high) // 2
if mid + 1 < len(nums) and nums[mid] < nums[mid + 1]:
low = mid + 1
else:
high = mid
return low | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Find Peak Element in a 1D Array\n\nGiven an array of integers, write a function to find a peak element. An element is a peak if it is greater than its neighbors. For corner elements, consider only one neighbor.\n\n#### Function Signature\n```python\ndef find_peak_element(n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2555,
"level": 1,
"question": "### Question: Find Peak Element in a 1D Array\n\nGiven an array of integers, write a function to find a peak element. An element is a peak if it is greater than its neighbors. For corner elements, consider only one neighbor.\n\n#### Function Signature\... |
def minimum_difference(weights):
total = sum(weights)
max_target = total // 2
dp = [False] * (max_target + 1)
dp[0] = True
for weight in weights:
for j in range(max_target, weight - 1, -1):
if dp[j - weight]:
dp[j] = True
max_sum = 0
for j in ran... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `weights` where `weights[i]` represents the weight of the `i-th` stone. Each stone can be either in the left or right pile. Find the minimum possible absolute difference between the sum of weights in the left pile and the sum of weights in the right pi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2556,
"level": 1,
"question": "You are given an array of integers `weights` where `weights[i]` represents the weight of the `i-th` stone. Each stone can be either in the left or right pile. Find the minimum possible absolute difference between the sum of weights in the left pile and... |
def remove_duplicates(nums):
seen = set()
result = []
for num in nums:
if num not in seen:
seen.add(num)
result.append(num)
return result | simplelr_Filter | [
{
"content": "Question:\nGiven a list of 20K integers ranging from -1000 to 1000, implement a function in Python that removes all duplicates and returns a list with only unique elements, while preserving the original order of the unique elements from the input list. Your function should run in O(n) time complex... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2557,
"level": 1,
"question": "Given a list of 20K integers ranging from -1000 to 1000, implement a function in Python that removes all duplicates and returns a list with only unique elements, while preserving the original order of the unique elements from the input list. Your funct... |
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.multioutput import MultiOutputClassifier
from sklearn.ensemble import RandomForestClassifier
def train_and_predict_multiclass_multioutput(X_train, y_train, X_test):
"""
Train a multiclass-multioutput classifier and predict the label... | simplelr_Docs | [
{
"content": "Question:\n### Multiclass and Multilabel Classification with Scikit-learn\n\n**Objective**: \nYou need to implement a multiclass and multilabel classification algorithm using scikit-learn to classify images of fruits based on their type and color.\n\n**Description**:\nYou are given a dataset that ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2558,
"level": 1,
"question": "### Multiclass and Multilabel Classification with Scikit-learn\n\n**Objective**: \nYou need to implement a multiclass and multilabel classification algorithm using scikit-learn to classify images of fruits based on their type and color.\n\n**Descriptio... |
def first_unique_character(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char in s:
if char_count[char] == 1:
return char
return '_' | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the first unique character in a given string. If all characters are repeating, return an underscore('_').\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2559,
"level": 1,
"question": "Write a function to find the first unique character in a given string. If all characters are repeating, return an underscore('_').",
"split": "train"
} |
from collections import defaultdict
from typing import List, Tuple, Optional
def detect_one_sparse(stream: List[Tuple[int, str]]) -> Optional[int]:
counts = defaultdict(int)
for number, sign in stream:
if sign == '+':
counts[number] += 1
else:
counts[number] -= 1
non... | simplelr_Data_Structure | [
{
"content": "Question:\n1-Sparse Detection from Dynamic Stream\n\nAs a data scientist in a high-frequency trading firm, you need to implement an algorithm to detect if a sequence is 1-sparse. A sequence is considered 1-sparse if, after canceling out repeated elements (sign indicated), there is exactly one uniq... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2560,
"level": 1,
"question": "1-Sparse Detection from Dynamic Stream\n\nAs a data scientist in a high-frequency trading firm, you need to implement an algorithm to detect if a sequence is 1-sparse. A sequence is considered 1-sparse if, after canceling out repeated elements (sign in... |
def longest_substring_with_k_distinct(s: str, k: int) -> int:
from collections import defaultdict
freq = defaultdict(int)
max_len = 0
left = 0
distinct = 0
n = len(s)
for right in range(n):
char = s[right]
if freq[char] == 0:
distinct += 1
freq[char]... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters and an integer `k`. You need to find the length of the longest substring of `s` that contains at most `k` distinct characters.\n\nWrite a function `longest_substring_with_k_distinct(s: str, k: int) -> int` to accomplish ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2561,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters and an integer `k`. You need to find the length of the longest substring of `s` that contains at most `k` distinct characters.\n\nWrite a function `longest_substring_with_k_distinct(s: ... |
def consistently_performing_employees(employeeName, employeeScore):
# Initialize a dictionary to track each employee's scores
score_dict = {}
# Iterate through each name and score pair
for name, score in zip(employeeName, employeeScore):
# Convert score to integer in case it's provided as a... | simplelr_Leetcode | [
{
"content": "Question:\nA company uses a grading system to evaluate employees' performance. Each employee is given a score between 0 and 100 based on their performance. The company wants to create a report that highlights employees who are consistently performing within certain thresholds. \n\nYou are given a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2562,
"level": 1,
"question": "A company uses a grading system to evaluate employees' performance. Each employee is given a score between 0 and 100 based on their performance. The company wants to create a report that highlights employees who are consistently performing within certa... |
import math
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = math.isqrt(n)
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True | simplelr_Data_Structure | [
{
"content": "Question:\n### Context\nIn cryptography and number theory, determining whether a number is prime plays a crucial role. We need to verify the primality of a number efficiently to ensure the security and efficiency of cryptographic algorithms.\n\n### Task\nWrite a function `is_prime(n: int) -> bool`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2563,
"level": 1,
"question": "### Context\nIn cryptography and number theory, determining whether a number is prime plays a crucial role. We need to verify the primality of a number efficiently to ensure the security and efficiency of cryptographic algorithms.\n\n### Task\nWrite a ... |
def count_words(strings: list):
"""Count the occurrences of each word in a list of strings, case insensitively.
Args:
strings: A list of strings.
Returns:
A dictionary with words as keys (in lowercase) and their counts as values.
"""
word_count = {}
for string in strings:
... | simplelr_Evol | [
{
"content": "Question:\nPlease implement a function in Python that takes a list of strings and returns a dictionary where the keys are individual words from the strings, and the values represent the count of how many times each word appeared across all input strings. Words should be treated case insensitively,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2564,
"level": 1,
"question": "Please implement a function in Python that takes a list of strings and returns a dictionary where the keys are individual words from the strings, and the values represent the count of how many times each word appeared across all input strings. Words sh... |
def remove_duplicates(s):
seen = set()
result = []
for char in s:
if char not in seen:
seen.add(char)
result.append(char)
return ''.join(result) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that can take a string of text, remove any duplicate characters, and then return the result as a new string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2565,
"level": 1,
"question": "Create a function that can take a string of text, remove any duplicate characters, and then return the result as a new string.",
"split": "train"
} |
def find_consecutives(nums):
if not nums:
return []
result = []
seen = set()
prev = nums[0]
count = 1
for num in nums[1:]:
if num == prev:
count += 1
if count == 2 and num not in seen:
result.append(num)
seen.add(n... | simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, write a function to find all the elements that appear more than once in the list but appear consecutively. The function should return these elements in a list in the order they first appear. Your implementation should have a time complexity of O(n).\n\n### Exam... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2566,
"level": 1,
"question": "Given a list of integers, write a function to find all the elements that appear more than once in the list but appear consecutively. The function should return these elements in a list in the order they first appear. Your implementation should have a t... |
def is_subset_sum(nums, target):
dp = [False] * (target + 1)
dp[0] = True # Base case: empty subset sums to 0
for num in nums:
# Start from the end to avoid using the same number multiple times in the same subset
for s in range(target, num - 1, -1):
if dp[s - num]:
... | simplelr_Apps | [
{
"content": "Question:\nYou are given an array of integers and a target integer. Determine if there exists a subset of the array that adds up to exactly the target number.\n\nNote:\n\n1. Each of the array elements will not exceed 1000.\n2. The array size will not exceed 100.\n\nExample 1:\n\nInput: [2, 3, 7, 8... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2567,
"level": 1,
"question": "You are given an array of integers and a target integer. Determine if there exists a subset of the array that adds up to exactly the target number.\n\nNote:\n\n1. Each of the array elements will not exceed 1000.\n2. The array size will not exceed 100.\... |
my_strings = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']
def get_long_strings(strings):
return [string for string in strings if len(string) > 5]
long_strings = get_long_strings(my_strings)
print(long_strings) | simplelr_Filter | [
{
"content": "Question:\nHere is the list of strings that I have:\n```python\nmy_strings = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']\n```\nI need to write a function that will return a new list containing only the words that have more than 5 characters. \n\nHere is my attempt at writin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2568,
"level": 1,
"question": "Here is the list of strings that I have:\n```python\nmy_strings = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']\n```\nI need to write a function that will return a new list containing only the words that have more than 5 character... |
def longest_even_subsequence(nums):
max_length = 0
current_length = 0
for num in nums:
if num % 2 == 0:
current_length += 1
if current_length > max_length:
max_length = current_length
else:
current_length = 0
return max_length | simplelr_Apps | [
{
"content": "Question:\nWrite a function `longest_even_subsequence` that takes a list of integers as input and returns the length of the longest contiguous subsequence where all numbers are even. If there are no even numbers, the function should return 0.\n\nExamples:\n```python\nlongest_even_subsequence([1, 2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2569,
"level": 1,
"question": "Write a function `longest_even_subsequence` that takes a list of integers as input and returns the length of the longest contiguous subsequence where all numbers are even. If there are no even numbers, the function should return 0.\n\nExamples:\n```pyt... |
from collections import defaultdict, Counter
def find_smallest_window(s: str, t: str) -> str:
if len(t) > len(s):
return ""
t_count = Counter(t)
required_unique = len(t_count)
s_count = defaultdict(int)
have = 0
left = 0
min_length = float('inf')
min_window = ""
fo... | simplelr_Algorithm | [
{
"content": "Question:\n### Question:\n\nYou are to implement a function that finds the smallest window in a string containing all the characters of another given string.\n\n**Objective:**\nWrite the function `find_smallest_window`.\n\n1. `find_smallest_window(s: str, t: str) -> str`:\n - Finds the smallest ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2570,
"level": 1,
"question": "### Question:\n\nYou are to implement a function that finds the smallest window in a string containing all the characters of another given string.\n\n**Objective:**\nWrite the function `find_smallest_window`.\n\n1. `find_smallest_window(s: str, t: str)... |
def is_pangram(s):
letters = {c.lower() for c in s if 'a' <= c.lower() <= 'z'}
return len(letters) == 26 | simplelr_Filter | [
{
"content": "Question:\nGenerate a whitespace and punctuation-insensitive function in Python. The function should check if a given string is a pangram — a phrase that contains every letter of the alphabet. For instance, \"The five box jersey zip code thru just winksvyqx\" is a pangram because it contains all t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2571,
"level": 1,
"question": "Generate a whitespace and punctuation-insensitive function in Python. The function should check if a given string is a pangram — a phrase that contains every letter of the alphabet. For instance, \"The five box jersey zip code thru just winksvyqx\" is ... |
import json
def parse_json_file(filename):
try:
with open(filename, 'r') as file:
data = json.load(file)
return data
except FileNotFoundError:
print(f"File not found: {filename}")
return None
except json.JSONDecodeError as e:
print(f"Error parsing JSO... | simplelr_Filter | [
{
"content": "Question:\nI have a JSON file and I need to write a function that will be able to parse it and return the results in a dictionary.\n\nHere is a sample JSON file:\n```\n{\n \"name\": \"John\",\n \"age\": 30,\n \"address\": {\n \"street\": \"123 Main St\",\n \"city\": \"Anytow... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2572,
"level": 1,
"question": "I have a JSON file and I need to write a function that will be able to parse it and return the results in a dictionary.\n\nHere is a sample JSON file:\n```\n{\n \"name\": \"John\",\n \"age\": 30,\n \"address\": {\n \"street\": \"123 Mai... |
from collections import Counter
def can_form_palindrome(s):
# Preprocess the string: lowercase and remove non-alphanumeric characters
clean_s = ''.join([c.lower() for c in s if c.isalnum()])
# Count the frequency of each character
count = Counter(clean_s)
# Count how many characters have odd freque... | simplelr_Taco | [
{
"content": "Question:\nGiven a string, determine if it can be rearranged to form a palindrome. A palindrome is a word or phrase that reads the same forwards and backwards, ignoring spaces, punctuation, and capitalization.\n\nExamples:\n\n```python\n\"civic\" => true (already a palindrome)\n\"ivicc\" => true (... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2573,
"level": 1,
"question": "Given a string, determine if it can be rearranged to form a palindrome. A palindrome is a word or phrase that reads the same forwards and backwards, ignoring spaces, punctuation, and capitalization.\n\nExamples:\n\n```python\n\"civic\" => true (already... |
def is_anagram(word1, word2):
# Process each word to include only lowercase alphabetic characters
processed1 = [c.lower() for c in word1 if c.isalpha()]
processed2 = [c.lower() for c in word2 if c.isalpha()]
# If lengths differ, they cannot be anagrams
if len(processed1) != len(processed2):
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that checks if a given word is an anagram of another word. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function should be case-insensitive and ignore an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2574,
"level": 1,
"question": "Write a Python function that checks if a given word is an anagram of another word. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function shoul... |
def calculate_course_averages(students):
courses = {}
for student in students:
for course, grade in student.items():
if course in courses:
courses[course][0] += grade
courses[course][1] += 1
else:
courses[course] = [grade, 1]
av... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes a list of dictionaries, where each dictionary represents a student's grades in a course, and returns a new dictionary with the average grade for each course. Each student's dictionary contains course names as keys and their corresponding grades as valu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2575,
"level": 1,
"question": "Write a Python function that takes a list of dictionaries, where each dictionary represents a student's grades in a course, and returns a new dictionary with the average grade for each course. Each student's dictionary contains course names as keys and... |
from typing import List
def sort_colors(nums: List[int]) -> None:
low = 0
high = len(nums) - 1
i = 0
while i <= high:
if nums[i] == 0:
nums[low], nums[i] = nums[i], nums[low]
low += 1
i += 1
elif nums[i] == 1:
i += 1
else:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\n\n#### Context\nYou are part of the team developing an automated sorting mechanism for a factory that produces colored balls. The balls come in three colors: red, white, and blue. Each color is represented by a distinct integer: red (0), white (1), and blue (2).\n\n#### Pr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2576,
"level": 1,
"question": "### Question\n\n#### Context\nYou are part of the team developing an automated sorting mechanism for a factory that produces colored balls. The balls come in three colors: red, white, and blue. Each color is represented by a distinct integer: red (0), ... |
def addNumbers(num1, num2):
for num in (num1, num2):
if type(num) is not int:
raise ValueError("Invalid input: input must be a positive integer between 1 and 100")
if not (1 <= num <= 100):
raise ValueError("Invalid input: input must be a positive integer between 1 and 100")
... | simplelr_Filter | [
{
"content": "Question:\nCreate a function 'addNumbers' that takes in two integers and returns their sum. The function should only accept positive integers between 1 and 100 as inputs. If the input is outside of this range, the function should throw an error with the message \"Invalid input: input must be a pos... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2577,
"level": 1,
"question": "Create a function 'addNumbers' that takes in two integers and returns their sum. The function should only accept positive integers between 1 and 100 as inputs. If the input is outside of this range, the function should throw an error with the message \... |
def min_val(lst):
if len(lst) == 1:
return lst[0]
else:
min_rest = min_val(lst[1:])
return min(lst[0], min_rest)
print(min_val([1, 2, 3, 4, 5])) | simplelr_Filter | [
{
"content": "Question:\ndef min_val(lst):\n if len(lst) == 1:\n return lst[0]\n else:\n min_rest = min_val(lst[1:])\n return min(lst[0], min_rest)\n \nprint(min_val([1, 2, 3, 4, 5]))\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2578,
"level": 1,
"question": "def min_val(lst):\n if len(lst) == 1:\n return lst[0]\n else:\n min_rest = min_val(lst[1:])\n return min(lst[0], min_rest)\n \nprint(min_val([1, 2, 3, 4, 5]))",
"split": "train"
} |
def calculate_parity(n: int) -> int:
return bin(n).count('1') % 2 | simplelr_Algorithm | [
{
"content": "Question:\n## Scenario\nRecent advancements in data encoding techniques have led to an increased focus on understanding various representations of numbers and strings. You are tasked with using your skills in bitwise operations and binary manipulations to solve a problem involving the parity of bi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2579,
"level": 1,
"question": "## Scenario\nRecent advancements in data encoding techniques have led to an increased focus on understanding various representations of numbers and strings. You are tasked with using your skills in bitwise operations and binary manipulations to solve a... |
def merge_and_sort_dicts(dict1, dict2):
# Create a new dictionary to hold the merged result
merged_dict = {}
# Collect all unique keys from both dictionaries
all_keys = dict1.keys() | dict2.keys()
# Merge the dictionaries by summing the values of common keys
for key in all_keys:
merged_d... | simplelr_Package | [
{
"content": "Question:\nCreate a function called `merge_and_sort_dicts` that takes two parameters: `dict1` and `dict2`, which are both dictionaries. The function should return a list of tuples, where each tuple contains a key-value pair from the merged dictionary, and the list is sorted by keys in ascending or... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2580,
"level": 1,
"question": "Create a function called `merge_and_sort_dicts` that takes two parameters: `dict1` and `dict2`, which are both dictionaries. The function should return a list of tuples, where each tuple contains a key-value pair from the merged dictionary, and the lis... |
def find_difference(s: str, t: str) -> str:
res = 0
for c in s:
res ^= ord(c)
for c in t:
res ^= ord(c)
return chr(res) | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Finding the Additional Character\n\n#### Objective\nImplement a function that receives two strings, \\(s\\) and \\(t\\), where \\(t\\) is created by shuffling the characters in \\(s\\) and adding one additional character. Your task is to find that additional character.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2581,
"level": 1,
"question": "### Question: Finding the Additional Character\n\n#### Objective\nImplement a function that receives two strings, \\(s\\) and \\(t\\), where \\(t\\) is created by shuffling the characters in \\(s\\) and adding one additional character. Your task is to ... |
import math
def generate_primes(n):
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(math.sqrt(n)) + 1):
if sieve[i]:
sieve[i*i : n+1 : i] = [False] * len(sieve[i*i : n+1 : i])
primes = [i for i, is_prime in enumerate(sieve) ... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that generates a sequence of prime numbers up to a specified maximum value `n`. The function should return a list of all prime numbers found within the range from 2 up to and including `n`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2582,
"level": 1,
"question": "Create a function that generates a sequence of prime numbers up to a specified maximum value `n`. The function should return a list of all prime numbers found within the range from 2 up to and including `n`.",
"split": "train"
} |
def is_palindrome(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1]) | simplelr_Filter | [
{
"content": "Question:\nHere is a pseudocode for a recursive algorithm that determines whether a given number is a palindrome:\n```\nf(n):\n if digit_count(n) <= 1:\n return True\n if first_digit(n) != last_digit(n):\n return False\n return f(n without first and last digits)\n```\nI'd like to convert ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2583,
"level": 1,
"question": "Here is a pseudocode for a recursive algorithm that determines whether a given number is a palindrome:\n```\nf(n):\n if digit_count(n) <= 1:\n return True\n if first_digit(n) != last_digit(n):\n return False\n return f(n without first and last... |
from typing import List
def sum_of_unique_elements(lst: List[int]) -> int:
counts = {}
for num in lst:
counts[num] = counts.get(num, 0) + 1
sum_unique = 0
for num, count in counts.items():
if count == 1:
sum_unique += num
return sum_unique | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of Unique Elements\n\n#### Context:\nYou are tasked with writing a function to calculate the sum of all unique elements in an input list. Identifying unique elements and summing them up can have applications in data analysis, statistical computations, and financial algorithms.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2584,
"level": 1,
"question": "### Sum of Unique Elements\n\n#### Context:\nYou are tasked with writing a function to calculate the sum of all unique elements in an input list. Identifying unique elements and summing them up can have applications in data analysis, statistical comput... |
def prime_factors(n):
if n < 2:
return []
factors = []
# Divide by 2 until n is odd
while n % 2 == 0:
factors.append(2)
n = n // 2
# Check for odd factors up to sqrt(n)
i = 3
while i * i <= n:
while n % i == 0:
factors.append(i)
n = n /... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code to find the prime factorization of a given number?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2585,
"level": 1,
"question": "Can you provide a Python code to find the prime factorization of a given number?",
"split": "train"
} |
from dateutil import parser
from datetime import timezone
from typing import List
def format_timestamps(timestamps: List[str]) -> List[str]:
result = []
for ts in timestamps:
dt_obj = parser.parse(ts)
if dt_obj.tzinfo is not None:
dt_obj = dt_obj.astimezone(timezone.utc)
els... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nAs part of a data processing pipeline, you need to transform a list of timestamps into a more human-readable format. This task will test your understanding of date and time manipulation, along with your ability to handle various input formats gracefully.\n\n### Task\nWrite... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2586,
"level": 1,
"question": "### Scenario\nAs part of a data processing pipeline, you need to transform a list of timestamps into a more human-readable format. This task will test your understanding of date and time manipulation, along with your ability to handle various input for... |
def remove_k_digits(num, k):
stack = []
for digit in num:
# Remove digits from the stack as long as we can make a smaller number
while k > 0 and stack and stack[-1] > digit:
stack.pop()
k -= 1
stack.append(digit)
# If there are still digits to remove, remove f... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `str`, containing digits from `0` to `9`. Your task is to return the smallest number possible after removing exactly `k` digits from the string. The output should be in string format with no leading zeros. If the resultant number is empty, return `\"0\"`.\nAnswer:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2587,
"level": 1,
"question": "You are given a string `str`, containing digits from `0` to `9`. Your task is to return the smallest number possible after removing exactly `k` digits from the string. The output should be in string format with no leading zeros. If the resultant number... |
def can_segment_string(s, k):
if len(s) % k != 0:
return []
result = []
for i in range(0, len(s), k):
word = s[i:i+k]
if len(set(word)) != k:
return []
result.append(word)
return result | simplelr_Evol | [
{
"content": "Question:\nGiven a string s made up of lowercase letters and an integer k, write a function to determine if s can be segmented into a space-separated sequence of words such that each word is of length k and consists of unique characters only. If possible, return such a sequence, otherwise return a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2588,
"level": 1,
"question": "Given a string s made up of lowercase letters and an integer k, write a function to determine if s can be segmented into a space-separated sequence of words such that each word is of length k and consists of unique characters only. If possible, return ... |
def euler_totient(n: int) -> int:
"""
Returns the count of integers between 1 and n inclusive
that are coprime with n.
Parameters:
n (int): The integer n to calculate the totsient function for.
Returns:
int: The count of coprime integers.
"""
if n == 1:
return 1
result ... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are working on an encryption project and need to efficiently determine the number of integers that are coprime with a given number n. A function `euler_totient(n)` calculates this by enumerating potential divisors and reducing the input value iteratively. \n\nImplement the `euler_to... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2589,
"level": 1,
"question": "You are working on an encryption project and need to efficiently determine the number of integers that are coprime with a given number n. A function `euler_totient(n)` calculates this by enumerating potential divisors and reducing the input value itera... |
def maximize_sweetness(candies, k):
if not candies or k == 0:
return 0
candies_sorted = sorted(candies, reverse=True)
take = min(k, len(candies_sorted))
return sum(candies_sorted[:take]) | simplelr_Leetcode | [
{
"content": "Question:\nA bag contains a large number of different types of candies, where each type of candy has a different sweetness level. You are given an array `candies` of length `n`, where `candies[i]` represents the sweetness level of the `i-th` candy. You are also given an integer `k`, which represen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2590,
"level": 1,
"question": "A bag contains a large number of different types of candies, where each type of candy has a different sweetness level. You are given an array `candies` of length `n`, where `candies[i]` represents the sweetness level of the `i-th` candy. You are also g... |
def multiply_matrix(matrix, multiplier):
return [[x * multiplier for x in row] for row in matrix]
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that accepts a rectangular matrix (two dimensional array) and an integer. The matrix is of size `M x N` (where `M` represents rows and `N` represents columns), containing only integers. The function should return a new matrix where each element is multiplied by the give... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2591,
"level": 1,
"question": "Write a function that accepts a rectangular matrix (two dimensional array) and an integer. The matrix is of size `M x N` (where `M` represents rows and `N` represents columns), containing only integers. The function should return a new matrix where eac... |
def max_sum_non_adjacent(arr: list) -> int:
if not arr:
return 0
include = 0
exclude = 0
for num in arr:
new_include = exclude + num
new_exclude = max(include, exclude)
include, exclude = new_include, new_exclude
return max(include, exclude) | simplelr_Algorithm | [
{
"content": "Question:\n### Problem: Maximum Sum of Non-Adjacent Elements\n\nGiven an array of integers, write a function `max_sum_non_adjacent(arr: list) -> int` that returns the maximum sum of non-adjacent elements. You are not allowed to take two adjacent elements from the array. If the array is empty, the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2592,
"level": 1,
"question": "### Problem: Maximum Sum of Non-Adjacent Elements\n\nGiven an array of integers, write a function `max_sum_non_adjacent(arr: list) -> int` that returns the maximum sum of non-adjacent elements. You are not allowed to take two adjacent elements from the... |
def F(x):
if x < 1400:
return (x - 1000) ** 3
else:
return x + 100 | simplelr_Filter | [
{
"content": "Question:\nF(x) is a function in which when x is less than 1400, (x-1000)^3 is returned and when it's equal to or greater than 1400, the value of x+100 is returned. Write this function in python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2593,
"level": 1,
"question": "F(x) is a function in which when x is less than 1400, (x-1000)^3 is returned and when it's equal to or greater than 1400, the value of x+100 is returned. Write this function in python.",
"split": "train"
} |
def longest_unique_substring(s):
max_length = 0
start = 0
char_index = {}
for end in range(len(s)):
current_char = s[end]
if current_char in char_index:
# Move start to the position right after the last occurrence of current_char
start = max(start, char_index[curr... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that, given a string, returns the length of the longest substring with all unique characters. Provide a solution that is efficient in terms of time complexity. Additionally, write test cases to validate your function using edge cases, such as an empty string, a s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2594,
"level": 1,
"question": "Write a Python function that, given a string, returns the length of the longest substring with all unique characters. Provide a solution that is efficient in terms of time complexity. Additionally, write test cases to validate your function using edge ... |
def int_to_binary_string(n):
return bin(n)[2:] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to convert an integer to its binary representation as a string without the '0b' prefix.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2595,
"level": 1,
"question": "Write a function to convert an integer to its binary representation as a string without the '0b' prefix.",
"split": "train"
} |
def rotate_string(s, num):
if not s or num == 0:
return s
shift = num % len(s)
return s[-shift:] + s[:-shift] | simplelr_Filter | [
{
"content": "Question:\nHello, I need to create a function in Python that takes a string and a number as input and returns a new string where the characters in the input string are rotated to the right by the given number of positions. For example, if the input string is \"hello\" and the number is 2, the outp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2596,
"level": 1,
"question": "Hello, I need to create a function in Python that takes a string and a number as input and returns a new string where the characters in the input string are rotated to the right by the given number of positions. For example, if the input string is \"he... |
from typing import List
def manipulate_bytearray(strings: List[str]) -> bytearray:
# Concatenate the list of strings into a single bytearray
concatenated = bytearray(''.join(strings), 'utf-8')
# Replace each space with an underscore
for i in range(len(concatenated)):
if concatenated[i] == ... | simplelr_Docs | [
{
"content": "Question:\n### Byte Array Manipulation\n\n#### Objective\nImplement a Python function that receives a list of strings and performs a series of operations using bytearray objects. The function should:\n\n1. Concatenate strings into a single bytearray.\n2. Modify the bytearray by replacing spaces wi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2597,
"level": 1,
"question": "### Byte Array Manipulation\n\n#### Objective\nImplement a Python function that receives a list of strings and performs a series of operations using bytearray objects. The function should:\n\n1. Concatenate strings into a single bytearray.\n2. Modify t... |
def sort_numbers_in_string(input_string: str) -> list:
"""
Extracts all the numbers from a given string and returns them as a sorted list of integers.
Args:
input_string (str): A string containing words and numbers separated by spaces.
Returns:
list: A sorted list of integers extracted from th... | simplelr_Algorithm | [
{
"content": "Question:\n### Task\n\nWrite a function that accepts a string containing a mix of words and numbers (separated by spaces) and returns a list of the numbers in sorted order.\n\n#### Function Signature\n```python\ndef sort_numbers_in_string(input_string: str) -> list:\n \"\"\"\n Extracts all t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2598,
"level": 1,
"question": "### Task\n\nWrite a function that accepts a string containing a mix of words and numbers (separated by spaces) and returns a list of the numbers in sorted order.\n\n#### Function Signature\n```python\ndef sort_numbers_in_string(input_string: str) -> li... |
def count_words(s):
return len(s.split()) | simplelr_Filter | [
{
"content": "Question:\nCan you generate a Python code to count the number of words in a given string using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2599,
"level": 1,
"question": "Can you generate a Python code to count the number of words in a given string using Python?",
"split": "train"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.