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 is_valid(expression):
stack = []
closer_to_opener = {')': '(', '}': '{', ']': '['}
for char in expression:
if char in ['(', '{', '[']:
stack.append(char)
elif char in closer_to_opener:
if not stack:
return False
top = stack.pop()
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a string expression containing characters '(', ')', '{', '}', '[' and ']', including any alphanumeric characters and spaces. Your task is to determine if the string contains valid groups of these parentheses.\n\nA string containing any set of parentheses is valid if:\n1. E... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3900,
"level": 1,
"question": "You are given a string expression containing characters '(', ')', '{', '}', '[' and ']', including any alphanumeric characters and spaces. Your task is to determine if the string contains valid groups of these parentheses.\n\nA string containing any se... |
def longest_substring_two_distinct(s):
left = 0
max_len = 0
char_count = {}
for right in range(len(s)):
char = s[right]
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# If the number of distinct characters exceeds ... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a string s consisting of lowercase and uppercase Latin letters and returns the length of the longest substring containing at most two distinct characters. For example, given s = \"eceba\", the function should return 3 (substring \"ece\").\nAnswer:\nLet's thin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3901,
"level": 1,
"question": "Write a function that takes a string s consisting of lowercase and uppercase Latin letters and returns the length of the longest substring containing at most two distinct characters. For example, given s = \"eceba\", the function should return 3 (subst... |
def custom_insertion_sort(arr: list[int], k: int) -> list[int]:
if k <= 0:
return arr
for i in range(1, k):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr | simplelr_Data_Structure | [
{
"content": "Question:\n**Objective**:\nWrite a function `custom_insertion_sort(arr, k)` to perform a custom insertion sort on a given array. The sorting will only process the first `k` elements of the array. The function should return the partially sorted array where the first `k` elements are sorted, and the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3902,
"level": 1,
"question": "**Objective**:\nWrite a function `custom_insertion_sort(arr, k)` to perform a custom insertion sort on a given array. The sorting will only process the first `k` elements of the array. The function should return the partially sorted array where the fir... |
def factorial(num):
result = 1
for i in range(1, num + 1):
result *= i
return result
| simplelr_Taco | [
{
"content": "Question:\nImplement a function to calculate the factorial of a non-negative integer. Factorial is the product of all positive integers less than or equal to the given number. The factorial of 0 is defined to be 1.\n\nExample:\nGiven num = 5, return 120.\nGiven num = 0, return 1.\n\nDo not use any... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3903,
"level": 1,
"question": "Implement a function to calculate the factorial of a non-negative integer. Factorial is the product of all positive integers less than or equal to the given number. The factorial of 0 is defined to be 1.\n\nExample:\nGiven num = 5, return 120.\nGiven n... |
import json
def extract_json_objects(s):
decoder = json.JSONDecoder()
index = 0
result = []
while index < len(s):
start = s.find('{', index)
if start == -1:
break
try:
obj, new_index = decoder.raw_decode(s, start)
if isinstance(obj, dict):
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns a list of valid JSON objects found within that string. The function should be able to parse and extract JSON objects that are correctly formatted and standalone within the string. If no valid JSON objects are found, the fu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3904,
"level": 1,
"question": "Write a Python function that takes a string as input and returns a list of valid JSON objects found within that string. The function should be able to parse and extract JSON objects that are correctly formatted and standalone within the string. If no v... |
def transpose_matrix(matrix):
return [list(row) for row in zip(*matrix)] | simplelr_Filter | [
{
"content": "Question:\nWrite a function that takes a matrix (a list of lists) and returns the transposed matrix.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3905,
"level": 1,
"question": "Write a function that takes a matrix (a list of lists) and returns the transposed matrix.",
"split": "train"
} |
import bisect
def search_insert(array, val):
return bisect.bisect_left(array, val) | simplelr_Data_Structure | [
{
"content": "Question:\nYou have been hired as a software engineer for a tech company that maintains large sorted datasets. One of your tasks is to optimize the insertion of new data points into these sorted datasets efficiently. You are given a sorted list of integers and a target integer. Your goal is to fin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3906,
"level": 1,
"question": "You have been hired as a software engineer for a tech company that maintains large sorted datasets. One of your tasks is to optimize the insertion of new data points into these sorted datasets efficiently. You are given a sorted list of integers and a ... |
def longest_consecutive_sequence(days: list[int]) -> int:
if not days:
return 0
days_set = set(days)
max_len = 0
for num in days_set:
if (num - 1) not in days_set:
current_num = num
current_len = 1
while (current_num + 1) in days_set:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Longest Consecutive Sequence\n\n#### Context\nYou are developing a feature for a social media application that tracks daily user activities on the platform. One of the metrics you're interested in analyzing is the longest streak of consecutive days a user has been active. This featu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3907,
"level": 1,
"question": "### Longest Consecutive Sequence\n\n#### Context\nYou are developing a feature for a social media application that tracks daily user activities on the platform. One of the metrics you're interested in analyzing is the longest streak of consecutive days... |
def count_words(s):
return len(s.split()) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to count the number of words in a given string. A word is defined as a sequence of characters separated by whitespace characters. Assume that the string may contain leading, trailing, and multiple consecutive whitespace characters.\nAnswer:\nLet's think step by step.\n"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3908,
"level": 1,
"question": "Write a function to count the number of words in a given string. A word is defined as a sequence of characters separated by whitespace characters. Assume that the string may contain leading, trailing, and multiple consecutive whitespace characters.",
... |
def is_balanced(s):
stack = []
matching = {')': '(', '}': '{', ']': '['}
for c in s:
if c in matching.values():
stack.append(c)
elif c in matching:
if not stack:
return False
if stack.pop() != matching[c]:
return False
r... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` representing a sequence of parentheses, implement a function to determine if the parentheses are balanced. The input string `s` may contain any combination of the characters `'('`, `')'`, `'{'`, `'}'`, `'['`, and `']'`. Return `true` if `s` is balanced, and `false` ot... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3909,
"level": 1,
"question": "Given a string `s` representing a sequence of parentheses, implement a function to determine if the parentheses are balanced. The input string `s` may contain any combination of the characters `'('`, `')'`, `'{'`, `'}'`, `'['`, and `']'`. Return `true`... |
def determinant_3x3(matrix):
# Extract the elements of the matrix
a, b, c = matrix[0][0], matrix[0][1], matrix[0][2]
d, e, f = matrix[1][0], matrix[1][1], matrix[1][2]
g, h, i = matrix[2][0], matrix[2][1], matrix[2][2]
# Calculate the determinant using the formula
determinant = a * (e * i -... | simplelr_Filter | [
{
"content": "Question:\nI need to write a program in Python that can calculate the determinant of a 3x3 matrix. Can you help me with the code?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3910,
"level": 1,
"question": "I need to write a program in Python that can calculate the determinant of a 3x3 matrix. Can you help me with the code?",
"split": "train"
} |
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances, pairwise_kernels
def compute_pairwise_matrices(X: np.ndarray, Y: np.ndarray, metrics: list, kernels: list) -> dict:
result = {'metrics': {}, 'kernels': {}}
for metric in metrics:
result['metrics'][metric] = pairwise_distan... | simplelr_Docs | [
{
"content": "Question:\n**Objective:**\nWrite a Python function using `scikit-learn`'s `pairwise` module to compute various pairwise matrices (distance and kernel) for a given set of input vectors. Your implementation should demonstrate an understanding of both distance metrics and kernels.\n\n**Problem Statem... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3911,
"level": 1,
"question": "**Objective:**\nWrite a Python function using `scikit-learn`'s `pairwise` module to compute various pairwise matrices (distance and kernel) for a given set of input vectors. Your implementation should demonstrate an understanding of both distance metri... |
def sum_of_even_numbers(numbers):
return sum([num for num in numbers if num % 2 == 0]) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a list of integers and returns the sum of the even numbers in the list. Additionally, ensure that the function can handle large numbers efficiently and is optimized for performance. Use a list comprehension for this task.\nAnswer:\nLet's think step by... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3912,
"level": 1,
"question": "Create a Python function that takes a list of integers and returns the sum of the even numbers in the list. Additionally, ensure that the function can handle large numbers efficiently and is optimized for performance. Use a list comprehension for this ... |
from collections import deque
from typing import List
def orangesRotting(grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0]) if rows else 0
queue = deque()
fresh = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append... | simplelr_Filter | [
{
"content": "Question:\nimport heapq\n\nclass Solution:\n def orangesRotting(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n queue, fresh = [], []\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == 1:\n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3913,
"level": 1,
"question": "import heapq\n\nclass Solution:\n def orangesRotting(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n queue, fresh = [], []\n for r in range(rows):\n for c in range(cols):\n ... |
def findSmallestMissingPositive(nums):
n = len(nums)
for i in range(n):
while True:
x = nums[i]
if x < 1 or x > n or nums[x - 1] == x:
break
# Swap the current element with the one at x-1
nums[i], nums[x - 1] = nums[x - 1], x
# Check fo... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array `nums` of n integers, where each integer is between 1 and n, inclusive, compute the smallest missing positive integer. Write a function `findSmallestMissingPositive` that returns this integer. Your algorithm should run in O(n) time and use O(1) extra space.\nAnswer:\nLet'... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3914,
"level": 1,
"question": "Given an array `nums` of n integers, where each integer is between 1 and n, inclusive, compute the smallest missing positive integer. Write a function `findSmallestMissingPositive` that returns this integer. Your algorithm should run in O(n) time and u... |
def invert_dictionary(d):
inverted = {}
for key, value in d.items():
if value not in inverted:
inverted[value] = []
inverted[value].append(key)
return inverted | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function called `invert_dictionary` that takes a dictionary as input and returns a new dictionary with inverted key-value pairs. Specifically, any value from the original dictionary should become a key in the new dictionary, and the corresponding key from the original dic... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3915,
"level": 1,
"question": "Write a Python function called `invert_dictionary` that takes a dictionary as input and returns a new dictionary with inverted key-value pairs. Specifically, any value from the original dictionary should become a key in the new dictionary, and the corr... |
def to_binary_string(n):
if n == 0:
return '0'
sign = '-' if n < 0 else ''
return sign + bin(abs(n))[2:] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that converts a small number into a binary string representation. The function should take a single argument that is a small number and return a string that represents its binary form. Make sure to handle support for at least the smallest 16-bit number.\nAnswer:\nLet's... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3916,
"level": 1,
"question": "Create a function that converts a small number into a binary string representation. The function should take a single argument that is a small number and return a string that represents its binary form. Make sure to handle support for at least the smal... |
from typing import List
import heapq
def k_largest_elements(arr: List[int], k: int) -> List[int]:
heap = []
for num in arr:
if len(heap) < k:
heapq.heappush(heap, num)
else:
if num > heap[0]:
heapq.heappop(heap)
heapq.heappush(heap, num)
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are required to implement a function `k_largest_elements(arr: List[int], k: int) -> List[int]` that finds and returns the `k` largest elements from the input list `arr`. The result should be sorted in descending order.\n\n### Input Format\n* A list of intege... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3917,
"level": 1,
"question": "### Problem Statement\n\nYou are required to implement a function `k_largest_elements(arr: List[int], k: int) -> List[int]` that finds and returns the `k` largest elements from the input list `arr`. The result should be sorted in descending order.\n\n#... |
def int_to_roman(n: int) -> str:
roman_numerals = [
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(90, 'XC'),
(50, 'L'),
(40, 'XL'),
(10, 'X'),
(9, 'IX'),
(5, 'V'),
(4, 'IV'),
(1, 'I'),
]
... | simplelr_Codeforces | [
{
"content": "Question:\nThe Roman Empire used a peculiar system for writing numbers known as Roman numerals. Roman numerals are based on combinations of the following seven symbols:\n\nSymbol Value\nI -> 1\nV -> 5\nX -> 10\nL -> 50\nC -> 100\nD -> 500\nM ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3918,
"level": 1,
"question": "The Roman Empire used a peculiar system for writing numbers known as Roman numerals. Roman numerals are based on combinations of the following seven symbols:\n\nSymbol Value\nI -> 1\nV -> 5\nX -> 10\nL -> 50\nC ... |
def fibonacci_sequence(n):
if n < 0:
return []
elif n == 0:
return [0]
elif n == 1:
return [0, 1]
else:
fib_list = [0, 1]
a, b = 0, 1
while True:
next_term = a + b
if next_term > n:
break
fib_list.append(... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to compute the Fibonacci sequence up to a given number n. The function should return a list of Fibonacci numbers up to n (inclusive if n itself is a Fibonacci number). The function should be efficient and avoid redundant calculations.\nAnswer:\nLet's think step b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3919,
"level": 1,
"question": "Write a python function to compute the Fibonacci sequence up to a given number n. The function should return a list of Fibonacci numbers up to n (inclusive if n itself is a Fibonacci number). The function should be efficient and avoid redundant calcula... |
def longest_palindrome(strings):
s = ''.join(strings)
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
center_char = None
for char in freq:
if freq[char] % 2 != 0:
center_char = char
freq[char] -= 1
break
left = []
for char in ... | simplelr_Evol | [
{
"content": "Question:\nCreate a function that accepts a list of strings and returns the longest palindrome that can be formed by any combination of characters in the list. If multiple longest palindromes can be formed, return any of them. If no palindrome can be formed, return an empty string. Ensure your alg... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3920,
"level": 1,
"question": "Create a function that accepts a list of strings and returns the longest palindrome that can be formed by any combination of characters in the list. If multiple longest palindromes can be formed, return any of them. If no palindrome can be formed, retu... |
def capitalize_sentences(document: str) -> str:
result = []
capitalize_next = True
for char in document:
if char in ['.', '!', '?']:
result.append(char)
capitalize_next = True
else:
if capitalize_next:
if char.isalpha():
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question: Sentence Capitalization in a Document\n\nYour task is to implement a feature for a text editor that capitalizes the first letter of each sentence within a document. A sentence is considered to end with any one of the following punctuation marks: `.`, `?`, `!`. After... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3921,
"level": 1,
"question": "### Coding Question: Sentence Capitalization in a Document\n\nYour task is to implement a feature for a text editor that capitalizes the first letter of each sentence within a document. A sentence is considered to end with any one of the following punc... |
def summarize_ranges(numbers: list[int]) -> list[str]:
if not numbers:
return []
result = []
current_start = current_end = numbers[0]
for num in numbers[1:]:
if num == current_end + 1:
current_end = num
else:
if current_start == current_end:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question: Number Range Summarization\n\nAs a proficient developer, you are tasked with creating a system to summarize ranges of numbers. This is especially useful in scenarios where you want to represent large sets of consecutive numbers succinctly.\n\n**Context:**... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3922,
"level": 1,
"question": "### Coding Assessment Question: Number Range Summarization\n\nAs a proficient developer, you are tasked with creating a system to summarize ranges of numbers. This is especially useful in scenarios where you want to represent large sets of consecutive ... |
import struct
def unpack_binary_file(file_path: str) -> list:
"""
Reads from a binary file, unpacks the integers and strings, and returns a list of tuples.
Args:
file_path (str): The path to the binary file.
Returns:
list: A list of tuples, where each tuple contains an integer... | simplelr_Docs | [
{
"content": "Question:\nYou are required to write a Python function that reads a binary file containing a series of packed integers and strings, decodes the strings from encoded binary data, and outputs a list of tuples with the decoded strings and corresponding integers.\n\n#### Specifications:\n\n1. **Binary... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3923,
"level": 1,
"question": "You are required to write a Python function that reads a binary file containing a series of packed integers and strings, decodes the strings from encoded binary data, and outputs a list of tuples with the decoded strings and corresponding integers.\n\n... |
def cumulative_product(lst):
result = []
running_product = 1
for num in lst:
running_product *= num
result.append(running_product)
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns a new list where each element is the cumulative product of the elements up to that point in the original list. For example, given the list [1, 2, 3, 4], the output should be [1, 2, 6, 24].\nAnswer:\nLet's think step by st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3924,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns a new list where each element is the cumulative product of the elements up to that point in the original list. For example, given the list [1, 2, 3, 4], the output should be [1, 2, 6, 24... |
def maxProfit(k, arr):
if not arr or k == 0:
return 0
n = len(arr)
max_possible_trans = (n - 1) // 2
effective_k = min(k, max_possible_trans)
if effective_k == 0:
return 0
if effective_k >= max_possible_trans:
total = 0
for i in range(n - 1):
diff = ar... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr` representing the prices of items over a series of days, find the maximum profit you can achieve by buying and selling the item's shares considering that you may complete up to `k` transactions. However, you cannot engage in multiple transactions at the s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3925,
"level": 1,
"question": "Given an array of integers `arr` representing the prices of items over a series of days, find the maximum profit you can achieve by buying and selling the item's shares considering that you may complete up to `k` transactions. However, you cannot engag... |
def int_to_binary(n):
if n == 0:
return '0'
is_negative = False
if n < 0:
is_negative = True
n = -n
bits = []
while n > 0:
remainder = n % 2
bits.append(str(remainder))
n = n // 2
bits.reverse()
if is_negative:
return '-' + ''.join(bits... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert an integer to its binary representation without using built-in functions like bin() or format().\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3926,
"level": 1,
"question": "Write a python function to convert an integer to its binary representation without using built-in functions like bin() or format().",
"split": "train"
} |
def is_match(s: str, p: str) -> bool:
m = len(s)
n = len(p)
# Create a DP table of (m+1) x (n+1) initialized to False
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True # Empty string matches empty pattern
# Initialize the first row
for j in range(1, n + 1):
if p[j-... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters and a pattern `p` consisting of lowercase English letters where `p` may contain the wildcard character `*`. The wildcard character `*` can match any sequence of characters (including the empty sequence). Return `true` if... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3927,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters and a pattern `p` consisting of lowercase English letters where `p` may contain the wildcard character `*`. The wildcard character `*` can match any sequence of characters (including th... |
def count_word_occurrences(sentence):
counts = {}
words = sentence.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to count the occurrences of all words in a given sentence. The function should return a dictionary where the keys are the words and the values are the counts.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3928,
"level": 1,
"question": "Write a python function to count the occurrences of all words in a given sentence. The function should return a dictionary where the keys are the words and the values are the counts.",
"split": "train"
} |
def max_sum_with_k_distinct(nums, k):
left = 0
current_sum = 0
max_sum = float('-inf')
counts = {}
for right in range(len(nums)):
num = nums[right]
current_sum += num
if num in counts:
counts[num] += 1
else:
counts[num] = 1
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums` and an integer `k`. You should return the maximum sum of a non-empty subarray of `nums` such that the subarray has at most `k` distinct integers. A subarray is a contiguous part of an array. For example, if `nums = [1, 2, 1, 2, 3]` and `k = 2`, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3929,
"level": 1,
"question": "You are given an array of integers `nums` and an integer `k`. You should return the maximum sum of a non-empty subarray of `nums` such that the subarray has at most `k` distinct integers. A subarray is a contiguous part of an array. For example, if `nu... |
def add_digits(num):
if num == 0:
return 0
remainder = num % 9
return 9 if remainder == 0 else remainder | simplelr_Leetcode | [
{
"content": "Question:\nGiven a non-negative integer `num`, repeatedly add all its digits until the result has only one digit. \n\nFor example, given `num = 38`, the process is as follows:\n- `3 + 8 = 11`\n- `1 + 1 = 2`\nSince `2` has only one digit, return it.\n\nThe function should have `O(1)` time complexit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3930,
"level": 1,
"question": "Given a non-negative integer `num`, repeatedly add all its digits until the result has only one digit. \n\nFor example, given `num = 38`, the process is as follows:\n- `3 + 8 = 11`\n- `1 + 1 = 2`\nSince `2` has only one digit, return it.\n\nThe functio... |
import os
import fnmatch
from typing import List
def recursive_include(directory: str, patterns: List[str]) -> List[str]:
matching_files = []
for root, dirs, files in os.walk(directory):
for filename in files:
if any(fnmatch.fnmatch(filename, pattern) for pattern in patterns):
... | simplelr_Docs | [
{
"content": "Question:\n### Question: Implementing a File Inclusion Command\n\n**Context:**\n\nYou are tasked with implementing a function that simulates the `recursive-include` command from the setuptools documentation provided. This command includes all files under a specified directory that match any of the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3931,
"level": 1,
"question": "### Question: Implementing a File Inclusion Command\n\n**Context:**\n\nYou are tasked with implementing a function that simulates the `recursive-include` command from the setuptools documentation provided. This command includes all files under a specif... |
def rotate(mat):
n = len(mat)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
# Reverse each row
for row in mat:
row.reverse() | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem: Rotate Matrix\n\nYou are given an n x n 2D matrix `mat` representing an image. Write a function `rotate(mat)` that rotates the image by 90 degrees clockwise.\n\n**Function Signature**\n```python\ndef rotate(mat: List[List[int]]) -> None:\n```\n\n**Input**\n- `mat`: A list o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3932,
"level": 1,
"question": "### Problem: Rotate Matrix\n\nYou are given an n x n 2D matrix `mat` representing an image. Write a function `rotate(mat)` that rotates the image by 90 degrees clockwise.\n\n**Function Signature**\n```python\ndef rotate(mat: List[List[int]]) -> None:\n... |
def count_distinct_prime_factors(n):
factors = set()
divisor = 2
while n > 1:
if n % divisor == 0:
factors.add(divisor)
while n % divisor == 0:
n = n // divisor
else:
divisor += 1
return len(factors) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that finds the number of distinct prime factors for a given number. The function takes an integer as input and returns the count of distinct prime factors. Assume the input number is always a positive integer greater than 1.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3933,
"level": 1,
"question": "Create a function that finds the number of distinct prime factors for a given number. The function takes an integer as input and returns the count of distinct prime factors. Assume the input number is always a positive integer greater than 1.",
"spli... |
def check_record(s):
absent_count = 0
current_late = 0
for c in s:
if c == 'A':
absent_count += 1
if absent_count > 1:
return False
current_late = 0
elif c == 'L':
current_late += 1
if current_late > 2:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` representing a student’s performance record consisting of characters 'A' (absent), 'L' (late), and 'P' (present), rewrite the string to represent the student's attendance such that a student is rewarded if they have no more than one 'A' and no more than two consecutiv... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3934,
"level": 1,
"question": "Given a string `s` representing a student’s performance record consisting of characters 'A' (absent), 'L' (late), and 'P' (present), rewrite the string to represent the student's attendance such that a student is rewarded if they have no more than one ... |
def primes_below(n):
if n < 2:
return []
sieve = [True] * n
sieve[0], sieve[1] = False, False
for p in range(2, int(n ** 0.5) + 1):
if sieve[p]:
for multiple in range(p * p, n, p):
sieve[multiple] = False
primes = [i for i, is_prime in enumerate(sieve) if ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find all the prime numbers below a given number `n` and return a list of these prime numbers. A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3935,
"level": 1,
"question": "Write a python function to find all the prime numbers below a given number `n` and return a list of these prime numbers. A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.",
"split": "train"
} |
import itertools
def word_combinations(words):
if not words:
return []
chars = [list(word) for word in words]
product = itertools.product(*chars)
combinations = [''.join(p) for p in product]
unique_combinations = sorted(set(combinations))
return unique_combinations | simplelr_Package | [
{
"content": "Question:\nIn this problem, you are required to implement a function `word_combinations` that generates all possible unique letter combinations from a given list of words. The task is to write a function named `word_combinations` that takes a list of words and returns a list of all unique letter c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3936,
"level": 1,
"question": "In this problem, you are required to implement a function `word_combinations` that generates all possible unique letter combinations from a given list of words. The task is to write a function named `word_combinations` that takes a list of words and re... |
def calculate_average_scores(students):
averages = []
for student in students:
name = student[0]
scores = student[1]
avg = sum(scores) / len(scores)
averages.append((name, avg))
# Sort by average descending, then by name ascending
return sorted(averages, key=lambda x: (-x... | simplelr_Apps | [
{
"content": "Question:\n## Task\n\nYou are given a list of student records, where each record contains a student's name and a list of their test scores. You are to write a function that calculates the average test score for each student and returns a list of tuples, each containing a student's name and their a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3937,
"level": 1,
"question": "## Task\n\nYou are given a list of student records, where each record contains a student's name and a list of their test scores. You are to write a function that calculates the average test score for each student and returns a list of tuples, each cont... |
from typing import List
def min_cost_path(grid: List[List[int]]) -> int:
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
if n == 0:
return 0
# Initialize DP table
dp = [[0 for _ in range(n)] for _ in range(m)]
dp[0][0] = grid[0][0]
# Fill the first row
f... | simplelr_Codeforces | [
{
"content": "Question:\nIn an autonomous vehicle system, the vehicle needs to navigate through a grid with different terrains that have varying traversal costs. The grid is represented by a two-dimensional list where each integer value corresponds to the cost of traversing that cell. The vehicle can only move ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3938,
"level": 1,
"question": "In an autonomous vehicle system, the vehicle needs to navigate through a grid with different terrains that have varying traversal costs. The grid is represented by a two-dimensional list where each integer value corresponds to the cost of traversing th... |
def max_visible_distinct_numbers(nums, k):
if k == 0 or len(nums) < k:
return 0
max_distinct = 0
current_distinct = 0
freq = {}
left = 0
for right in range(len(nums)):
num = nums[right]
if num in freq:
freq[num] += 1
else:
freq[nu... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums` and an integer `k`, return the maximum number of visible distinct numbers you can observe if you select exactly `k` continuous numbers from `nums`. Note that a number is considered visible if it appears in the selected subarray.\nAnswer:\nLet's think step b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3939,
"level": 1,
"question": "Given an integer array `nums` and an integer `k`, return the maximum number of visible distinct numbers you can observe if you select exactly `k` continuous numbers from `nums`. Note that a number is considered visible if it appears in the selected sub... |
def sum_and_group_transactions(transactions: list[int]) -> list[int]:
if not transactions:
return []
grouped_transactions = []
current_sum = transactions[0]
for i in range(1, len(transactions)):
if (transactions[i] >= 0 and current_sum >= 0) or (transactions[i] < 0 and current_... | simplelr_Algorithm | [
{
"content": "Question:\n### Sum and Group Integers\n\n#### Context:\nYou are developing a feature for an accounting software that processes a large list of financial transactions. Each transaction is simply an integer representing either income (positive value) or expense (negative value). The goal is to summa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3940,
"level": 1,
"question": "### Sum and Group Integers\n\n#### Context:\nYou are developing a feature for an accounting software that processes a large list of financial transactions. Each transaction is simply an integer representing either income (positive value) or expense (ne... |
import re
def is_hex(s):
return bool(re.fullmatch(r'^0x[0-9a-f]+$', s, re.IGNORECASE)) | simplelr_Apps | [
{
"content": "Question:\nWrite a function that determines if a given string is a valid hexadecimal number. A valid hexadecimal number starts with '0x' or '0X' followed by one or more characters from '0'-'9', 'a'-'f', and 'A'-'F'. The function should return `True` if the string is valid, otherwise `False`.\n\nEx... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3941,
"level": 1,
"question": "Write a function that determines if a given string is a valid hexadecimal number. A valid hexadecimal number starts with '0x' or '0X' followed by one or more characters from '0'-'9', 'a'-'f', and 'A'-'F'. The function should return `True` if the string... |
import math
def is_prime(n):
if n <= 1:
return "Not Prime"
if n == 2:
return "Prime"
if n % 2 == 0:
return "Not Prime"
max_divisor = int(math.sqrt(n)) + 1
for d in range(3, max_divisor, 2):
if n % d == 0:
return "Not Prime"
return "Prime" | simplelr_Filter | [
{
"content": "Question:\nIs there a way to create a Python function that can check if a given number is a prime number and return a message indicating whether the number is \"Prime\" or \"Not Prime\"? Additionally, can the function be optimized to efficiently handle large numbers?\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3942,
"level": 1,
"question": "Is there a way to create a Python function that can check if a given number is a prime number and return a message indicating whether the number is \"Prime\" or \"Not Prime\"? Additionally, can the function be optimized to efficiently handle large numb... |
def three_sum(nums):
nums.sort()
res = []
n = len(nums)
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of distinct integers `nums`, find all unique triplets in the list which give the sum of zero. Note that all triplets must be ordered such that `nums[a] < nums[b] < nums[c]` and `a < b < c`. Return all the triplets in lexicographical order, each triplet being a list of integ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3943,
"level": 1,
"question": "Given a list of distinct integers `nums`, find all unique triplets in the list which give the sum of zero. Note that all triplets must be ordered such that `nums[a] < nums[b] < nums[c]` and `a < b < c`. Return all the triplets in lexicographical order,... |
def reverse_print(s):
reversed_s = s[::-1]
for char in reversed_s:
print(char) | simplelr_Filter | [
{
"content": "Question:\nCode a function that prints out the characters of a string in reverse order, starting from the last character.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3944,
"level": 1,
"question": "Code a function that prints out the characters of a string in reverse order, starting from the last character.",
"split": "train"
} |
from typing import List
def sort_by_length(strings: List[str]) -> List[str]:
return sorted(strings, key=lambda s: len(s), reverse=True) | simplelr_Algorithm | [
{
"content": "Question:\n### Sorting an Array of Strings by Decreasing Length\n\nYou are required to implement a function that takes an array of strings and sorts it in decreasing order of string length. If two strings have the same length, they should retain their original relative order (i.e., maintain stabil... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3945,
"level": 1,
"question": "### Sorting an Array of Strings by Decreasing Length\n\nYou are required to implement a function that takes an array of strings and sorts it in decreasing order of string length. If two strings have the same length, they should retain their original re... |
import torch
def scaled_dot_product_attention(query, key, value, mask=None):
"""
Calculate the attention weights and output using scaled dot-product attention mechanism.
Args:
- query (torch.Tensor): Query tensor of shape (batch_size, num_heads, seq_length, depth).
- key (torch.Tensor): Key tensor... | simplelr_Docs | [
{
"content": "Question:\n### Custom Attention Mechanism Implementation in PyTorch\n\n#### Objective\nImplement a custom scaled dot-product attention mechanism using PyTorch. This function will be the core component of a transformer-like architecture used in various NLP tasks, such as machine translation or text... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3946,
"level": 1,
"question": "### Custom Attention Mechanism Implementation in PyTorch\n\n#### Objective\nImplement a custom scaled dot-product attention mechanism using PyTorch. This function will be the core component of a transformer-like architecture used in various NLP tasks, ... |
from typing import List
import locale
def format_transaction_amounts(amounts: List[float], loc: str) -> List[str]:
try:
locale.setlocale(locale.LC_ALL, loc)
except locale.Error:
raise locale.Error(f"Locale {loc} is not recognized or unsupported")
formatted_amounts = []
for amt in a... | simplelr_Docs | [
{
"content": "Question:\n### Locale Formatter\n\nYou are given a Python program that handles monetary transactions and needs to display amounts in different locale formats. Your task is to write a function `format_transaction_amounts` that accepts a list of transaction amounts and a locale string, then returns ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3947,
"level": 1,
"question": "### Locale Formatter\n\nYou are given a Python program that handles monetary transactions and needs to display amounts in different locale formats. Your task is to write a function `format_transaction_amounts` that accepts a list of transaction amounts... |
from typing import List
def max_contiguous_subsequence_sum(arr: List[int]) -> int:
if not arr:
return 0
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
return max_gl... | simplelr_Data_Structure | [
{
"content": "Question:\n### Context\nYou have been allocated the task of optimizing memory use in a critical financial application. The application performs regular analysis on an array representing daily financial transaction profit and loss. Your task is to determine the maximum possible profit that can be o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3948,
"level": 1,
"question": "### Context\nYou have been allocated the task of optimizing memory use in a critical financial application. The application performs regular analysis on an array representing daily financial transaction profit and loss. Your task is to determine the ma... |
def is_sum_of_digits_divisible_by_3(number):
digit_sum = 0
for digit in str(abs(number)):
digit_sum += int(digit)
return digit_sum % 3 == 0 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to check if the sum of digits of a number is divisible by 3 without any remainder.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3949,
"level": 1,
"question": "Write a python function to check if the sum of digits of a number is divisible by 3 without any remainder.",
"split": "train"
} |
def decode_string(s):
stack = []
currentString = ''
currentNum = 0
for char in s:
if char.isdigit():
currentNum = currentNum * 10 + int(char)
elif char == '[':
stack.append((currentString, currentNum))
currentString = ''
currentNum = 0
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are working on a text processing library that decodes compressed text data. The data follows a specific encoding rule where substrings are repeated a certain number of times, and these repetitions can be nested.\n\n### Question\nImplement a function `decode_string(s)` ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3950,
"level": 1,
"question": "### Scenario\nYou are working on a text processing library that decodes compressed text data. The data follows a specific encoding rule where substrings are repeated a certain number of times, and these repetitions can be nested.\n\n### Question\nImple... |
def gcd(a, b):
if a == 0 and b == 0:
return None
a = abs(a)
b = abs(b)
while b:
a, b = b, a % b
return a
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes two integer inputs and returns the greatest common divisor (GCD) of the two numbers. The function should use the Euclidean algorithm to compute the GCD.\n\n**Notes**:\n- The Euclidean algorithm works by recursively reducing the problem of finding the GCD of t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3951,
"level": 1,
"question": "Write a function that takes two integer inputs and returns the greatest common divisor (GCD) of the two numbers. The function should use the Euclidean algorithm to compute the GCD.\n\n**Notes**:\n- The Euclidean algorithm works by recursively reducing ... |
import bisect
def smallestCommonElement(mat):
if not mat:
return -1
first_row = mat[0]
for num in first_row:
all_have = True
for row in mat[1:]:
idx = bisect.bisect_left(row, num)
if idx < len(row) and row[idx] == num:
continue
els... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a matrix `mat` where each row is sorted in non-decreasing order, find the smallest common element in all rows. If there is no common element, return `-1`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3952,
"level": 1,
"question": "Given a matrix `mat` where each row is sorted in non-decreasing order, find the smallest common element in all rows. If there is no common element, return `-1`.",
"split": "train"
} |
def process_strings(string_list: list) -> list:
output = []
for expr in string_list:
# Evaluate the expression
result = eval(expr)
# Format the result based on its type
if isinstance(result, int):
formatted_result = str(result)
else:
# It's a float... | simplelr_Docs | [
{
"content": "Question:\n**Title: Calculation and String Manipulation with Lists**\n\n**Objective:**\nYou are required to implement a function that takes a list of strings, processes each string to perform some calculations and string manipulations, and then returns a new list based on the processed strings.\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3953,
"level": 1,
"question": "**Title: Calculation and String Manipulation with Lists**\n\n**Objective:**\nYou are required to implement a function that takes a list of strings, processes each string to perform some calculations and string manipulations, and then returns a new list... |
def are_anagrams(str1, str2):
# Convert both strings to lowercase and remove all whitespace
s1 = str1.lower().replace(' ', '')
s2 = str2.lower().replace(' ', '')
# Check if the lengths are different
if len(s1) != len(s2):
return False
# Sort both strings and compare
return ... | simplelr_Filter | [
{
"content": "Question:\nFormulate a Python function that accepts two string inputs and determines if they are anagrams. Anagrams are words that consist of the same characters in a different order. For instance, the strings \"Angel\" and \"gLean\". In your function, first, convert the strings to lowercase and s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3954,
"level": 1,
"question": "Formulate a Python function that accepts two string inputs and determines if they are anagrams. Anagrams are words that consist of the same characters in a different order. For instance, the strings \"Angel\" and \"gLean\". In your function, first, con... |
def unique_characters(s):
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
result = []
added = set()
for char in s:
if counts[char] == 1 and char not in added:
result.append(char)
added.add(char)
return result | simplelr_Filter | [
{
"content": "Question:\nIf I have a function in Python that takes a string and returns the first occurrence of each character in the string, I can use a simple loop to achieve this. How can I modify this function to return only the characters that appear exactly once in the string?\nAnswer:\nLet's think step b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3955,
"level": 1,
"question": "If I have a function in Python that takes a string and returns the first occurrence of each character in the string, I can use a simple loop to achieve this. How can I modify this function to return only the characters that appear exactly once in the s... |
import pandas as pd
def analyze_data(df):
result = {
'total_rows': df.shape[0],
'total_columns': df.shape[1],
'column_names': df.columns.tolist(),
'data_types': {col: str(df[col].dtype) for col in df.columns},
'missing_values': df.isnull().sum().to_dict(),
'mean_valu... | simplelr_Package | [
{
"content": "Question:\nIn the realm of data manipulation and analysis, the Pandas library stands out as a powerful tool in Python. In this exercise, you will build a function that processes a given dataset to extract meaningful insights and present the results in a structured format.\n\n### Task:\nDefine a fu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3956,
"level": 1,
"question": "In the realm of data manipulation and analysis, the Pandas library stands out as a powerful tool in Python. In this exercise, you will build a function that processes a given dataset to extract meaningful insights and present the results in a structure... |
def calculate_factorial(n):
if n == 0:
return 1
elif n < 0:
raise ValueError("n must be a non-negative integer.")
else:
result = 1
for i in range(n, 1, -1):
result *= i
return result | simplelr_Filter | [
{
"content": "Question:\ndef calculate_factorial(n):\n if n == 0:\n return 1\n elif n < 0:\n raise ValueError(\"n must be a non-negative integer.\")\n else:\n result = 1\n for i in range(n, 1, -1):\n result *= i\n return result\nAnswer:\nLet's think step by... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3957,
"level": 1,
"question": "def calculate_factorial(n):\n if n == 0:\n return 1\n elif n < 0:\n raise ValueError(\"n must be a non-negative integer.\")\n else:\n result = 1\n for i in range(n, 1, -1):\n result *= i\n return r... |
def cycle_sort(arr):
if not arr:
return arr
sorted_arr = sorted(arr)
n = len(arr)
# Create a map from value to list of indices in the sorted array
index_map = {}
for idx, val in enumerate(sorted_arr):
if val not in index_map:
index_map[val] = []
inde... | simplelr_Data_Structure | [
{
"content": "Question:\n### Cycle Sort Implementation and Application\n\n#### Objective:\nWrite a function `cycle_sort(arr)` that implements the Cycle Sort algorithm. Your function should sort the array in ascending order with minimal number of writes. \n\n#### Input:\n* An unsorted list `arr` of integers. \n*... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3958,
"level": 1,
"question": "### Cycle Sort Implementation and Application\n\n#### Objective:\nWrite a function `cycle_sort(arr)` that implements the Cycle Sort algorithm. Your function should sort the array in ascending order with minimal number of writes. \n\n#### Input:\n* An u... |
def two_sum(nums, target):
complements = {}
for num in nums:
complement = target - num
if complement in complements:
return [complement, num]
complements[num] = num
return None | simplelr_Filter | [
{
"content": "Question:\nI have a list of unique integers, and I want to find the first pair of numbers that add up to a given target sum. I want to do this efficiently, so I want to use a hash table (or dictionary in Python) to store the numbers I've seen so far and their complements.\n\nHere is my solution:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3959,
"level": 1,
"question": "I have a list of unique integers, and I want to find the first pair of numbers that add up to a given target sum. I want to do this efficiently, so I want to use a hash table (or dictionary in Python) to store the numbers I've seen so far and their com... |
from typing import List, Tuple
def sort_leaderboard(results: List[Tuple[str, int]]) -> List[str]:
sorted_results = sorted(results, key=lambda x: (-x[1], x[0]))
return [name for name, score in sorted_results] | simplelr_Leetcode | [
{
"content": "Question:\nYou are organizing a coding competition and need to create a leaderboard. The leaderboard should display the scores of each participant in descending order. You are given a list of tuples `results`, where each tuple contains a participant's name and their score in the format `(name, sco... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3960,
"level": 1,
"question": "You are organizing a coding competition and need to create a leaderboard. The leaderboard should display the scores of each participant in descending order. You are given a list of tuples `results`, where each tuple contains a participant's name and th... |
def is_valid_expression(expression: str) -> bool:
stack = []
matching = {')': '(', ']': '[', '}': '{'}
for char in expression:
if char in ['(', '[', '{']:
stack.append(char)
elif char in matching:
if not stack:
return False
top = stack.pop(... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context:\nYou are developing a basic text editor for creating documents. One of the essential features of the editor is the ability to correctly handle and validate mathematical expressions within the text. Specifically, you need to ensure that eve... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3961,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context:\nYou are developing a basic text editor for creating documents. One of the essential features of the editor is the ability to correctly handle and validate mathematical expressions within the text. Specif... |
def remove_duplicates_preserve_order(lst):
seen = set()
unique_list = []
for item in lst:
if item not in seen:
unique_list.append(item)
seen.add(item)
return unique_list | simplelr_Filter | [
{
"content": "Question:\nWrite a python function that takes a list of strings and removes all duplicates from that list while preserving the original order of occurrence of the non duplicate elements.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3962,
"level": 1,
"question": "Write a python function that takes a list of strings and removes all duplicates from that list while preserving the original order of occurrence of the non duplicate elements.",
"split": "train"
} |
def second_highest(nums):
unique_nums = list(set(nums))
if len(unique_nums) < 2:
return None
sorted_unique = sorted(unique_nums)
return sorted_unique[-2] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the second highest number in a list. If the list has less than 2 distinct numbers, return None.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3963,
"level": 1,
"question": "Write a python function to find the second highest number in a list. If the list has less than 2 distinct numbers, return None.",
"split": "train"
} |
def max_subarray_sum(arr):
if not arr:
return 0 # or raise ValueError("Array is empty")
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
return max_global | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python code snippet to find the maximum sum of a subarray within a one-dimensional array using Kadane's algorithm?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3964,
"level": 1,
"question": "Can you help me with a Python code snippet to find the maximum sum of a subarray within a one-dimensional array using Kadane's algorithm?",
"split": "train"
} |
def length_of_longest_substring(s: str) -> int:
if not s:
return 0
char_index_map = {}
left = 0
max_length = 0
for right in range(len(s)):
char = s[right]
# Check if the character is in the map and its index is within the current window
if char in char_index_map and c... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge: Longest Substring Without Repeating Characters\n\n#### Context\nString manipulation and optimization tasks are common in software engineering. This problem involves finding the longest substring within a given string that contains no repeating characters. A naive a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3965,
"level": 1,
"question": "### Coding Challenge: Longest Substring Without Repeating Characters\n\n#### Context\nString manipulation and optimization tasks are common in software engineering. This problem involves finding the longest substring within a given string that contains... |
def ip_to_int(ip_str):
parts = ip_str.split('.')
if len(parts) != 4:
raise ValueError('Invalid IPv4 address')
for part in parts:
if not part.isdigit():
raise ValueError('Invalid IPv4 address')
num = int(part)
if num < 0 or num > 255:
raise ValueError('... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that validates and converts a string representation of an IPv4 address into its corresponding Integer representation. If the input string is not a valid IPv4 address, the function should raise a ValueError with the message 'Invalid IPv4 address'.\nAnswer:\nLet's ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3966,
"level": 1,
"question": "Write a Python function that validates and converts a string representation of an IPv4 address into its corresponding Integer representation. If the input string is not a valid IPv4 address, the function should raise a ValueError with the message 'Inva... |
def decodeString(s):
stack = []
current_num = 0
current_str = ''
for c in s:
if c.isdigit():
current_num = current_num * 10 + int(c)
elif c == '[':
stack.append((current_str, current_num))
current_str = ''
current_num = 0
elif c == ... | simplelr_Taco | [
{
"content": "Question:\nGiven an encoded string where repetitions of substrings are denoted by the format number[string], write a function to decode it. The input string may contain nested encoded substrings.\n\nExample 1:\nInput:\ns = \"3[a]2[bc]\"\nOutput: \"aaabcbc\"\n\nExample 2:\nInput:\ns = \"3[a2[c]]\"\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3967,
"level": 1,
"question": "Given an encoded string where repetitions of substrings are denoted by the format number[string], write a function to decode it. The input string may contain nested encoded substrings.\n\nExample 1:\nInput:\ns = \"3[a]2[bc]\"\nOutput: \"aaabcbc\"\n\nEx... |
def reverse_words_in_string(s):
words = s.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse the words in a string but keep the words intact.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3968,
"level": 1,
"question": "Write a function to reverse the words in a string but keep the words intact.",
"split": "train"
} |
def reverseWords(s):
words = s.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Apps | [
{
"content": "Question:\nYou are given a string containing a sentence. Your task is to write a function `reverseWords()` that reverses the order of words in that sentence while maintaining the order of characters within each word. Punctuation and special characters should be treated as part of the words.\n\n###... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3969,
"level": 1,
"question": "You are given a string containing a sentence. Your task is to write a function `reverseWords()` that reverses the order of words in that sentence while maintaining the order of characters within each word. Punctuation and special characters should be t... |
def find_index(lst, item):
try:
return lst.index(item)
except ValueError:
return -1
print(find_index([1, 2, 3, 4, 5], 3)) | simplelr_Filter | [
{
"content": "Question:\ndef find_index(lst, item):\n try:\n return lst.index(item)\n except ValueError:\n return -1\n\nprint(find_index([1, 2, 3, 4, 5], 3))\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3970,
"level": 1,
"question": "def find_index(lst, item):\n try:\n return lst.index(item)\n except ValueError:\n return -1\n\nprint(find_index([1, 2, 3, 4, 5], 3))",
"split": "train"
} |
def simulate_battle(warrior1: dict, warrior2: dict) -> str:
current_attacker = warrior1
current_defender = warrior2
while True:
# Perform the attack
current_defender['health'] -= current_attacker['damage']
# Print the current health status
print(f"After this turn, {warrior1... | simplelr_Package | [
{
"content": "Question:\nYou are asked to develop a function named `simulate_battle` which simulates a battle between two warriors. The primary operations involved in the battle are:\n\n1. **Checking Victory Condition**: After each attack, check if the opponent's health has fallen to zero or below.\n2. **Switch... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3971,
"level": 1,
"question": "You are asked to develop a function named `simulate_battle` which simulates a battle between two warriors. The primary operations involved in the battle are:\n\n1. **Checking Victory Condition**: After each attack, check if the opponent's health has fa... |
def find_duplicates(array):
seen = set()
duplicates = set()
for num in array:
if num in seen:
duplicates.add(num)
else:
seen.add(num)
return list(duplicates) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to determine if an array of integers contains any duplicate values. If duplicates are found, return the duplicate values in a list. Otherwise, return an empty list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3972,
"level": 1,
"question": "Write a python function to determine if an array of integers contains any duplicate values. If duplicates are found, return the duplicate values in a list. Otherwise, return an empty list.",
"split": "train"
} |
factorial_memory = {} # Global cache for factorial values
def calculate_factorial(n: int) -> int:
global factorial_memory # Declare to use the global variable
if not isinstance(n, int):
raise ValueError("Input must be an integer.")
if n < 0:
raise ValueError("Input must be a non-nega... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nWrite a Python function that calculates the factorial of a given non-negative integer `n`. The function should demonstrate proper handling of local and global variable scopes, as well as the use of exception handling to manage invalid inputs.\n\n#### Detailed Requiremen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3973,
"level": 1,
"question": "#### Objective:\nWrite a Python function that calculates the factorial of a given non-negative integer `n`. The function should demonstrate proper handling of local and global variable scopes, as well as the use of exception handling to manage invalid ... |
import pandas as pd
def clean_dataframe(df: pd.DataFrame) -> pd.DataFrame:
# Create a copy of the input DataFrame to avoid modifying the original
df = df.copy()
# Requirement 1: Trim leading and trailing whitespace from all string columns
df['names'] = df['names'].str.strip()
df['emails'] = df... | simplelr_Docs | [
{
"content": "Question:\n### String Manipulation and Data Cleaning with pandas\n\nYou are given a dataset containing several columns of text data. Your task is to clean and transform this data into a more structured format using pandas. Specifically, you should demonstrate your understanding of the `StringDtype... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3974,
"level": 1,
"question": "### String Manipulation and Data Cleaning with pandas\n\nYou are given a dataset containing several columns of text data. Your task is to clean and transform this data into a more structured format using pandas. Specifically, you should demonstrate you... |
import json
def extract_object_by_key_value(file_path, target_key, target_value):
"""
Searches for and returns the first object in a JSON file that contains the specified key-value pair.
"""
try:
with open(file_path, 'r') as file:
data = json.load(file)
# If... | simplelr_Filter | [
{
"content": "Question:\nHow would you write a script that extracts a specific object from a JSON file, when the object has a specific key and value pair?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3975,
"level": 1,
"question": "How would you write a script that extracts a specific object from a JSON file, when the object has a specific key and value pair?",
"split": "train"
} |
def longest_zigzag(arr):
n = len(arr)
if n == 0:
return 0
if n == 1:
return 1
up = [1] * n
down = [1] * n
max_length = 1
for i in range(1, n):
if arr[i] > arr[i - 1]:
up[i] = down[i - 1] + 1
down[i] = 1
elif arr[i] < arr[i - 1... | simplelr_Taco | [
{
"content": "Question:\n# Description\n\nA sequence of numbers is called a zigzag sequence if the differences between successive numbers strictly alternate between positive and negative. In other words, the sequence `a1, a2, a3,..., an` is a zigzag sequence if and only if one of the following holds:\n\n- a1 < ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3976,
"level": 1,
"question": "# Description\n\nA sequence of numbers is called a zigzag sequence if the differences between successive numbers strictly alternate between positive and negative. In other words, the sequence `a1, a2, a3,..., an` is a zigzag sequence if and only if one... |
def sort_versions(versions):
return sorted(versions, key=lambda v: tuple(map(int, v.split('.')))) | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of version numbers represented as strings, write a function to sort them in ascending order. A version number is in the format \"x.y.z\" where x, y, and z are non-negative integers (x, y, and z do not have leading zeros). If two version numbers are equal when considered as ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3977,
"level": 1,
"question": "Given a list of version numbers represented as strings, write a function to sort them in ascending order. A version number is in the format \"x.y.z\" where x, y, and z are non-negative integers (x, y, and z do not have leading zeros). If two version nu... |
def longestSubsequenceSameElement(arr):
counts = {}
for num in arr:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
return max(counts.values())
| simplelr_Taco | [
{
"content": "Question:\nFind the longest subsequence in an array of integers such that all elements of the subsequence are the same. The subsequence does not need to be contiguous. \n\nFor example, given the array arr = [1, 3, 2, 3, 3, 4, 3], the longest subsequence with the same element is [3, 3, 3, 3], which... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3978,
"level": 1,
"question": "Find the longest subsequence in an array of integers such that all elements of the subsequence are the same. The subsequence does not need to be contiguous. \n\nFor example, given the array arr = [1, 3, 2, 3, 3, 4, 3], the longest subsequence with the ... |
def is_balanced(s):
stack = []
bracket_map = {')': '(', '}': '{'}
for char in s:
if char in ['(', '{']:
stack.append(char)
elif char in [')', '}']:
if not stack:
return False
top = stack.pop()
if bracket_map[char] != top:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` containing round and curly brackets (`'(){}'`), determine if the brackets are balanced. Return `true` if they are balanced, otherwise return `false`. A string is considered balanced if:\n1. Each opening bracket has a corresponding closing bracket of the same type.\n2.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3979,
"level": 1,
"question": "Given a string `s` containing round and curly brackets (`'(){}'`), determine if the brackets are balanced. Return `true` if they are balanced, otherwise return `false`. A string is considered balanced if:\n1. Each opening bracket has a corresponding cl... |
from typing import List, Tuple
def minMeetingRooms(intervals: List[Tuple[int, int]]) -> int:
events = []
for start, end in intervals:
events.append((start, 1)) # 1 represents a start event
events.append((end, 0)) # 0 represents an end event
events.sort()
current_rooms = 0
... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a list of intervals where each interval represents a meeting time with a start and end time. Your task is to find the minimum number of meeting rooms required to accommodate all these meetings without any overlapping.\n\nYou need to implement a function that takes as input... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3980,
"level": 1,
"question": "You are given a list of intervals where each interval represents a meeting time with a start and end time. Your task is to find the minimum number of meeting rooms required to accommodate all these meetings without any overlapping.\n\nYou need to imple... |
def max_water_container(arr):
left = 0
right = len(arr) - 1
max_area = 0
while left < right:
width = right - left
height = min(arr[left], arr[right])
current_area = width * height
if current_area > max_area:
max_area = current_area
if arr[left] < arr[r... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` representing the height of vertical lines drawn at each index along the x-axis. Each pair of lines defines a container that can hold water. The width between two lines is the difference of their indices. The amount of water a pair of lines can ho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3981,
"level": 1,
"question": "You are given an array of integers `arr` representing the height of vertical lines drawn at each index along the x-axis. Each pair of lines defines a container that can hold water. The width between two lines is the difference of their indices. The amo... |
def sum_even_numbers(numbers):
if not numbers:
return 'No numbers given'
even_sum = 0
for num in numbers:
if num % 2 == 0:
even_sum += num
return even_sum
| simplelr_Taco | [
{
"content": "Question:\n# Task\n\nAlice loves even numbers and she hates odd numbers. She wants a python program to help her extract even numbers from a given list and sum them up. Additionally, if the list is empty, the program should return 'No numbers given'.\n\nWrite a function called `sum_even_numbers` th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3982,
"level": 1,
"question": "# Task\n\nAlice loves even numbers and she hates odd numbers. She wants a python program to help her extract even numbers from a given list and sum them up. Additionally, if the list is empty, the program should return 'No numbers given'.\n\nWrite a fu... |
def busyStudent(startTime, endTime, queryTime):
count = 0
for s, e in zip(startTime, endTime):
if s <= queryTime <= e:
count += 1
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two integer arrays `startTime` and `endTime`, both of length `n`, where `startTime[i]` and `endTime[i]` represent the start and end times of the `i`th work interval. You're also given an integer `queryTime`. Return _the number of work intervals during which the worker is b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3983,
"level": 1,
"question": "You are given two integer arrays `startTime` and `endTime`, both of length `n`, where `startTime[i]` and `endTime[i]` represent the start and end times of the `i`th work interval. You're also given an integer `queryTime`. Return _the number of work int... |
def combine_strings(string_list):
return ' '.join(string_list) | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function that efficiently combines a given list of strings into a single string, where each original string is separated by a space. The function should use the `join` method to achieve this. Additionally, explain how the code works and why using `join` is more efficient... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3984,
"level": 1,
"question": "Design a Python function that efficiently combines a given list of strings into a single string, where each original string is separated by a space. The function should use the `join` method to achieve this. Additionally, explain how the code works and... |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def advanced_pointplot(save_file_path: str) -> None:
try:
# Load the penguins dataset
penguins = sns.load_dataset('penguins')
except Exception as e:
print(f"Error loading dataset: {e}")
return
# Set m... | simplelr_Docs | [
{
"content": "Question:\n### Question: Advanced Data Visualization using Seaborn Point Plot\n\n#### Objective:\nWrite a Python function using `seaborn` that:\n1. Loads a specific dataset from seaborn.\n2. Produces a detailed point plot utilizing multiple facets of the seaborn library as outlined below.\n3. Save... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3985,
"level": 1,
"question": "### Question: Advanced Data Visualization using Seaborn Point Plot\n\n#### Objective:\nWrite a Python function using `seaborn` that:\n1. Loads a specific dataset from seaborn.\n2. Produces a detailed point plot utilizing multiple facets of the seaborn ... |
def reverse_string(s):
return s[::-1]
# Example usage:
print(reverse_string("hello")) # Output: "olleh" | simplelr_Filter | [
{
"content": "Question:\nWhat is the purpose of using a string literal in Python, and how can it be used in a function that reverses the string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3986,
"level": 1,
"question": "What is the purpose of using a string literal in Python, and how can it be used in a function that reverses the string?",
"split": "train"
} |
def longestLetterSubstring(s):
max_length = 0
current_length = 0
for char in s:
if char.isalpha():
current_length += 1
else:
if current_length > max_length:
max_length = current_length
current_length = 0
# Check for the last s... | simplelr_Apps | [
{
"content": "Question:\n## Task\n\nGiven a string containing a mix of letters and numbers, find the longest substring that consists of only letters and return its length. If there are multiple substrings with the same length, return the length of the first one found.\n\n# Notes\n\n- The string will have at lea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3987,
"level": 1,
"question": "## Task\n\nGiven a string containing a mix of letters and numbers, find the longest substring that consists of only letters and return its length. If there are multiple substrings with the same length, return the length of the first one found.\n\n# Not... |
def find_single_number(nums: list[int]) -> int:
result = 0
for num in nums:
result ^= num
return result | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given an array of integers where some elements appear twice and others appear once. Your task is to implement a function `find_single_number(nums: List[int]) -> int` which returns the element that appears exactly once. Your solution should have a linear ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3988,
"level": 1,
"question": "### Problem Statement\n\nYou are given an array of integers where some elements appear twice and others appear once. Your task is to implement a function `find_single_number(nums: List[int]) -> int` which returns the element that appears exactly once. ... |
import bisect
def length_of_LIS(nums):
if not nums:
return 0
tails = []
for x in nums:
idx = bisect.bisect_left(tails, x)
if idx == len(tails):
tails.append(x)
else:
tails[idx] = x
return len(tails) | simplelr_Filter | [
{
"content": "Question:\nIn the world of competitive programming, a common task is to find the longest increasing subsequence (LIS) in an array. Given an array of integers, write a Python function to find the length of the longest increasing subsequence.\nAnswer:\nLet's think step by step.\n",
"role": "user... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3989,
"level": 1,
"question": "In the world of competitive programming, a common task is to find the longest increasing subsequence (LIS) in an array. Given an array of integers, write a Python function to find the length of the longest increasing subsequence.",
"split": "train"
} |
def length_of_longest_substring(s):
char_index_map = {}
left = 0
max_length = 0
for right in range(len(s)):
char = s[right]
if char in char_index_map and char_index_map[char] >= left:
left = char_index_map[char] + 1
char_index_map[char] = right
current_len... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` that consists of lowercase letters and contains no spaces. Write a function to return the **length of the longest substring** of `s` that contains **no repeating characters**. If there is no such substring, return 0.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3990,
"level": 1,
"question": "You are given a string `s` that consists of lowercase letters and contains no spaces. Write a function to return the **length of the longest substring** of `s` that contains **no repeating characters**. If there is no such substring, return 0.",
"spl... |
def increment_string(strng):
head = strng.rstrip('0123456789')
tail = strng[len(head):]
if not tail:
return strng + '1'
return head + str(int(tail) + 1).zfill(len(tail)) | simplelr_Filter | [
{
"content": "Question:\ndef increment_string(strng):\n head = strng.rstrip('0123456789')\n tail = strng[len(head):]\n if tail == \"\":\n return strng + '1'\n return head + str(int(tail) + 1).zfill(len(tail))\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3991,
"level": 1,
"question": "def increment_string(strng):\n head = strng.rstrip('0123456789')\n tail = strng[len(head):]\n if tail == \"\":\n return strng + '1'\n return head + str(int(tail) + 1).zfill(len(tail))",
"split": "train"
} |
import re
from collections import Counter
def most_frequent_word(text: str) -> str:
# Extract words using regular expression
words = re.findall(r'[a-zA-Z0-9]+', text)
# Convert words to lowercase for case-insensitive comparison
words_lower = [word.lower() for word in words]
# Count the frequency of... | simplelr_Codeforces | [
{
"content": "Question:\nGiven a string of text, your task is to identify the most frequently occurring word in the string. Words are sequences of alphanumeric characters (both lowercase and uppercase Latin letters and digits) separated by non-alphanumeric characters. The comparison of words should be case-inse... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3992,
"level": 1,
"question": "Given a string of text, your task is to identify the most frequently occurring word in the string. Words are sequences of alphanumeric characters (both lowercase and uppercase Latin letters and digits) separated by non-alphanumeric characters. The comp... |
def count_vowels(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
return sum(1 for char in s.lower() if char in vowels) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string and returns the count of vowels in the string\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3993,
"level": 1,
"question": "Write a Python function that takes a string and returns the count of vowels in the string",
"split": "train"
} |
def reorder_list(initial_list, order_by):
temp = initial_list.copy()
result = []
for x in order_by:
while x in temp:
temp.remove(x)
result.append(x)
result += temp
return result | simplelr_Apps | [
{
"content": "Question:\nWrite a function\n```python\nreorder_list(initial_list, order_by)\n```\nthat takes in a list of integers `initial_list` and a list of integers `order_by`, and returns a new list that reorders the elements in `initial_list` based on the order defined in `order_by`. If `order_by` contains... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3994,
"level": 1,
"question": "Write a function\n```python\nreorder_list(initial_list, order_by)\n```\nthat takes in a list of integers `initial_list` and a list of integers `order_by`, and returns a new list that reorders the elements in `initial_list` based on the order defined in... |
def processLogs(logs: list) -> dict:
grouped_logs = {}
for log in logs:
# Extract the timestamp and message from the log entry
timestamp = list(log.keys())[0]
message = log[timestamp]
# Split the timestamp into date and time parts
date_part, time_part = timestamp... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a log processing system. Each log entry is a dictionary where the key is a timestamp (as a string) in the format \"YYYY-MM-DD HH:MM:SS\" and the value is a message (string). Write a function called `processLogs(logs)` that processes a list of log entries and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3995,
"level": 1,
"question": "You are tasked with creating a log processing system. Each log entry is a dictionary where the key is a timestamp (as a string) in the format \"YYYY-MM-DD HH:MM:SS\" and the value is a message (string). Write a function called `processLogs(logs)` that ... |
def flatten_and_sort_stacks(stacks):
flattened = []
for stack in stacks:
flattened.extend(stack)
flattened.sort()
return flattened | simplelr_Filter | [
{
"content": "Question:\nDevelop a Python function that accepts an array of stacks as input, where each stack can have varying amounts of elements. The function should apply a multi-step reasoning process to flatten these stacks into a single horizontal list, while preserving the original order of the elements ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3996,
"level": 1,
"question": "Develop a Python function that accepts an array of stacks as input, where each stack can have varying amounts of elements. The function should apply a multi-step reasoning process to flatten these stacks into a single horizontal list, while preserving ... |
def count_partitions(n):
# Initialize a 2D list to store intermediate results
dp = [[0] * (n + 1) for _ in range(n + 1)]
# Base case: there is one way to partition 0, which is using no parts
for j in range(n + 1):
dp[0][j] = 1
for i in range(1, n + 1):
dp[i][0] = 0
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Integer Decomposition Count\n\nGiven a positive integer `n`, write a function `count_partitions(n)` that returns the number of ways to partition `n` into sums of positive integers. In a partition of `n`, the order of terms does not matter, and partitions that differ only i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3997,
"level": 1,
"question": "### Question: Integer Decomposition Count\n\nGiven a positive integer `n`, write a function `count_partitions(n)` that returns the number of ways to partition `n` into sums of positive integers. In a partition of `n`, the order of terms does not matter... |
from urllib.parse import urlparse, urlunparse, parse_qs, quote, unquote
from typing import Union, Dict, Any
def analyze_and_construct_url(url: str, action: Dict[str, Any]) -> Union[str, Dict[str, Any]]:
# Check for conflicting quote and unquote actions
if action.get('quote') and action.get('unquote'):
... | simplelr_Docs | [
{
"content": "Question:\n### URL Component Analysis and Construction\n\n#### Problem Statement:\n\nYou work for a company that deals with various URL manipulations for web scraping and API interactions. Your task is to create a function `analyze_and_construct_url(url, action)` that takes two inputs:\n1. `url` (... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3998,
"level": 1,
"question": "### URL Component Analysis and Construction\n\n#### Problem Statement:\n\nYou work for a company that deals with various URL manipulations for web scraping and API interactions. Your task is to create a function `analyze_and_construct_url(url, action)`... |
def fibonacci(n):
if not hasattr(fibonacci, 'memo'):
fibonacci.memo = {0: 0, 1: 1}
if n not in fibonacci.memo:
for i in range(len(fibonacci.memo), n + 1):
fibonacci.memo[i] = fibonacci.memo[i - 1] + fibonacci.memo[i - 2]
return fibonacci.memo[n] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to retrieve the nth Fibonacci number using Python. The function should be efficient and utilize memoization to improve performance.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3999,
"level": 1,
"question": "Write a function to retrieve the nth Fibonacci number using Python. The function should be efficient and utilize memoization to improve performance.",
"split": "train"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.