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 can_be_empty(s):
n = len(s)
if n % 3 != 0:
return False
from collections import defaultdict
counts = defaultdict(int)
for c in s:
counts[c] += 1
if counts['a'] != counts['b'] or counts['b'] != counts['c']:
return False
stack = []
for c in s:
stack.appe... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting solely of characters `'a'`, `'b'`, and `'c'`. You can perform the following operation any number of times: Remove three consecutive characters that are all different ('abc' or 'acb' or 'bac' or 'bca' or 'cab' or 'cba') from the string. Your goal is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7600,
"level": 1,
"question": "You are given a string `s` consisting solely of characters `'a'`, `'b'`, and `'c'`. You can perform the following operation any number of times: Remove three consecutive characters that are all different ('abc' or 'acb' or 'bac' or 'bca' or 'cab' or 'c... |
def findLongestCommonPrefix(strs: list) -> str:
if not strs:
return ""
if len(strs) == 1:
return strs[0]
min_len = min(len(s) for s in strs)
prefix = ""
for i in range(min_len):
c = strs[0][i]
for s in strs[1:]:
if s[i] != c:
return prefix
... | simplelr_Package | [
{
"content": "Question:\nYou are required to implement a function named `findLongestCommonPrefix` that takes a list of strings and finds the longest common prefix among them. If there is no common prefix, the function returns an empty string.\n\n### Function Signature:\n```python\ndef findLongestCommonPrefix(st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7601,
"level": 1,
"question": "You are required to implement a function named `findLongestCommonPrefix` that takes a list of strings and finds the longest common prefix among them. If there is no common prefix, the function returns an empty string.\n\n### Function Signature:\n```pyt... |
def is_subsequence(s: str, p: str) -> bool:
if len(p) == 0:
return True
if len(p) > len(s):
return False
i = j = 0
while i < len(s) and j < len(p):
if s[i] == p[j]:
j += 1
i += 1
return j == len(p) | simplelr_Leetcode | [
{
"content": "Question:\nYou have a string `s` that consists of lower case English letters and a pattern `p` which also consists of lower case English letters. Determine if the pattern `p` is a subsequence of the string `s`. Return `true` if `p` is a subsequence of `s`, and `false` otherwise.\nAnswer:\nLet's th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7602,
"level": 1,
"question": "You have a string `s` that consists of lower case English letters and a pattern `p` which also consists of lower case English letters. Determine if the pattern `p` is a subsequence of the string `s`. Return `true` if `p` is a subsequence of `s`, and `f... |
def sum_even_numbers(lst):
return sum(num for num in lst if num % 2 == 0) | simplelr_Apps | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns the sum of the integers that are even. The function should filter out the even numbers from the list and then calculate their sum.\n\n### Example\n\n```python\nsum_even_numbers([1, 2, 3, 4, 5, 6]) # Output: 12\nsum_even_n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7603,
"level": 1,
"question": "Create a function that takes a list of integers and returns the sum of the integers that are even. The function should filter out the even numbers from the list and then calculate their sum.\n\n### Example\n\n```python\nsum_even_numbers([1, 2, 3, 4, 5,... |
from urllib.parse import urljoin, quote
from typing import List
def build_full_urls(base_url: str, url_fragments: List[str]) -> List[str]:
full_urls = []
for fragment in url_fragments:
quoted_fragment = quote(fragment)
full_url = urljoin(base_url, quoted_fragment)
full_urls.append(full_... | simplelr_Docs | [
{
"content": "Question:\n**URL List Processor**\n\n### Objective:\nYou are tasked with writing a Python function `build_full_urls(base_url: str, url_fragments: List[str]) -> List[str]` that:\n- Accepts a base URL and a list of URL fragments.\n- Returns a list of fully qualified URLs based on the base URL and ea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7604,
"level": 1,
"question": "**URL List Processor**\n\n### Objective:\nYou are tasked with writing a Python function `build_full_urls(base_url: str, url_fragments: List[str]) -> List[str]` that:\n- Accepts a base URL and a list of URL fragments.\n- Returns a list of fully qualifie... |
def quick_sort(arr: list) -> list:
if len(arr) <= 1:
return arr
pivot = arr[0]
left = []
middle = []
right = []
for x in arr:
if x < pivot:
left.append(x)
elif x == pivot:
middle.append(x)
else:
right.append(x)
return quick_... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nSorting algorithms are fundamental to computer science and often serve as the basis for more complex operations. One such algorithm is the QuickSort, which uses a divide-and-conquer strategy to sort elements by recursively partitioning the array.\n\n### Problem Statement\nW... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7605,
"level": 1,
"question": "### Context\nSorting algorithms are fundamental to computer science and often serve as the basis for more complex operations. One such algorithm is the QuickSort, which uses a divide-and-conquer strategy to sort elements by recursively partitioning the... |
def first_unique_char(input_string: str) -> str:
if not input_string:
return ""
freq = {}
for char in input_string:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
for char in input_string:
if freq[char] == 1:
return cha... | simplelr_Algorithm | [
{
"content": "Question:\n## Unique Character Finder\n\n### Objective\n\nYou are tasked with implementing an efficient algorithm to determine the first non-repeating character in a given string of lowercase alphabets.\n\n### Problem Statement\n\nWrite a function `first_unique_char(input_string: str) -> str` to f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7606,
"level": 1,
"question": "## Unique Character Finder\n\n### Objective\n\nYou are tasked with implementing an efficient algorithm to determine the first non-repeating character in a given string of lowercase alphabets.\n\n### Problem Statement\n\nWrite a function `first_unique_c... |
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0:
return False
# Write n-1 as d * 2^s
d = n - 1
s = 0
while d % 2 == 0:
d //= 2
s += 1
# Bases for testing up to 2^64
bases = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code to determine if a given number is a prime number or not. Also, ensure that the code is efficient for large numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7607,
"level": 1,
"question": "Write a Python code to determine if a given number is a prime number or not. Also, ensure that the code is efficient for large numbers.",
"split": "train"
} |
def reverse_array(A):
i = 0
j = len(A) - 1
while i < j:
# Swap elements at positions i and j
temp = A[i]
A[i] = A[j]
A[j] = temp
i += 1
j -= 1
return A | simplelr_Filter | [
{
"content": "Question:\nGiven an array A with n elements, where n is a positive integer and A is non-empty, perform a function to reverse the order of the array such that the last element becomes the first element and vice versa. The function should have a time complexity of O(n) and use only a constant amount... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7608,
"level": 1,
"question": "Given an array A with n elements, where n is a positive integer and A is non-empty, perform a function to reverse the order of the array such that the last element becomes the first element and vice versa. The function should have a time complexity of ... |
def is_palindrome_check(text):
# Process the text by keeping only alphabetic characters and converting to lowercase
processed = [char.lower() for char in text if char.isalpha()]
cleaned_text = ''.join(processed)
# Check if the cleaned text is a palindrome
return cleaned_text == cleaned_text[::-1] | simplelr_Filter | [
{
"content": "Question:\nCreate a function named \"is_palindrome_check\" that takes one parameter, \"text\", and returns True if the string is a palindrome (reads the same forwards and backwards), ignoring any non-alphabetic characters and case.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7609,
"level": 1,
"question": "Create a function named \"is_palindrome_check\" that takes one parameter, \"text\", and returns True if the string is a palindrome (reads the same forwards and backwards), ignoring any non-alphabetic characters and case.",
"split": "train"
} |
def max_subarray_sum(arr):
if not arr:
return 0 # Assuming the function should return 0 for empty arrays
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 ... | simplelr_Evol | [
{
"content": "Question:\nDesign a function to calculate the maximum sum of any contiguous subarray within a given list of integers. The function should take a list of integers as input and return the maximum possible sum. Do not use built-in functions that directly solve the problem. \n\nExample input:\n`arr = ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7610,
"level": 1,
"question": "Design a function to calculate the maximum sum of any contiguous subarray within a given list of integers. The function should take a list of integers as input and return the maximum possible sum. Do not use built-in functions that directly solve the p... |
def max_area(heights):
left = 0
right = len(heights) - 1
max_volume = 0
while left < right:
current_height = min(heights[left], heights[right])
width = right - left
current_volume = current_height * width
if current_volume > max_volume:
max_volume = current_vo... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers representing the heights of buildings as they appear in a straight line. Each element in the list represents the height of a building at that specific position. Two buildings can form a container with the line segment connecting them. The container will ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7611,
"level": 1,
"question": "You are given a list of integers representing the heights of buildings as they appear in a straight line. Each element in the list represents the height of a building at that specific position. Two buildings can form a container with the line segment c... |
import heapq
from collections import Counter
def rearrange_string(s):
count = Counter(s)
n = len(s)
max_freq = max(count.values(), default=0)
if max_freq > (n + 1) // 2:
return ""
heap = [(-v, k) for k, v in count.items()]
heapq.heapify(heap)
result = []
whil... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string containing only lowercase letters. Rearrange the characters of the string such that no two adjacent characters are the same. If it is not possible to do so, return an empty string. If there are multiple valid rearrangements, return any of them.\nAnswer:\nLet's thi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7612,
"level": 1,
"question": "You are given a string containing only lowercase letters. Rearrange the characters of the string such that no two adjacent characters are the same. If it is not possible to do so, return an empty string. If there are multiple valid rearrangements, retu... |
def reverse_string(s):
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse a string in Python. Explain your code step-by-step.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7613,
"level": 1,
"question": "Write a function to reverse a string in Python. Explain your code step-by-step.",
"split": "train"
} |
def convert_to_roman(num: 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_Data_Structure | [
{
"content": "Question:\n### Convert Integer to Roman Numeral\n\nYou are tasked with writing a function `convert_to_roman` that converts a given integer within a specific range into its corresponding Roman numeral string.\n\nRoman numerals are represented by the following symbols:\n- I, V, X, L, C, D, M\n\nThe ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7614,
"level": 1,
"question": "### Convert Integer to Roman Numeral\n\nYou are tasked with writing a function `convert_to_roman` that converts a given integer within a specific range into its corresponding Roman numeral string.\n\nRoman numerals are represented by the following symb... |
def next_greater_element(arr):
stack = []
result = [-1] * len(arr)
for i in range(len(arr)-1, -1, -1):
while stack and stack[-1] <= arr[i]:
stack.pop()
if stack:
result[i] = stack[-1]
else:
result[i] = -1
stack.append(arr[i])
... | simplelr_Filter | [
{
"content": "Question:\nWe are given a 1-dimensional array of integers. For every element in the array, we need to find out the next greater element to its right. This is also known as the Next Greater Element problem.\n\nHere is the formal definition of the problem:\n\nGiven an array of integers, find the nex... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7615,
"level": 1,
"question": "We are given a 1-dimensional array of integers. For every element in the array, we need to find out the next greater element to its right. This is also known as the Next Greater Element problem.\n\nHere is the formal definition of the problem:\n\nGiven... |
def all_subsets(s):
elements = list(s)
n = len(elements)
result = []
for i in range(2 ** n):
subset = []
for k in range(n):
if i & (1 << k):
subset.append(elements[k])
result.append(set(subset))
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to return all possible subsets of a set. For example, if the set is {1, 2}, the function should return [{}, {1}, {2}, {1, 2}].\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7616,
"level": 1,
"question": "Write a python function to return all possible subsets of a set. For example, if the set is {1, 2}, the function should return [{}, {1}, {2}, {1, 2}].",
"split": "train"
} |
import re
from collections import Counter
def count_top_words(file_path: str, top_n: int):
with open(file_path, 'r') as f:
text = f.read()
# Convert the text to lowercase
text = text.lower()
# Replace any characters that are not letters or apostrophes with spaces
text = re.sub(r"[... | simplelr_Package | [
{
"content": "Question:\nWrite a function to count the number of unique words in a text file, ignoring case, and print the top N most common words along with their counts, sorted by frequency. The function should take the following inputs:\n* The file path to the text file.\n* The number of top frequent words (... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7617,
"level": 1,
"question": "Write a function to count the number of unique words in a text file, ignoring case, and print the top N most common words along with their counts, sorted by frequency. The function should take the following inputs:\n* The file path to the text file.\n*... |
def isPowerOfFour(N):
if N == 0:
return -1
if (N & (N - 1)) != 0:
return -1
exponent = N.bit_length() - 1
if exponent % 2 == 0:
return exponent // 2
else:
return -1
| simplelr_Taco | [
{
"content": "Question:\nGiven a number N, determine if it is a power of 4. If N is a power of 4, return the exponent k such that 4^k = N. If N is not a power of 4, return -1.\n\nExample 1:\nInput:\nN = 16\nOutput:\n2\nExplanation:\n16 is 4^2. Hence, the output is 2.\n\nExample 2:\nInput:\nN = 15\nOutput:\n-1\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7618,
"level": 1,
"question": "Given a number N, determine if it is a power of 4. If N is a power of 4, return the exponent k such that 4^k = N. If N is not a power of 4, return -1.\n\nExample 1:\nInput:\nN = 16\nOutput:\n2\nExplanation:\n16 is 4^2. Hence, the output is 2.\n\nExampl... |
def exchange_sort(arr, comparator=None):
if comparator is None:
comparator = lambda x, y: x <= y # Default to ascending order with equality check to prevent unnecessary swaps
arr = arr.copy() # Create a copy to avoid modifying the original list
n = len(arr)
for _ in range(n - 1):
swapp... | simplelr_Data_Structure | [
{
"content": "Question:\n### Exchange Sort Extension\n\nYou are given an array of `n` integers. Extend the existing `exchange_sort()` function to handle the following enhancements:\n\n1. **Early Termination**: Introduce an optimization where the sorting process stops early if the array becomes sorted before com... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7619,
"level": 1,
"question": "### Exchange Sort Extension\n\nYou are given an array of `n` integers. Extend the existing `exchange_sort()` function to handle the following enhancements:\n\n1. **Early Termination**: Introduce an optimization where the sorting process stops early if ... |
def can_rearrange(s1: str, s2: str) -> bool:
return len(s1) == len(s2) and sorted(s1) == sorted(s2) | simplelr_Code_Contests | [
{
"content": "Question:\nYou have been invited to a puzzle challenge where the goal is to create unique strings by rearranging characters. One type of challenge involves determining if one string can be rearranged to form another by rearranging its characters.\n\nWrite a function that checks whether it is possi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7620,
"level": 1,
"question": "You have been invited to a puzzle challenge where the goal is to create unique strings by rearranging characters. One type of challenge involves determining if one string can be rearranged to form another by rearranging its characters.\n\nWrite a funct... |
import re
def count_words(text):
# Use regex to find all words, treating apostrophes as part of words
words = re.findall(r"\w+(?:'\w+)*", text.lower())
return len(words)
# Example usage:
text = "Hello, world! Don't worry about the punctuation."
print(count_words(text)) # Output: 6 | simplelr_Filter | [
{
"content": "Question:\nIf I want to create a Python script that can count the number of words in a given text, I can write a function that splits the text into words based on spaces and then counts the number of elements in the resulting list. How can I modify this function to handle punctuation correctly, so... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7621,
"level": 1,
"question": "If I want to create a Python script that can count the number of words in a given text, I can write a function that splits the text into words based on spaces and then counts the number of elements in the resulting list. How can I modify this function ... |
import torch
def analyze_tensor(tensor: torch.Tensor) -> dict:
"""
Analyzes the given tensor and returns a dictionary with the size, number of elements,
whether it is a square matrix, and whether it is one-dimensional.
Parameters:
tensor (torch.Tensor): The input tensor to analyze.
Returns:
... | simplelr_Docs | [
{
"content": "Question:\n<|Analysis Begin|>\n\nThe provided documentation describes the `torch.Size` class in PyTorch, which is used to represent the size of all dimensions of a tensor. This class is a subclass of the `tuple` and supports common sequence operations such as indexing and getting the length.\n\nTh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7622,
"level": 1,
"question": "<|Analysis Begin|>\n\nThe provided documentation describes the `torch.Size` class in PyTorch, which is used to represent the size of all dimensions of a tensor. This class is a subclass of the `tuple` and supports common sequence operations such as ind... |
from collections import Counter
def count_integers(lst):
"""
Counts the frequency of each integer in the given list and returns the result as a dictionary.
Args:
lst (list): A list of integers.
Returns:
dict: A dictionary where keys are unique integers from the list and values... | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function that takes in a list of integers and returns a dictionary where each unique integer from the list is a key, and its value is the count of how many times it appears in the list. Ensure the function is efficient and handles large lists. Test your function with a l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7623,
"level": 1,
"question": "Design a Python function that takes in a list of integers and returns a dictionary where each unique integer from the list is a key, and its value is the count of how many times it appears in the list. Ensure the function is efficient and handles large... |
from typing import List, Tuple, Dict
def analyze_logs(logs: List[dict]) -> Tuple[Dict[str, List[str]], List[str]]:
visitor_logs = {} # key: visitor_id, value: list of tuples (timestamp, url)
url_counts = {} # key: url, value: count
# Process each log to collect visitor's logs and count URL visits
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are tasked with implementing a system that processes and analyzes logs generated from a server's activity over a period. The logs are recorded in a specific format, and your objective is to collect information about unique visitors and their activity sequences... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7624,
"level": 1,
"question": "### Problem Statement\nYou are tasked with implementing a system that processes and analyzes logs generated from a server's activity over a period. The logs are recorded in a specific format, and your objective is to collect information about unique vi... |
import shutil
import os
def manage_directory(src_dir: str, dst_dir: str, archive_name: str) -> None:
# Move the directory from source to destination
new_dir_path = os.path.join(dst_dir, os.path.basename(src_dir))
shutil.move(src_dir, new_dir_path)
print(f"Directory moved from {src_dir} to {new_dir_path... | simplelr_Docs | [
{
"content": "Question:\n### File & Directory Management Task\n\nYou are required to create a script that performs the following operations:\n\n1. Moves a directory from one location to another.\n2. After moving, create a compressed archive (zip format) of the moved directory.\n3. Calculate and print the disk u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7625,
"level": 1,
"question": "### File & Directory Management Task\n\nYou are required to create a script that performs the following operations:\n\n1. Moves a directory from one location to another.\n2. After moving, create a compressed archive (zip format) of the moved directory.... |
def hamming_distance(a, b):
xor_result = a ^ b
return bin(xor_result).count('1') | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the Hamming Distance between two integers. The function should compare two numbers and return the number of positions at which the corresponding bits are different.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7626,
"level": 1,
"question": "Write a function to calculate the Hamming Distance between two integers. The function should compare two numbers and return the number of positions at which the corresponding bits are different.",
"split": "train"
} |
from collections import Counter
def sum_of_unique_elements(lst: list) -> int:
if not isinstance(lst, list):
raise TypeError("Input must be a list.")
for num in lst:
if type(num) is not int:
raise TypeError("All elements must be integers.")
counts = Counter(lst)
sum... | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of Unique Elements\n\nYou are tasked with implementing a function that calculates the sum of elements in a list that appear exactly once.\n\n#### Function Signature:\n```python\ndef sum_of_unique_elements(lst: list) -> int:\n```\n\n### Input:\n* A list of integers `lst`.\n\n### ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7627,
"level": 1,
"question": "### Sum of Unique Elements\n\nYou are tasked with implementing a function that calculates the sum of elements in a list that appear exactly once.\n\n#### Function Signature:\n```python\ndef sum_of_unique_elements(lst: list) -> int:\n```\n\n### Input:\n... |
from typing import List, Tuple
def analyze_stock_prices(stock_prices: List[int]) -> Tuple[int, int, int]:
n = len(stock_prices)
if n < 2:
return (0, -1, -1)
min_price_day = 0
max_profit = 0
buy_day = -1
sell_day = -1
for i in range(1, n):
if stock_prices[i] < stock... | simplelr_Apps | [
{
"content": "Question:\nWrite a function `analyze_stock_prices` that takes a list of stock prices (integers) representing sequential days and returns a tuple containing the maximum profit achievable by buying on one day and selling on a later day, and the days on which to buy and sell to achieve that profit. T... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7628,
"level": 1,
"question": "Write a function `analyze_stock_prices` that takes a list of stock prices (integers) representing sequential days and returns a tuple containing the maximum profit achievable by buying on one day and selling on a later day, and the days on which to buy... |
def swap_elements(list1, list2):
list1[:], list2[:] = list2[:], list1[:] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to swap elements of two lists without using a temporary variable.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7629,
"level": 1,
"question": "Write a python function to swap elements of two lists without using a temporary variable.",
"split": "train"
} |
def merge_and_deduplicate(list1, list2):
seen = set()
result = []
for item in list1:
if item not in seen:
result.append(item)
seen.add(item)
for item in list2:
if item not in seen:
result.append(item)
seen.add(item)
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to merge two lists and eliminate duplicate elements, maintaining the original order of the first occurrence of each element.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7630,
"level": 1,
"question": "Write a python function to merge two lists and eliminate duplicate elements, maintaining the original order of the first occurrence of each element.",
"split": "train"
} |
import re
from typing import List
def extract_unique_words(text: str) -> List[str]:
"""
Extracts unique words from the input text.
:param text: A string containing the input text.
:return: A sorted list of unique words (case-insensitive) without punctuation.
"""
# Convert the text to lowercase... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are developing a utility function for a text processing suite that requires extracting unique words from a piece of text. The function should ignore the case of the words and exclude any punctuation marks.\n\n### Task\nImplement a function `extract_unique_words` that e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7631,
"level": 1,
"question": "### Scenario\nYou are developing a utility function for a text processing suite that requires extracting unique words from a piece of text. The function should ignore the case of the words and exclude any punctuation marks.\n\n### Task\nImplement a fun... |
def longest_unique_subsequence(s: str) -> int:
"""
Returns the length of the longest subsequence with all unique characters.
Args:
s (str): The input string
Returns:
int: The length of the longest unique subsequence
"""
return len(set(s)) | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge: Unique Character Subsequence \n\n#### Scenario\nYou have been assigned to work on a new text-processing feature for a document analysis tool. Your task is to find the length of the longest subsequence in a given string where all characters are unique, without alter... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7632,
"level": 1,
"question": "### Coding Challenge: Unique Character Subsequence \n\n#### Scenario\nYou have been assigned to work on a new text-processing feature for a document analysis tool. Your task is to find the length of the longest subsequence in a given string where all c... |
from typing import List
def maxProfit(prices: List[int]) -> int:
if not prices:
return 0
buy1 = -prices[0]
sell1 = 0
buy2 = -float('inf')
sell2 = 0
for price in prices[1:]:
new_buy1 = max(buy1, -price)
new_sell1 = max(sell1, buy1 + price)
new_buy2 = max(buy2, sel... | simplelr_Codeforces | [
{
"content": "Question:\nYou have been tasked with developing a new application that involves processing stock market data. Specifically, you need to determine the maximum profit that can be achieved by buying and selling stocks given the daily prices for a single stock over a period of time. However, there is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7633,
"level": 1,
"question": "You have been tasked with developing a new application that involves processing stock market data. Specifically, you need to determine the maximum profit that can be achieved by buying and selling stocks given the daily prices for a single stock over a... |
def minimum_trips(packages, capacity):
total = 0
for p in packages:
total += (p + capacity - 1) // capacity
return total | simplelr_Leetcode | [
{
"content": "Question:\nA logistics company needs to manage a fleet of trucks that deliver packages to various destinations along a highway. The highway is represented as a straight line and there are `n` destinations numbered from `0` to `n - 1` along this line. Each destination has a certain volume of packag... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7634,
"level": 1,
"question": "A logistics company needs to manage a fleet of trucks that deliver packages to various destinations along a highway. The highway is represented as a straight line and there are `n` destinations numbered from `0` to `n - 1` along this line. Each destina... |
def length_of_longest_unique_substring(s):
words = s.split()
max_length = 0
for word in words:
last_seen = {}
left = 0
current_max = 0
for right in range(len(word)):
char = word[right]
if char in last_seen and last_seen[char] >= left:
l... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` representing a list of words, each separated by a single space. Find the length of the longest substring that contains unique characters within this string. If there are multiple substrings with the same maximum length, return the one that appears first. Retur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7635,
"level": 1,
"question": "You are given a string `s` representing a list of words, each separated by a single space. Find the length of the longest substring that contains unique characters within this string. If there are multiple substrings with the same maximum length, retur... |
def sum_of_list(numbers):
total = 0
for number in numbers:
total += number
return total
# Example usage
numbers = [10, 20, 30, 40, 50]
print("Sum of the list:", sum_of_list(numbers)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum of a list of numbers. Here's the list: [10, 20, 30, 40, 50].\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7636,
"level": 1,
"question": "Write a function to calculate the sum of a list of numbers. Here's the list: [10, 20, 30, 40, 50].",
"split": "train"
} |
def uniqueBackupTimes(backupTimes):
unique = list(set(backupTimes))
unique.sort()
return unique
| simplelr_Taco | [
{
"content": "Question:\nSophie has recently started working at a company called DataSecure, where she needs to manage data backups. Each day, Sophie initiates backup of critical data files, and the duration to backup each file is given. At the end of the day, she records the total time spent on backup. However... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7637,
"level": 1,
"question": "Sophie has recently started working at a company called DataSecure, where she needs to manage data backups. Each day, Sophie initiates backup of critical data files, and the duration to backup each file is given. At the end of the day, she records the ... |
from collections import Counter
def get_histogram(input_list: list) -> dict:
return dict(Counter(input_list)) | simplelr_Data_Structure | [
{
"content": "Question:\nHistogram Count\n\nYou are tasked with implementing a histogram counting function, which accurately represents the distribution of numerical data in a given list. A histogram provides a frequency count of each unique value in the list.\n\n#### Function Signature:\n```python\ndef get_his... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7638,
"level": 1,
"question": "Histogram Count\n\nYou are tasked with implementing a histogram counting function, which accurately represents the distribution of numerical data in a given list. A histogram provides a frequency count of each unique value in the list.\n\n#### Function... |
def longest_palindromic_substring_length(word):
if not word:
return 0
# Preprocess the string by inserting '#' between each character and at both ends
processed = '#' + '#'.join(word) + '#'
n = len(processed)
dp = [0] * n
C, R = 0, 0 # Center and right boundary of the current largest p... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `word` consisting of alphabetical characters. A **palindromic substring** is a substring that reads the same backward as forward. Return _the length of the longest palindromic substring in_ `word`. The solution should have a time complexity better than `O(n^2)`.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7639,
"level": 1,
"question": "You are given a string `word` consisting of alphabetical characters. A **palindromic substring** is a substring that reads the same backward as forward. Return _the length of the longest palindromic substring in_ `word`. The solution should have a time... |
def filter_chat_history(chat_history: list, user_id: str) -> list:
# Filter messages where the user is either sender or recipient
filtered_messages = [
msg for msg in chat_history
if msg['sender'] == user_id or msg['recipient'] == user_id
]
# Sort the filtered messages by timestamp
s... | simplelr_Evol | [
{
"content": "Question:\nIn a messaging application, chat histories are stored in a list of dictionaries, where each dictionary represents a message containing sender's ID, recipient's ID, timestamp, and message content. Here is an example:\n\n```\nchat_history = [\n {\"sender\": \"user1\", \"recipient\": \"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7640,
"level": 1,
"question": "In a messaging application, chat histories are stored in a list of dictionaries, where each dictionary represents a message containing sender's ID, recipient's ID, timestamp, and message content. Here is an example:\n\n```\nchat_history = [\n {\"sen... |
import heapq
def k_largest_elements(arr: list, k: int) -> list:
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)
# Extract the elements and sort... | simplelr_Algorithm | [
{
"content": "Question:\n## Problem Statement:\n\nYou are tasked with writing a function to find the k largest elements in a given unsorted array and return them sorted in non-decreasing order.\n\n### Function Definition\nWrite a function:\n\n```python\ndef k_largest_elements(arr: list, k: int) -> list:\n \"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7641,
"level": 1,
"question": "## Problem Statement:\n\nYou are tasked with writing a function to find the k largest elements in a given unsorted array and return them sorted in non-decreasing order.\n\n### Function Definition\nWrite a function:\n\n```python\ndef k_largest_elements(... |
def unique_characters_count(s):
return len(set(s)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the number of unique characters in a given string. For example, if the input string is \"programming\", the function should return 8, since the unique characters are 'p', 'r', 'o', 'g', 'a', 'm', 'i', and 'n'.\nAnswer:\nLet's think step by step.\n",
"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7642,
"level": 1,
"question": "Write a python function to find the number of unique characters in a given string. For example, if the input string is \"programming\", the function should return 8, since the unique characters are 'p', 'r', 'o', 'g', 'a', 'm', 'i', and 'n'.",
"split... |
def find_first_peak(temperatures):
n = len(temperatures)
for i in range(n):
if i == 0:
if temperatures[i] > temperatures[i + 1]:
return temperatures[i]
elif i == n - 1:
if temperatures[i] > temperatures[i - 1]:
return temperatures[i]
... | simplelr_Taco | [
{
"content": "Question:\nYou are given an array of integers representing the temperatures recorded over a week. A peak in the array is defined as an element which is greater than its neighbours. Your task is to find the first peak in the array. If no peak exists, return -1.\n\nFor example, in the array `[1, 3, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7643,
"level": 1,
"question": "You are given an array of integers representing the temperatures recorded over a week. A peak in the array is defined as an element which is greater than its neighbours. Your task is to find the first peak in the array. If no peak exists, return -1.\n\... |
import numpy as np
def weighted_sum_update(X, Y, Cond):
mask = Cond < 0
return np.where(mask, 2 * Y, X + Y) | simplelr_Filter | [
{
"content": "Question:\nImplement a Python function that computes the weighted sum of two 2D tensors based on a condition tensor. Given three 4D tensors `X`, `Y`, and `Cond` of the same shape, the function should update `X` such that for each element, if the corresponding element in `Cond` is less than 0, the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7644,
"level": 1,
"question": "Implement a Python function that computes the weighted sum of two 2D tensors based on a condition tensor. Given three 4D tensors `X`, `Y`, and `Cond` of the same shape, the function should update `X` such that for each element, if the corresponding ele... |
def caesar_cipher(text, shift):
result = ""
for c in text:
if c.isalpha():
base = 65 if c.isupper() else 97
offset = ord(c) - base
new_offset = (offset + shift) % 26
new_char = chr(base + new_offset)
result += new_char
else:
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to implement a simple Caesar cipher, which is a type of substitution cipher where each letter in the plaintext is shifted a certain number of places down or up the alphabet. The function should take two parameters: the text to be encrypted and the number of posit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7645,
"level": 1,
"question": "Write a Python function to implement a simple Caesar cipher, which is a type of substitution cipher where each letter in the plaintext is shifted a certain number of places down or up the alphabet. The function should take two parameters: the text to b... |
def sum_of_multiples(numbers: list, limit: int) -> int:
if not numbers or limit <= 0:
return 0
include_zero = 0 in numbers
non_zero = [n for n in numbers if n != 0]
non_zero = list(set(non_zero)) # Remove duplicates
sum_zero = 0
if include_zero and limit > 0:
sum_zero = 0 # Z... | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of Multiples\n\n#### Problem Statement\nWrite a function that calculates the sum of all multiples of a given set of numbers up to a specified limit. The function should be able to handle scenarios where no multiples are found and should work efficiently for a large range of inpu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7646,
"level": 1,
"question": "### Sum of Multiples\n\n#### Problem Statement\nWrite a function that calculates the sum of all multiples of a given set of numbers up to a specified limit. The function should be able to handle scenarios where no multiples are found and should work ef... |
def is_valid_IP(s):
parts = s.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:
return False... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that determines whether a given string is a valid IPv4 address. A valid IPv4 address consists of four numeric sections separated by dots, where each section is an integer between 0 and 255.\n\n### Example\n\n```\nis_valid_IP(\"192.168.1.1\") == True\nis_valid_IP(\"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7647,
"level": 1,
"question": "Write a function that determines whether a given string is a valid IPv4 address. A valid IPv4 address consists of four numeric sections separated by dots, where each section is an integer between 0 and 255.\n\n### Example\n\n```\nis_valid_IP(\"192.168.... |
def coinChange(coins, amount):
if amount == 0:
return 0
# Initialize the dp array with infinity
dp = [float('inf')] * (amount + 1)
dp[0] = 0 # Base case: 0 coins needed to make 0 amount
for coin in coins:
if coin > amount:
continue # Skip coins larger than the amou... | simplelr_Taco | [
{
"content": "Question:\nYou are given a set of coins with different denominations and an amount of money. Your task is to find out the minimum number of coins required to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.\n\nYou may assume that you have a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7648,
"level": 1,
"question": "You are given a set of coins with different denominations and an amount of money. Your task is to find out the minimum number of coins required to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1... |
def reverse_array(arr):
n = len(arr)
for i in range(n // 2):
arr[i], arr[n - 1 - i] = arr[n - 1 - i], arr[i]
return arr
# Example usage
arr = [1, 2, 3, 4, 5]
reverse_array(arr)
print(arr) # Output: [5, 4, 3, 2, 1] | simplelr_Filter | [
{
"content": "Question:\nTo show you an example of an array and how it can be manipulated, consider an array `arr` of integers. Initially, the array is [1, 2, 3, 4, 5]. Write a function in Python that reverses the elements of this array in place without using any additional data structures. Then, call this func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7649,
"level": 1,
"question": "To show you an example of an array and how it can be manipulated, consider an array `arr` of integers. Initially, the array is [1, 2, 3, 4, 5]. Write a function in Python that reverses the elements of this array in place without using any additional da... |
from datetime import datetime, timedelta
def get_due_tasks(tasks, current_date, D):
current_date_obj = datetime.strptime(current_date, "%Y-%m-%d").date()
end_date_obj = current_date_obj + timedelta(days=D)
due_task_ids = []
for task in tasks:
task_id, due_date_str = task
due_date =... | simplelr_Taco | [
{
"content": "Question:\nThe management team at a software development company is working on a new task management application. They are currently concerned with optimizing a feature that allows users to identify tasks which are due soon. The system stores tasks with their due dates and provides a function to r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7650,
"level": 1,
"question": "The management team at a software development company is working on a new task management application. They are currently concerned with optimizing a feature that allows users to identify tasks which are due soon. The system stores tasks with their due... |
import os
def standardize_path(relative_path):
expanded_path = os.path.expanduser(relative_path)
absolute_path = os.path.abspath(expanded_path)
return absolute_path | simplelr_Data_Structure | [
{
"content": "Question:\n**Context**:\nYou are tasked with implementing a utility that standardizes file paths for workspaces in a large-scale collaborative environment. Users might provide various path formats, and it is your job to ensure they are converted to absolute paths for consistency. \n\n### Brief\nIm... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7651,
"level": 1,
"question": "**Context**:\nYou are tasked with implementing a utility that standardizes file paths for workspaces in a large-scale collaborative environment. Users might provide various path formats, and it is your job to ensure they are converted to absolute paths... |
def length_of_longest_substring(s):
left = 0
max_length = 0
char_map = {}
for right in range(len(s)):
char = s[right]
if char in char_map and char_map[char] >= left:
left = char_map[char] + 1
char_map[char] = right
current_length = right - left + 1
... | simplelr_Filter | [
{
"content": "Question:\nGiven a string, find the length of the longest substring without repeating characters.\n\nExample 1:\nInput: \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\n\nExample 2:\nInput: \"bbbbb\"\nOutput: 1\nExplanation: The answer is \"b\", with the length o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7652,
"level": 1,
"question": "Given a string, find the length of the longest substring without repeating characters.\n\nExample 1:\nInput: \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\n\nExample 2:\nInput: \"bbbbb\"\nOutput: 1\nExplanation: The... |
def sort_students(students: list[dict]) -> list[dict]:
return sorted(students, key=lambda x: (-x['grade'], x['name'], x['id'])) | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Problem Description:\nYou are assigned the task of sorting a list of student records based on their grades. Each student record contains three attributes: `name` (a string), `grade` (an integer), and `id` (an integer). Your objective is to sort the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7653,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Problem Description:\nYou are assigned the task of sorting a list of student records based on their grades. Each student record contains three attributes: `name` (a string), `grade` (an integer), and `id` (an inte... |
from collections import Counter
def custom_sort(lst):
count = Counter(lst)
singles = []
first_dup = []
second_dup = []
seen = {}
for num in lst:
if count[num] == 1:
singles.append(num)
else:
if seen.get(num, 0) == 0:
first_dup.append(num)... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers `lst` where each integer appears either once or twice. Sort the list in ascending order such that the integers that appear once come before the integers that appear twice. If two integers appear the same number of times, they should be sorted based on th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7654,
"level": 1,
"question": "You are given a list of integers `lst` where each integer appears either once or twice. Sort the list in ascending order such that the integers that appear once come before the integers that appear twice. If two integers appear the same number of times... |
def longest_subsequence_length(nums, k):
if not nums:
return 0
nums.sort()
max_len = 1
current_len = 1
for i in range(1, len(nums)):
if nums[i] - nums[i-1] <= k:
current_len += 1
if current_len > max_len:
max_len = current_len
else:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums` and a positive integer `k`. Return _the length of the longest subsequence of `nums` that satisfies the given conditions:_ \n1. The absolute difference between any two elements in the subsequence is less than or equal to `k`.\n2. The subsequence ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7655,
"level": 1,
"question": "You are given an array of integers `nums` and a positive integer `k`. Return _the length of the longest subsequence of `nums` that satisfies the given conditions:_ \n1. The absolute difference between any two elements in the subsequence is less than or... |
def merge_and_sort_dicts(dict1, dict2):
# Merge the dictionaries, with dict2's values overwriting dict1's
merged = dict1.copy()
merged.update(dict2)
# Sort the items by their values in ascending order
sorted_items = sorted(merged.items(), key=lambda item: item[1])
# Create a new dictionary from ... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function `merge_and_sort_dicts` that merges two dictionaries into a new dictionary and sorts the combined dictionary by its values. The function should take two arguments:\n1. `dict1`: The first dictionary to merge.\n2. `dict2`: The second dictionary to me... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7656,
"level": 1,
"question": "You are tasked with creating a function `merge_and_sort_dicts` that merges two dictionaries into a new dictionary and sorts the combined dictionary by its values. The function should take two arguments:\n1. `dict1`: The first dictionary to merge.\n2. `... |
def min_sum_path(mat):
if not mat or not mat[0]:
return 0
rows = len(mat)
cols = len(mat[0])
dp = [[0 for _ in range(cols)] for _ in range(rows)]
dp[0][0] = mat[0][0]
# Fill the first row
for j in range(1, cols):
dp[0][j] = dp[0][j-1] + mat[0][j]
# Fill the first column
... | simplelr_Apps | [
{
"content": "Question:\nYou are given a matrix of size n x m filled with non-negative integers. Your task is to start from the top-left corner of the matrix and reach the bottom-right corner, moving only right or down.\n\nWrite a function to return the minimum sum of all numbers along its path.\n\nExamples:\nI... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7657,
"level": 1,
"question": "You are given a matrix of size n x m filled with non-negative integers. Your task is to start from the top-left corner of the matrix and reach the bottom-right corner, moving only right or down.\n\nWrite a function to return the minimum sum of all numb... |
def create_tuple(str_input, int_input, flt_input):
return (str_input, int_input, flt_input)
my_tuple = create_tuple("Hello World", 20, 50.7) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program where you first define a function called \"create_tuple\" that takes three parameters, a string 'str_input', an integer 'int_input' and a float 'flt_input'. This function should then create and return a tuple with these three parameters as its elements. After defi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7658,
"level": 1,
"question": "Write a Python program where you first define a function called \"create_tuple\" that takes three parameters, a string 'str_input', an integer 'int_input' and a float 'flt_input'. This function should then create and return a tuple with these three par... |
def find_majority(nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count = 1
else:
if num == candidate:
count += 1
else:
count -= 1
# Verify if the candidate is a majority ele... | simplelr_Apps | [
{
"content": "Question:\nGiven a list of non-negative integers `nums`, write a function `find_majority` to determine if there exists a majority element. A majority element is an element that appears **more than n/2** times in the list `nums`, where n is the length of the list. If a majority element exists, retu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7659,
"level": 1,
"question": "Given a list of non-negative integers `nums`, write a function `find_majority` to determine if there exists a majority element. A majority element is an element that appears **more than n/2** times in the list `nums`, where n is the length of the list.... |
def is_valid_parentheses(s):
stack = []
bracket_map = {')': '(', '}': '{', ']': '['}
for char in s:
if char in bracket_map.values():
stack.append(char)
elif char in bracket_map:
if not stack:
return False
if stack.pop() != bracket_map[char]... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an input string, create a function to evaluate whether the parentheses in the string are balanced. The string can include the characters '(', ')', '{', '}', '[' and ']'. Your function should return `true` if the string is valid, and `false` otherwise. A string is considered valid ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7660,
"level": 1,
"question": "Given an input string, create a function to evaluate whether the parentheses in the string are balanced. The string can include the characters '(', ')', '{', '}', '[' and ']'. Your function should return `true` if the string is valid, and `false` other... |
def minCostToMeet(points, costPerUnit):
points.sort()
n = len(points)
median = points[n // 2]
total = 0
for p in points:
total += abs(p - median)
return total * costPerUnit | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array `points` representing the positions of `n` cars on a number line. The `i-th` car is initially at position `points[i]`. Each car can drive to any position in front of (or behind) it with a constant speed, but at a cost per unit distance traveled. The goal is for al... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7661,
"level": 1,
"question": "You are given an array `points` representing the positions of `n` cars on a number line. The `i-th` car is initially at position `points[i]`. Each car can drive to any position in front of (or behind) it with a constant speed, but at a cost per unit di... |
from collections import deque
def sliding_window_maximum(prices, k):
dq = deque()
result = []
for i in range(len(prices)):
# Remove indices out of the window
while dq and dq[0] < i - k + 1:
dq.popleft()
# Remove elements smaller than the current element
while dq ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `prices` where `prices[i]` represents the price of a particular item on the `i`-th day. There is also a sliding window of size `k`. Your task is to find, for each day `i`, the maximum price of the items within the sliding window of size `k` that ends o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7662,
"level": 1,
"question": "You are given an array of integers `prices` where `prices[i]` represents the price of a particular item on the `i`-th day. There is also a sliding window of size `k`. Your task is to find, for each day `i`, the maximum price of the items within the sli... |
def find_length(arr1: list, arr2: list) -> int:
n = len(arr1)
m = len(arr2)
if n == 0 or m == 0:
return 0
dp = [[0] * (m + 1) for _ in range(n + 1)]
max_length = 0
for i in range(1, n + 1):
for j in range(1, m + 1):
if arr1[i-1] == arr2[j-1]:
dp[i][j] ... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\nYou are given two arrays `arr1` and `arr2` of integers. Your task is to find the length of the longest subarray that appears in both arrays.\n\n### Function Signature\n```python\ndef find_length(arr1: list, arr2: list) -> int:\n```\n\n### Input\n* `arr1` and `arr2` are l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7663,
"level": 1,
"question": "### Question\n\nYou are given two arrays `arr1` and `arr2` of integers. Your task is to find the length of the longest subarray that appears in both arrays.\n\n### Function Signature\n```python\ndef find_length(arr1: list, arr2: list) -> int:\n```\n\n#... |
import heapq
def minEffortPath(grid):
if not grid or not grid[0]:
return 0 # assuming empty grid or single cell
rows = len(grid)
cols = len(grid[0])
# Initialize efforts grid with infinity
efforts = [[float('inf')] * cols for _ in range(rows)]
efforts[0][0] = 0
# Pri... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a 2D grid of integers where each cell represents elevation, implement an algorithm to find the minimum-effort path from the top-left cell to the bottom-right cell. The effort of a path is defined as the maximum difference in elevation between two consecutive cells along the path. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7664,
"level": 1,
"question": "Given a 2D grid of integers where each cell represents elevation, implement an algorithm to find the minimum-effort path from the top-left cell to the bottom-right cell. The effort of a path is defined as the maximum difference in elevation between two... |
def product_of_negatives(lst):
product = 1
for num in lst:
if num < 0:
product *= num
return product | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns the product of all the negative numbers in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7665,
"level": 1,
"question": "Create a function that takes a list of integers and returns the product of all the negative numbers in the list.",
"split": "train"
} |
def minPartitionDifference(arr, n):
total = sum(arr)
half_sum = total // 2
dp = [False] * (half_sum + 1)
dp[0] = True # Base case: sum of 0 is always possible
for num in arr:
for s in range(half_sum, num - 1, -1):
if dp[s - num]:
dp[s] = True
max_sum = 0
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of N integers. Your task is to partition the list into two subarrays such that the absolute difference between the sums of the two subarrays is minimized. Return the minimized absolute difference.\n\nExample 1:\nInput:\nN = 4\nArr[] = {1, 6, 11, 5}\nOutput:\n1\nExpl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7666,
"level": 1,
"question": "You are given a list of N integers. Your task is to partition the list into two subarrays such that the absolute difference between the sums of the two subarrays is minimized. Return the minimized absolute difference.\n\nExample 1:\nInput:\nN = 4\nArr[... |
import linecache
def extract_lines(filename: str, line_numbers: list) -> list:
linecache.clearcache()
result = []
for ln in line_numbers:
try:
line = linecache.getline(filename, ln)
result.append(line)
except:
result.append("")
linecache.clearcache()
... | simplelr_Docs | [
{
"content": "Question:\nYou are to create a function `extract_lines` that reads multiple specific lines from a given file and returns them as a list of strings. Use the `linecache` module to achieve this. Make sure to handle the cache appropriately to ensure that the solution works even if the file is updated ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7667,
"level": 1,
"question": "You are to create a function `extract_lines` that reads multiple specific lines from a given file and returns them as a list of strings. Use the `linecache` module to achieve this. Make sure to handle the cache appropriately to ensure that the solution... |
import json
def is_valid_json(s):
if not s:
return False
try:
json.loads(s)
return True
except json.JSONDecodeError:
return False
# Example usage:
# print(is_valid_json('{"key": "value"}')) # Output: True
# print(is_valid_json('Invalid JSON')) # Output: False
# print(is_v... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code snippet to check if a given string is valid JSON format?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7668,
"level": 1,
"question": "Can you provide a Python code snippet to check if a given string is valid JSON format?",
"split": "train"
} |
def print_numbers(n):
for i in range(1, n + 1):
print(i) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to print the numbers from 1 to n in ascending order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7669,
"level": 1,
"question": "Write a python function to print the numbers from 1 to n in ascending order.",
"split": "train"
} |
def left_rotate(arr, n):
if not arr:
return []
effective_n = n % len(arr)
return arr[effective_n:] + arr[:effective_n] | simplelr_Filter | [
{
"content": "Question:\nYou've been tasked with designing a function `left_rotate` that takes an array and an integer as input. The function should rotate the array to the left by the specified number of positions. For example, if the array is `[1, 2, 3, 4, 5]` and the number of positions is `2`, the output sh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7670,
"level": 1,
"question": "You've been tasked with designing a function `left_rotate` that takes an array and an integer as input. The function should rotate the array to the left by the specified number of positions. For example, if the array is `[1, 2, 3, 4, 5]` and the number... |
def max_values(lst):
result = []
for sublist in lst:
if sublist:
result.append(max(sublist))
return result
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of lists as input and returns a list containing the maximum values from each sublist. If a sublist is empty, skip it.\n\nExample:\n\n```python\nmax_values([[1, 3, 5], [4, 6, 2], [], [-1, -5, -3], [10, 15, 5]]) # [5, 6, -1, 15]\nmax_values([[7], [0], [2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7671,
"level": 1,
"question": "Write a function that takes a list of lists as input and returns a list containing the maximum values from each sublist. If a sublist is empty, skip it.\n\nExample:\n\n```python\nmax_values([[1, 3, 5], [4, 6, 2], [], [-1, -5, -3], [10, 15, 5]]) # [5, 6... |
from collections import defaultdict
from typing import List
def count_anagram_pairs(words: List[str]) -> int:
# Check if the input is a list
if not isinstance(words, list):
raise TypeError("Input must be a list.")
# Validate each word and compute anagram keys
anagram_counts = defaultdict(i... | simplelr_Algorithm | [
{
"content": "Question:\n### Anagram Pair Counter\n\nYou are tasked with implementing a function that counts the number of anagram pairs in a list of strings. The function should handle various edge cases and input formats.\n\n#### Function Signature\n```python\ndef count_anagram_pairs(words: List[str]) -> int:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7672,
"level": 1,
"question": "### Anagram Pair Counter\n\nYou are tasked with implementing a function that counts the number of anagram pairs in a list of strings. The function should handle various edge cases and input formats.\n\n#### Function Signature\n```python\ndef count_anag... |
def knapsack(capacity, items):
dp = [0] * (capacity + 1)
for weight, value in items:
for w in range(capacity, weight - 1, -1):
if dp[w - weight] + value > dp[w]:
dp[w] = dp[w - weight] + value
return dp[capacity] | simplelr_Filter | [
{
"content": "Question:\nCan you write a Python function to solve the 0/1 Knapsack problem using dynamic programming? The function should take the maximum weight capacity of the knapsack and a list of items, where each item is represented as a tuple of (weight, value). It should return the maximum value that ca... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7673,
"level": 1,
"question": "Can you write a Python function to solve the 0/1 Knapsack problem using dynamic programming? The function should take the maximum weight capacity of the knapsack and a list of items, where each item is represented as a tuple of (weight, value). It shou... |
def trap_rain_water(arr):
n = len(arr)
if n <= 2:
return 0
left_max = [0] * n
for i in range(1, n):
left_max[i] = max(left_max[i-1], arr[i-1])
right_max = [0] * n
for i in range(n-2, -1, -1):
right_max[i] = max(right_max[i+1], arr[i+1])
total = 0
for i in range(n)... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr`, representing the heights of a series of buildings. Each building can trap rainwater between it and the next taller building to its right. Write a function to return _the total amount of water trapped_ between the buildings after raining.\nAnswer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7674,
"level": 1,
"question": "You are given an array of integers `arr`, representing the heights of a series of buildings. Each building can trap rainwater between it and the next taller building to its right. Write a function to return _the total amount of water trapped_ between t... |
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[-1]
left = [x for x in arr[:-1] if x <= pivot]
right = [x for x in arr[:-1] if x > pivot]
return quicksort(left) + [pivot] + quicksort(right) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to sort an array using the quicksort algorithm. Пример: Для входного массива [10, 7, 8, 9, 1, 5] результат будет [1, 5, 7, 8, 9, 10].\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7675,
"level": 1,
"question": "Write a python function to sort an array using the quicksort algorithm. Пример: Для входного массива [10, 7, 8, 9, 1, 5] результат будет [1, 5, 7, 8, 9, 10].",
"split": "train"
} |
from typing import List
def contains_duplicates(nums: List[int]) -> bool:
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given a list of integers, and you need to detect whether the list contains any duplicate elements. If there are duplicates, return `True`. If no duplicates are present, return `False`.\n\n### Function Signature\n```python\ndef contains_duplicates(nums: L... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7676,
"level": 1,
"question": "### Problem Statement\n\nYou are given a list of integers, and you need to detect whether the list contains any duplicate elements. If there are duplicates, return `True`. If no duplicates are present, return `False`.\n\n### Function Signature\n```pyth... |
import heapq
def nth_ugly_number(n):
heap = []
heapq.heappush(heap, 1)
seen = set()
seen.add(1)
ugly_numbers = []
while len(ugly_numbers) < n:
current = heapq.heappop(heap)
ugly_numbers.append(current)
for factor in [2, 3, 5]:
next_num = current... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to print the nth Ugly Number. An ugly number is a positive integer whose prime factors only include 2, 3, and 5. For example, the first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7677,
"level": 1,
"question": "Write a python function to print the nth Ugly Number. An ugly number is a positive integer whose prime factors only include 2, 3, and 5. For example, the first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12.",
"split": "train"
} |
def stutter_stack(stack):
stack[:] = [x for x in stack for _ in range(2)] | simplelr_Data_Structure | [
{
"content": "Question:\n#### Context:\nYou have a stack data structure that is already populated with integer values. Your goal is to replace each value in the stack with two occurrences of that value, maintaining the original order.\n\n#### Function Signature:\nImplement a function named `stutter_stack` that ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7678,
"level": 1,
"question": "#### Context:\nYou have a stack data structure that is already populated with integer values. Your goal is to replace each value in the stack with two occurrences of that value, maintaining the original order.\n\n#### Function Signature:\nImplement a f... |
def remove_duplicates(s):
seen = set()
result = []
for char in s:
if char not in seen:
result.append(char)
seen.add(char)
return ''.join(result) | simplelr_Evol | [
{
"content": "Question:\nYou are given a string containing only lowercase alphabetical characters. Your task is to implement an algorithm that removes any duplicate characters and returns the string with only the first occurrence of each character, while preserving the original order of characters.\n\nExample:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7679,
"level": 1,
"question": "You are given a string containing only lowercase alphabetical characters. Your task is to implement an algorithm that removes any duplicate characters and returns the string with only the first occurrence of each character, while preserving the origina... |
def reverse_vowels(s):
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
s_list = list(s)
reversed_v = [c for c in s if c in vowels][::-1]
v_index = 0
for i in range(len(s_list)):
if s_list[i] in vowels:
s_list[i] = reversed_v[v_index]
v_index += 1
retur... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python script that takes a string and reverses only the vowels in it while leaving the rest of the characters in their original positions. For example, if the input is \"hello\", the output should be \"holle\". Ensure to maintain the case of the characters.\nAnswer:\nLet's think... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7680,
"level": 1,
"question": "Write a Python script that takes a string and reverses only the vowels in it while leaving the rest of the characters in their original positions. For example, if the input is \"hello\", the output should be \"holle\". Ensure to maintain the case of th... |
def decode_string(s: str) -> str:
"""
Decodes a given encoded string as per the encoding rules.
:param s: str : Encoded string
:return: str : Decoded string
"""
stack = []
current_str = ""
current_num = 0
for char in s:
if char.isdigit():
current_num = curren... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario:\nYou are part of a development team creating a text-based game where certain commands are encoded to shorten their notation. Your task is to write a function that decodes these commands into their full representation so that the game can execute them correctly.\n\n### Task... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7681,
"level": 1,
"question": "### Scenario:\nYou are part of a development team creating a text-based game where certain commands are encoded to shorten their notation. Your task is to write a function that decodes these commands into their full representation so that the game can ... |
def reverse_string(s):
if len(s) <= 1:
return s
else:
return s[-1] + reverse_string(s[:-1]) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code to reverse a string using a recursive function.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7682,
"level": 1,
"question": "Write a Python code to reverse a string using a recursive function.",
"split": "train"
} |
def min_max_manhattan_distance(nums1, nums2):
# Compute s and d for each point in the first set (assuming the second set is the same)
s1 = [x + y for x, y in zip(nums1, nums2)]
d1 = [x - y for x, y in zip(nums1, nums2)]
# Since the second set is the same as the first, we can reuse the same lists
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two integer arrays `nums1` and `nums2` of the same length `n`. Each element in the arrays represents a point's coordinate on a 2D plane. Specifically, `nums1[i]` and `nums2[i]` together form the coordinate `(nums1[i], nums2[i])`. You want to form `n` pairs such that each p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7683,
"level": 1,
"question": "You are given two integer arrays `nums1` and `nums2` of the same length `n`. Each element in the arrays represents a point's coordinate on a 2D plane. Specifically, `nums1[i]` and `nums2[i]` together form the coordinate `(nums1[i], nums2[i])`. You want... |
def sum_elementwise(list1, list2):
result = []
for a, b in zip(list1, list2):
result.append(a + b)
return result | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that calculates the sum of the elements of two lists element-wise and returns a new list containing the results? If the lists are of unequal length, the function should stop at the end of the shorter list.\nAnswer:\nLet's think step by step.\n",
"r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7684,
"level": 1,
"question": "How can I create a Python function that calculates the sum of the elements of two lists element-wise and returns a new list containing the results? If the lists are of unequal length, the function should stop at the end of the shorter list.",
"split"... |
def sum_even_nums_or_even_index(nums):
total = 0
for i in range(len(nums)):
if i % 2 == 0 or nums[i] % 2 == 0:
total += nums[i]
return total | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a 0-indexed integer array `nums` of length `n`. Your task is to return the sum of all elements that are either even or appear at an even index. Implement a function that calculates this sum.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7685,
"level": 1,
"question": "You are given a 0-indexed integer array `nums` of length `n`. Your task is to return the sum of all elements that are either even or appear at an even index. Implement a function that calculates this sum.",
"split": "train"
} |
def max_profit(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 = pric... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the maximum profit from buying and selling stocks on a single day. You are given a list of stock prices on consecutive days.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7686,
"level": 1,
"question": "Write a function to calculate the maximum profit from buying and selling stocks on a single day. You are given a list of stock prices on consecutive days.",
"split": "train"
} |
def is_rotation(str1, str2):
return len(str1) == len(str2) and str2 in (str1 + str1) | simplelr_Filter | [
{
"content": "Question:\nYou are given two strings, 'str1' and 'str2'. You need to check if 'str2' is a rotation of 'str1'.\n\nExample:\n\nstr1 = \"waterbottle\"\nstr2 = \"erbottlewat\"\n\nIn this case, 'str2' is indeed a rotation of 'str1'.\n\n\nCan you provide a Python code to check this?\nAnswer:\nLet's thin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7687,
"level": 1,
"question": "You are given two strings, 'str1' and 'str2'. You need to check if 'str2' is a rotation of 'str1'.\n\nExample:\n\nstr1 = \"waterbottle\"\nstr2 = \"erbottlewat\"\n\nIn this case, 'str2' is indeed a rotation of 'str1'.\n\n\nCan you provide a Python code ... |
import re
from collections import Counter
def analyze_word_frequencies(file_path, stop_words):
with open(file_path, 'r') as f:
text = f.read()
text_lower = text.lower()
cleaned_text = re.sub(r'[^\w\s]', '', text_lower)
words = cleaned_text.split()
filtered_words = [word for word in words if... | simplelr_Package | [
{
"content": "Question:\nIn this problem, you are required to write a function, `analyze_word_frequencies(file_path, stop_words)`, which reads a text file and calculates word frequencies, ignoring specified stop words. The function should utilize the `collections.Counter` class to manage word counts and regular... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7688,
"level": 1,
"question": "In this problem, you are required to write a function, `analyze_word_frequencies(file_path, stop_words)`, which reads a text file and calculates word frequencies, ignoring specified stop words. The function should utilize the `collections.Counter` clas... |
from collections import Counter
def find_common_elements_with_duplicates(list1, list2):
counter = Counter(list2)
result = []
for elem in list1:
if counter.get(elem, 0) > 0:
result.append(elem)
counter[elem] -= 1
return result | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function named \"find_common_elements_with_duplicates\" that takes two lists as parameters, list1 and list2. The function should return a new list containing the elements that are common to both lists, including duplicates. The order of the elements in the resulting list... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7689,
"level": 1,
"question": "Create a Python function named \"find_common_elements_with_duplicates\" that takes two lists as parameters, list1 and list2. The function should return a new list containing the elements that are common to both lists, including duplicates. The order of... |
from collections import Counter
def count_characters(words, chars):
char_freq = Counter(chars)
total_chars = len(chars)
sum_len = 0
for word in words:
word_len = len(word)
if word_len > total_chars:
continue
word_freq = Counter(word)
valid = True
for ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of strings `words` and a single string `chars`. Each string in `words` can be formed by characters from `chars` if the frequency of each character in the string does not exceed the frequency of the character in `chars`. Return _the sum of the lengths of all strings ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7690,
"level": 1,
"question": "You are given a list of strings `words` and a single string `chars`. Each string in `words` can be formed by characters from `chars` if the frequency of each character in the string does not exceed the frequency of the character in `chars`. Return _the... |
def can_be_equal_by_swapping(str1: str, str2: str) -> bool:
diffs = [i for i in range(len(str1)) if str1[i] != str2[i]]
if len(diffs) not in (0, 2):
return False
if len(diffs) == 0:
return True
i, j = diffs
return str1[i] == str2[j] and str1[j] == str2[i]
| simplelr_Taco | [
{
"content": "Question:\n### Task\nYou are given two strings `str1` and `str2` both of the same length, comprising only lowercase letters of the English alphabet. Your task is to determine if these strings can be made equal by swapping at most two characters within `str1`.\n\n### Example\nGiven two strings:\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7691,
"level": 1,
"question": "### Task\nYou are given two strings `str1` and `str2` both of the same length, comprising only lowercase letters of the English alphabet. Your task is to determine if these strings can be made equal by swapping at most two characters within `str1`.\n\n... |
from collections import Counter
def most_frequent_word(word_list):
if not word_list:
return ''
counts = Counter(word_list)
items = counts.items()
sorted_items = sorted(items, key=lambda x: (-x[1], x[0]))
return sorted_items[0][0] | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of strings, where each string represents a word. Your function should return the word that appears the most frequently in the list. If there is a tie, return the word that comes first lexicographically. For example, given the list `['apple', 'banana', ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7692,
"level": 1,
"question": "Write a function that takes a list of strings, where each string represents a word. Your function should return the word that appears the most frequently in the list. If there is a tie, return the word that comes first lexicographically. For example, g... |
def extract_even_numbers(input_list):
try:
if not isinstance(input_list, list):
raise TypeError
even = []
for num in input_list:
if not isinstance(num, int):
raise ValueError
if num % 2 == 0:
even.append(num)
return ... | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes a list of integers as input and returns a new list containing only the integers that are even. Additionally, the function should handle any exceptions that might occur if the input is not a list of integers. If an exception occurs, the function shou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7693,
"level": 1,
"question": "Write a function in Python that takes a list of integers as input and returns a new list containing only the integers that are even. Additionally, the function should handle any exceptions that might occur if the input is not a list of integers. If an ... |
def sum_of_squares(a, b):
return a ** 2 + b ** 2 | simplelr_Filter | [
{
"content": "Question:\nI want to create a Python function that calculates the sum of the squares of two numbers. Can you help me write this function?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7694,
"level": 1,
"question": "I want to create a Python function that calculates the sum of the squares of two numbers. Can you help me write this function?",
"split": "train"
} |
def sum_of_digits(s):
total = 0
for c in s:
if c.isdigit():
total += int(c)
return total | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function that calculates the sum of all digits in a given string? The function should ignore any non-digit characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7695,
"level": 1,
"question": "Can you provide a Python function that calculates the sum of all digits in a given string? The function should ignore any non-digit characters.",
"split": "train"
} |
def sieve_of_eratosthenes(n):
if n <= 2:
return []
sieve = [True] * n
sieve[0], sieve[1] = False, False
for current in range(2, int(n ** 0.5) + 1):
if sieve[current]:
for multiple in range(current * current, n, current):
sieve[multiple] = False
primes = [i... | simplelr_Taco | [
{
"content": "Question:\nCreate a function that takes an integer `n` as input and returns a list of all the prime numbers less than `n`. Your function should minimize the computational complexity as much as possible.\n\nFor example:\n\n- If `n = 10`, the function should return `[2, 3, 5, 7]`.\n- If `n = 20`, th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7696,
"level": 1,
"question": "Create a function that takes an integer `n` as input and returns a list of all the prime numbers less than `n`. Your function should minimize the computational complexity as much as possible.\n\nFor example:\n\n- If `n = 10`, the function should return... |
def sum_2d_list(lst):
sum_total = 0
for row in lst:
for element in row:
if type(element) in (int, float):
sum_total += element
return sum_total | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum of all elements in a 2D list (list of lists) in Python. The function should handle cases where the 2D list may contain non-numeric values by ignoring them.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7697,
"level": 1,
"question": "Write a function to calculate the sum of all elements in a 2D list (list of lists) in Python. The function should handle cases where the 2D list may contain non-numeric values by ignoring them.",
"split": "train"
} |
def min_books(ratings):
n = len(ratings)
if n == 0:
return 0
books = [1] * n
# Left to right pass
for i in range(1, n):
if ratings[i] > ratings[i-1]:
books[i] = books[i-1] + 1
# Right to left pass
for i in range(n-2, -1, -1):
if ratings[i] > rati... | simplelr_Leetcode | [
{
"content": "Question:\n## New Question 4:\n\nConsider a **0-indexed** integer array `ratings` of length `n` where `ratings[i]` represents the rating value of the `i-th` student. You are to distribute books to these students such that:\n\n1. Each student receives at least one book.\n2. Students with a higher r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7698,
"level": 1,
"question": "## New Question 4:\n\nConsider a **0-indexed** integer array `ratings` of length `n` where `ratings[i]` represents the rating value of the `i-th` student. You are to distribute books to these students such that:\n\n1. Each student receives at least one... |
def compress_ranges(nums):
if not nums:
return ""
if len(nums) == 1:
return str(nums[0])
ranges = []
start = end = nums[0]
for num in nums[1:]:
if num == end + 1:
end = num
else:
if start == end:
ranges.append(str(start))
... | simplelr_Apps | [
{
"content": "Question:\nCreate a function `compress_ranges` that takes a sorted list of integers and returns a string that represents the ranges of consecutive numbers.\n\nThe output string should represent each range of consecutive numbers in the input list with a start and end number separated by a dash, and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7699,
"level": 1,
"question": "Create a function `compress_ranges` that takes a sorted list of integers and returns a string that represents the ranges of consecutive numbers.\n\nThe output string should represent each range of consecutive numbers in the input list with a start and ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.