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 find_longest_substring(s):
last_pos = {}
max_length = 0
left = 0
for right in range(len(s)):
char = s[right]
if char in last_pos and last_pos[char] >= left:
left = last_pos[char] + 1
last_pos[char] = right
current_length = right - left + 1
if curre... | simplelr_Package | [
{
"content": "Question:\nYou are asked to implement a function named `find_longest_substring` that finds the length of the longest substring without repeating characters. This problem commonly appears in coding interviews and assesses your understanding of string manipulation and efficient algorithm design.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6200,
"level": 1,
"question": "You are asked to implement a function named `find_longest_substring` that finds the length of the longest substring without repeating characters. This problem commonly appears in coding interviews and assesses your understanding of string manipulation ... |
import heapq
from typing import Dict, Any, Optional
def dijkstra_shortest_path(graph: Dict[Any, Dict[Any, int]], start: Any, target: Any) -> Optional[int]:
if start not in graph or target not in graph:
return None
distances = {node: float('infinity') for node in graph}
distances[start] = 0
he... | simplelr_Algorithm | [
{
"content": "Question:\n### Graph Shortest Path Algorithm\n\nGraphs are data structures that consist of vertices (or nodes) connected by edges. Finding the shortest path from one vertex to another is a common problem which can be efficiently solved using algorithms like Dijkstra's algorithm.\n\n### Objective:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6201,
"level": 1,
"question": "### Graph Shortest Path Algorithm\n\nGraphs are data structures that consist of vertices (or nodes) connected by edges. Finding the shortest path from one vertex to another is a common problem which can be efficiently solved using algorithms like Dijks... |
from typing import List
def single_number3(nums: List[int]) -> List[int]:
xor_sum = 0
for num in nums:
xor_sum ^= num
mask = xor_sum & -xor_sum # Find the rightmost set bit
a, b = 0, 0
for num in nums:
if num & mask:
a ^= num
else:
b ^= num... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\n\nYou need to implement a function that finds two elements in a given list that appear only once while all other elements appear exactly twice. Utilize an efficient algorithm to ensure your solution has a time complexity of O(N) and a space complexity of O(1).\n\n#### Func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6202,
"level": 1,
"question": "### Question\n\nYou need to implement a function that finds two elements in a given list that appear only once while all other elements appear exactly twice. Utilize an efficient algorithm to ensure your solution has a time complexity of O(N) and a spa... |
def max_non_overlapping_events(events):
if not events:
return 0
sorted_events = sorted(events, key=lambda x: x[1])
count = 0
last_end = float('-inf')
for event in sorted_events:
start, end = event[0], event[1]
if start >= last_end:
count += 1
last_end ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `events` where each event is represented by an interval `[start, end]`, with `start` being the start time and `end` being the end time (inclusive). An event `[start, end]` is valid if it does not overlap with any other event in the list. Your task is to find the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6203,
"level": 1,
"question": "You are given a list of `events` where each event is represented by an interval `[start, end]`, with `start` being the start time and `end` being the end time (inclusive). An event `[start, end]` is valid if it does not overlap with any other event in ... |
from typing import List
def max_subarray_product(nums: List[int]) -> int:
if not nums:
return 0 # Though the problem states the list has at least one element
max_p = min_p = global_max = nums[0]
for num in nums[1:]:
prev_max = max_p
prev_min = min_p
curre... | simplelr_Package | [
{
"content": "Question:\nCreate a function `max_subarray_product(nums)` that takes a list of integers `nums` and returns the maximum product of a contiguous subarray. The array will contain both positive and negative numbers, as well as zeros.\n\nThe main challenge is to handle the changes in sign that can dram... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6204,
"level": 1,
"question": "Create a function `max_subarray_product(nums)` that takes a list of integers `nums` and returns the maximum product of a contiguous subarray. The array will contain both positive and negative numbers, as well as zeros.\n\nThe main challenge is to handl... |
def single_element(nums):
result = 0
for num in nums:
result ^= num
return result
| simplelr_Taco | [
{
"content": "Question:\nIn a sequence of integers, every element appears twice except for one element, which appears only once. Write a function to find that single element. You must implement a solution with a linear runtime complexity and use only constant extra space.\n\nConstraints\n\n* 1 ≤ n ≤ 3 * 10^4\n*... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6205,
"level": 1,
"question": "In a sequence of integers, every element appears twice except for one element, which appears only once. Write a function to find that single element. You must implement a solution with a linear runtime complexity and use only constant extra space.\n\nC... |
from typing import List
def binary_search_name(names: List[str], target: str) -> int:
if not names:
return -1
low = 0
high = len(names) - 1
while low <= high:
mid = (low + high) // 2
if names[mid] == target:
return mid
elif target < names[mid]:
hi... | simplelr_Data_Structure | [
{
"content": "Question:\nBinary Search\n\n#### Scenario\nSuppose you are developing a search utility for a contacts application where users have a list of contacts sorted alphabetically by their names. You need to implement a search function that efficiently locates a contact by their name.\n\n#### Task\nWrite ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6206,
"level": 1,
"question": "Binary Search\n\n#### Scenario\nSuppose you are developing a search utility for a contacts application where users have a list of contacts sorted alphabetically by their names. You need to implement a search function that efficiently locates a contact ... |
import re
def replace_ii_oo(s):
return re.sub(r'(ii|oo)', lambda m: m.group()[0], s) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that performs the same operations as these two steps: `str1 = str1.replace('ii', 'i').replace('oo', 'o')` and store the result in `str1`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6207,
"level": 1,
"question": "Create a function that performs the same operations as these two steps: `str1 = str1.replace('ii', 'i').replace('oo', 'o')` and store the result in `str1`.",
"split": "train"
} |
def reverse_bits_generalized(n, bit_length):
m = 0
i = 0
while i < bit_length:
m = (m << 1) + (n & 1)
n >>= 1
i += 1
return m | simplelr_Data_Structure | [
{
"content": "Question:\n### Question:\nGiven the reverse_bits function that reverses the bits of a 32-bit unsigned integer, enhance the function to handle reversing bits for different data sizes. Implement a general bit-reversal function `reverse_bits_generalized(n, bit_length)` that reverses the bits of a giv... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6208,
"level": 1,
"question": "### Question:\nGiven the reverse_bits function that reverses the bits of a 32-bit unsigned integer, enhance the function to handle reversing bits for different data sizes. Implement a general bit-reversal function `reverse_bits_generalized(n, bit_lengt... |
def isValidParentheses(s):
stack = []
mapping = { '(': ')', '[': ']', '{': '}' }
for char in s:
if char in mapping:
stack.append(mapping[char])
else:
if not stack:
return False
top = stack.pop()
if char != top:
r... | simplelr_Taco | [
{
"content": "Question:\nWrite a function `isValidParentheses(s)` that takes a string `s` as input and checks whether the input string is a valid combination of parentheses. A valid combination means every opening parenthesis has a corresponding closing parenthesis and the pairs are correctly nested. The functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6209,
"level": 1,
"question": "Write a function `isValidParentheses(s)` that takes a string `s` as input and checks whether the input string is a valid combination of parentheses. A valid combination means every opening parenthesis has a corresponding closing parenthesis and the pai... |
def product_of_list(lst):
product = 1
for num in lst:
product *= num
return product
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns the product of all the elements in the list. For example:\n\n```python\n[1, 2, 3, 4] ==> 24\n\n[2, 5, 7] ==> 70\n```\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6210,
"level": 1,
"question": "Write a function that takes a list of integers and returns the product of all the elements in the list. For example:\n\n```python\n[1, 2, 3, 4] ==> 24\n\n[2, 5, 7] ==> 70\n```",
"split": "train"
} |
def separate_numbers(arr):
pos = [x for x in arr if x > 0]
neg = [x for x in arr if x < 0]
neither = [x for x in arr if x == 0]
return pos, neg, neither | simplelr_Filter | [
{
"content": "Question:\nI have an array of integers with multiple elements that have the same sign. For example: [3, 5, -2, 1, -5, -7, 8] I want to separate the array into three subarrays. One containing the positive numbers, one containing the negative numbers, and one containing the numbers that aren't in e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6211,
"level": 1,
"question": "I have an array of integers with multiple elements that have the same sign. For example: [3, 5, -2, 1, -5, -7, 8] I want to separate the array into three subarrays. One containing the positive numbers, one containing the negative numbers, and one cont... |
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
def plot_penguin_data():
# Load the dataset and drop any rows with missing values
penguins = sns.load_dataset('penguins').dropna()
# Plot 1: Distribution of bill_length_mm
plt.figure()
sns.histplot(penguins, x='bill_length_mm... | simplelr_Docs | [
{
"content": "Question:\n### Question\n\nYou are a data analyst working on a dataset of various penguin species. Your task is to visualize this dataset to extract meaningful insights. Specifically, you need to create multiple visualizations to uncover patterns and distributions.\n\n1. Load the dataset `penguins... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6212,
"level": 1,
"question": "### Question\n\nYou are a data analyst working on a dataset of various penguin species. Your task is to visualize this dataset to extract meaningful insights. Specifically, you need to create multiple visualizations to uncover patterns and distribution... |
def min_path_sum(mat):
if not mat or not mat[0]:
return 0
m = len(mat)
n = len(mat[0])
# Initialize the first row
dp_prev = [0] * n
dp_prev[0] = mat[0][0]
for j in range(1, n):
dp_prev[j] = dp_prev[j-1] + mat[0][j]
for i in range(1, m):
current_dp = [0] ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer matrix `mat`, where `mat[i][j]` represents the cost of moving through cell `(i, j)`, find the minimum path sum from the top-left corner to the bottom-right corner. You can only move either down or right at any point in time. Return the minimum path sum.\nAnswer:\nLet's ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6213,
"level": 1,
"question": "Given an integer matrix `mat`, where `mat[i][j]` represents the cost of moving through cell `(i, j)`, find the minimum path sum from the top-left corner to the bottom-right corner. You can only move either down or right at any point in time. Return the... |
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return None | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers `nums`, and an integer `target`, and returns the indices of the two numbers such that they add up to `target`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6214,
"level": 1,
"question": "Create a function that takes an array of integers `nums`, and an integer `target`, and returns the indices of the two numbers such that they add up to `target`.",
"split": "train"
} |
def search_in_sorted_matrix(matrix, key):
if not matrix or not matrix[0]:
return (-1, -1)
rows = len(matrix)
cols = len(matrix[0])
row = 0
col = cols - 1
while row < rows and col >= 0:
current = matrix[row][col]
if current == key:
return (row, col)
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are developing an application that handles large datasets sorted in a two-dimensional grid. Each row and each column of the grid are sorted in non-decreasing order. One common operation is to search for particular elements within this grid. Implement an efficient funct... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6215,
"level": 1,
"question": "### Scenario\nYou are developing an application that handles large datasets sorted in a two-dimensional grid. Each row and each column of the grid are sorted in non-decreasing order. One common operation is to search for particular elements within this... |
def reverse_if_contains_vowel(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
if any(c.lower() in vowels for c in s):
return s[::-1]
return s | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns the reversed string, but only for strings that contain at least one vowel. If the string does not contain any vowels, return the original string. For example, \"hello\" would become \"olleh\", but \"bcdfg\" would remain \"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6216,
"level": 1,
"question": "Write a Python function that takes a string as input and returns the reversed string, but only for strings that contain at least one vowel. If the string does not contain any vowels, return the original string. For example, \"hello\" would become \"oll... |
def rotate_matrix_90_clockwise(matrix):
if not matrix:
return []
m = len(matrix)
n = len(matrix[0])
# Transpose the matrix
matrix[:] = list(map(list, zip(*matrix)))
# Now matrix is transposed; its dimensions are n x m
# Reverse each row to complete the rotation
for... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a matrix of integers of size `m x n`, rotate the matrix 90 degrees clockwise in place. You need to modify the matrix directly without using extra space. Return the modified matrix.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6217,
"level": 1,
"question": "Given a matrix of integers of size `m x n`, rotate the matrix 90 degrees clockwise in place. You need to modify the matrix directly without using extra space. Return the modified matrix.",
"split": "train"
} |
def count_substring_occurrences(text: str, pattern: str) -> int:
if len(pattern) == 0 or len(pattern) > len(text):
return 0
pattern_length = len(pattern)
count = 0
for i in range(len(text) - pattern_length + 1):
if text[i:i + pattern_length] == pattern:
count += 1
return ... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Context\nWorking with strings in programming often involves the need to identify patterns or counts of specific subpatterns. One interesting problem is to compute the frequency of a specific substring within a larger text. This could be useful for various text analysis tasks... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6218,
"level": 1,
"question": "### Problem Context\nWorking with strings in programming often involves the need to identify patterns or counts of specific subpatterns. One interesting problem is to compute the frequency of a specific substring within a larger text. This could be use... |
from collections import Counter
def can_form_palindrome(s):
digits = [c for c in s if c.isdigit()]
counts = Counter(digits)
odd_count = sum(1 for cnt in counts.values() if cnt % 2 != 0)
return "YES" if odd_count <= 1 else "NO"
| simplelr_Taco | [
{
"content": "Question:\nYou are given a string representing a long-integer number. Your task is to create a function that determines if the number can be rearranged into a palindrome. If it can, return `\"YES\"`, otherwise return `\"NO\"`.\n\nFor example, given the input string:\n```\ns = \"123321\"\n```\n\nTh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6219,
"level": 1,
"question": "You are given a string representing a long-integer number. Your task is to create a function that determines if the number can be rearranged into a palindrome. If it can, return `\"YES\"`, otherwise return `\"NO\"`.\n\nFor example, given the input stri... |
def min_moves(arr: list[int]) -> int:
arr_sorted = sorted(arr)
n = len(arr_sorted)
mid = n // 2
median = arr_sorted[mid]
total = 0
for num in arr_sorted:
total += abs(num - median)
return total | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers, find the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1.\n\nFor example:\n```python\nmin_moves([1,2,3]) = 2\n```\nExplanation: Only two moves are needed (each 2 can b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6220,
"level": 1,
"question": "Given an array of integers, find the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1.\n\nFor example:\n```python\nmin_moves([1,2,3]) = 2\n```\nExplanation: Only... |
def remove_duplicates(strings):
seen = set()
result = []
for string in strings:
if string not in seen:
seen.add(string)
result.append(string)
return result | simplelr_Filter | [
{
"content": "Question:\nDesign an algorithm in Python that takes a list of strings and returns the list with all duplicate strings removed.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6221,
"level": 1,
"question": "Design an algorithm in Python that takes a list of strings and returns the list with all duplicate strings removed.",
"split": "train"
} |
import numpy as np
def element_wise_max(arr1, arr2):
if arr1.shape != arr2.shape:
raise ValueError("Input arrays must have the same shape.")
return np.where(arr1 > arr2, arr1, arr2) | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function to perform an element-wise maximum operation between two 2D NumPy arrays. Instead of using the `np.max()` function which provides the maximum values across an axis, your function should return a new 2D array where each element is the maximum value of the corresp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6222,
"level": 1,
"question": "Design a Python function to perform an element-wise maximum operation between two 2D NumPy arrays. Instead of using the `np.max()` function which provides the maximum values across an axis, your function should return a new 2D array where each element ... |
def check_pair_sum(nums: list, k: int) -> bool:
if len(nums) < 2:
return False
seen = set()
for x in nums:
if (k - x) in seen:
return True
seen.add(x)
return False | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of Two Numbers as k\n\nYou are tasked with developing a function that checks if any pair of numbers from the list can be added up to match a given target sum k.\n\n## Problem Statement\n\nImplement a function `check_pair_sum(nums: list, k: int) -> bool` that determines if there ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6223,
"level": 1,
"question": "### Sum of Two Numbers as k\n\nYou are tasked with developing a function that checks if any pair of numbers from the list can be added up to match a given target sum k.\n\n## Problem Statement\n\nImplement a function `check_pair_sum(nums: list, k: int)... |
def find_unique_numbers(nums):
freq = {}
for num in nums:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
result = []
for num in nums:
if freq[num] == 1:
result.append(num)
return result | simplelr_Evol | [
{
"content": "Question:\nGiven a list of integers, write a function `find_unique_numbers(nums)` that returns a list containing only the elements that appear exactly once in the input list. The order of the returned elements should be the same as their order of appearance in the input list.\n\n### Input\n- A lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6224,
"level": 1,
"question": "Given a list of integers, write a function `find_unique_numbers(nums)` that returns a list containing only the elements that appear exactly once in the input list. The order of the returned elements should be the same as their order of appearance in th... |
def find_added_character(s: str, t: str) -> str:
sum_s = sum(ord(c) for c in s)
sum_t = sum(ord(c) for c in t)
added_char = sum_t - sum_s
return chr(added_char) | simplelr_Data_Structure | [
{
"content": "Question:\nFind the Added Character\n\n#### Problem Statement\nGiven two strings `s` and `t` which consist of only lowercase letters, string `t` is generated by random shuffling string `s` and then adding one more letter at a random position. Your task is to find the letter that was added to `t`.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6225,
"level": 1,
"question": "Find the Added Character\n\n#### Problem Statement\nGiven two strings `s` and `t` which consist of only lowercase letters, string `t` is generated by random shuffling string `s` and then adding one more letter at a random position. Your task is to find... |
def is_integer(x):
return type(x) is int | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to check if the input is an integer. How should you do it?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6226,
"level": 1,
"question": "Write a python function to check if the input is an integer. How should you do it?",
"split": "train"
} |
def sorted_keys_by_values(dic):
sorted_items = sorted(dic.items(), key=lambda x: (-x[1], x[0]))
return [k for k, v in sorted_items] | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a dictionary where the keys are strings and the values are integers. Your task is to sort the dictionary by its values in descending order and return a list of keys corresponding to the sorted values.\n\nWrite a function `sorted_keys_by_values` that takes a dictionary as i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6227,
"level": 1,
"question": "You are given a dictionary where the keys are strings and the values are integers. Your task is to sort the dictionary by its values in descending order and return a list of keys corresponding to the sorted values.\n\nWrite a function `sorted_keys_by_v... |
from typing import List
def generate_screen_sequence(n: int) -> List[str]:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
return [alphabet[:i] for i in range(1, n+1)] | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context\nIn a series of computer screens connected together, each screen displays a sequence of alphabets where each screen's sequence must be incrementally longer than the previous one. This problem involves arranging the alphabets in such a way t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6228,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context\nIn a series of computer screens connected together, each screen displays a sequence of alphabets where each screen's sequence must be incrementally longer than the previous one. This problem involves arra... |
def longest_beautiful_subsequence(nums, k):
nums.sort()
n = len(nums)
if n == 0:
return 0
low = 1
high = n
res = 1
while low <= high:
mid = (low + high) // 2
found = False
# Check all possible windows of size mid
for i in range(n - mid + 1):
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums`. A subsequence of `nums` is a sequence that can be derived from `nums` by deleting some or no elements without changing the order of the remaining elements. A subsequence is called **beautiful** if it is possible to reorder its elements such that th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6229,
"level": 1,
"question": "You are given an integer array `nums`. A subsequence of `nums` is a sequence that can be derived from `nums` by deleting some or no elements without changing the order of the remaining elements. A subsequence is called **beautiful** if it is possible t... |
import pandas as pd
def transform_sales_data(df):
# Create a copy to avoid modifying the original DataFrame
df = df.copy()
# Handle missing values in Quantity and Price by treating them as zero
df[['Quantity', 'Price']] = df[['Quantity', 'Price']].fillna(0)
# Convert 'Date' column to date... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function using the `pandas` library to manipulate a DataFrame based on given conditions. The function will take a DataFrame with specific columns and perform a series of transformations. \n\n### Problem Statement\nSuppose you have a DataFrame that contains sa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6230,
"level": 1,
"question": "You are required to write a function using the `pandas` library to manipulate a DataFrame based on given conditions. The function will take a DataFrame with specific columns and perform a series of transformations. \n\n### Problem Statement\nSuppose yo... |
def find_smallest_missing_positive(arr):
m = len(arr)
for i in range(m):
while True:
current = arr[i]
if current < 1 or current > m:
break
target = current - 1
if arr[target] == current:
break
arr[i], arr[target]... | simplelr_Apps | [
{
"content": "Question:\nWrite a function to find the smallest positive integer that is missing from an array of integers. The input array can contain both positive and negative integers, and the function should find the smallest positive integer that does not appear in the array. The function should return thi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6231,
"level": 1,
"question": "Write a function to find the smallest positive integer that is missing from an array of integers. The input array can contain both positive and negative integers, and the function should find the smallest positive integer that does not appear in the ar... |
def custom_sort(arr):
"""
Sort an array of integers in ascending order using bubble sort.
Args:
arr (list): List of integers to be sorted.
Returns:
list: A new list with the integers in ascending order.
"""
# Create a copy of the input array to avoid modifying the origi... | simplelr_Package | [
{
"content": "Question:\nCreate a function in Python that takes a list of integers and returns a new list with the same integers, but sorted in ascending order, without using any built-in sorting functions (such as `sorted()` or `.sort()`). The function should implement a sorting algorithm of your choice (e.g.,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6232,
"level": 1,
"question": "Create a function in Python that takes a list of integers and returns a new list with the same integers, but sorted in ascending order, without using any built-in sorting functions (such as `sorted()` or `.sort()`). The function should implement a sort... |
def max_items(prices, budget):
sorted_prices = sorted(prices)
total = 0
count = 0
for p in sorted_prices:
if total + p > budget:
break
total += p
count += 1
return count | simplelr_Codeforces | [
{
"content": "Question:\nYou are given an array of integers representing the prices of different items in a store, and you have a budget. Your task is to find the maximum number of items you can purchase without exceeding the budget.\n\nWrite a function `max_items(prices, budget)` that takes in two arguments:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6233,
"level": 1,
"question": "You are given an array of integers representing the prices of different items in a store, and you have a budget. Your task is to find the maximum number of items you can purchase without exceeding the budget.\n\nWrite a function `max_items(prices, budg... |
def second_largest(numbers):
if len(numbers) < 2:
return None
unique = list(set(numbers))
if len(unique) < 2:
return None
unique_sorted = sorted(unique, reverse=True)
return unique_sorted[1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the second largest number in a list. If the list has less than two elements or all elements are the same, return None.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6234,
"level": 1,
"question": "Write a python function to find the second largest number in a list. If the list has less than two elements or all elements are the same, return None.",
"split": "train"
} |
import hashlib
def string_to_sha256(input_string):
# Create a sha256 hash object
sha_signature = hashlib.sha256()
# Update the hash object with the encoded bytes of the input string
sha_signature.update(input_string.encode('utf-8'))
# Return the hexadecimal representation of the hash
return sha... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code snippet to convert a string to its SHA-256 hash?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6235,
"level": 1,
"question": "Can you provide a Python code snippet to convert a string to its SHA-256 hash?",
"split": "train"
} |
def max_activities_within_slot(start, end, time, duration):
slot_end = time + duration
count = 0
for s, e in zip(start, end):
if s >= time and e <= slot_end:
count += 1
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `n` activities where each activity has a start time and an end time represented by two **0-indexed** integer arrays `start` and `end` respectively. An activity `i` starts at `start[i]` and ends at `end[i]`. You have a single slot of time starting from `time` of d... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6236,
"level": 1,
"question": "You are given a list of `n` activities where each activity has a start time and an end time represented by two **0-indexed** integer arrays `start` and `end` respectively. An activity `i` starts at `start[i]` and ends at `end[i]`. You have a single slo... |
import unicodedata
def count_japanese_scripts(text):
counts = {'hiragana': 0, 'katakana': 0, 'kanji': 0}
for char in text:
try:
name = unicodedata.name(char)
if 'HIRAGANA' in name:
counts['hiragana'] += 1
elif 'KATAKANA' in name:
count... | simplelr_Filter | [
{
"content": "Question:\nIn the Japanese language, there are three types of scripts: Hiragana, Katakana, and Kanji. \nGiven a string of Hiragana, Katakana, and Kanji characters, write a Python function to count the number of each character type.\n\nHere is a sample string: \n\n\"\"\n\nThe function should return... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6237,
"level": 1,
"question": "In the Japanese language, there are three types of scripts: Hiragana, Katakana, and Kanji. \nGiven a string of Hiragana, Katakana, and Kanji characters, write a Python function to count the number of each character type.\n\nHere is a sample string: \n\... |
def is_sorted_and_unique(lst):
if len(lst) <= 1:
return True
for i in range(len(lst) - 1):
if lst[i] >= lst[i + 1]:
return False
return len(lst) == len(set(lst))
# Test cases
assert is_sorted_and_unique([]) == True
assert is_sorted_and_unique([5]) == True
assert is_sorted_and_un... | simplelr_Filter | [
{
"content": "Question:\nIs there a way to write a Python function that checks if a given list is sorted in ascending order and all elements are unique? And could you provide a way to test this function with a series of assert statements to ensure it works correctly?\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6238,
"level": 1,
"question": "Is there a way to write a Python function that checks if a given list is sorted in ascending order and all elements are unique? And could you provide a way to test this function with a series of assert statements to ensure it works correctly?",
"spli... |
def minDeletionsToPalindrome(s: str) -> int:
s_reversed = s[::-1]
n = len(s)
# Initialize a DP table with (n+1) rows and columns, filled with 0s.
dp = [[0] * (n + 1) for _ in range(n + 1)]
# Fill the DP table
for i in range(1, n + 1):
for j in range(1, n + 1):
if s[i-1] ... | simplelr_Taco | [
{
"content": "Question:\nGiven a string $s$ consisting of lower case English letters, the goal is to determine the minimum number of deletions required to make the string a palindrome. A palindrome is a string that reads the same forwards and backwards. \n\nYou need to implement the function `minDeletionsToPali... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6239,
"level": 1,
"question": "Given a string $s$ consisting of lower case English letters, the goal is to determine the minimum number of deletions required to make the string a palindrome. A palindrome is a string that reads the same forwards and backwards. \n\nYou need to impleme... |
def add_item(lst, item, flag):
if flag:
return [item] + lst
else:
return lst + [item] | simplelr_Filter | [
{
"content": "Question:\nCreate a function that takes a list, an item, and a boolean flag as arguments. If the flag is true, it should add the item to the beginning of the list. If the flag is false, it should add the item to the end of the list. For this exercise, do not use built-in Python methods like `.appe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6240,
"level": 1,
"question": "Create a function that takes a list, an item, and a boolean flag as arguments. If the flag is true, it should add the item to the beginning of the list. If the flag is false, it should add the item to the end of the list. For this exercise, do not use ... |
def enhanced_binary_search(array, target):
"""
Performs a binary search to find the index of target in the sorted array.
Parameters:
array (list): A sorted list of integers.
target (int): The target value to search for.
Returns:
int: The index of target if present; otherwise, -1.
"""
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Binary Search Task\nYou are provided with a sorted array of integers. Implement a function `enhanced_binary_search` that takes the array and a target value as input and returns the index of the target value if it is present in the array. If it is not present, your function should re... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6241,
"level": 1,
"question": "### Binary Search Task\nYou are provided with a sorted array of integers. Implement a function `enhanced_binary_search` that takes the array and a target value as input and returns the index of the target value if it is present in the array. If it is n... |
def tag_based_on_element_presence(data, element, tag):
"""
Adds/removes a tag from keys in a dictionary based on the presence/absence of an element in the corresponding value lists.
Args:
data (dict): The dictionary where keys are strings and values are lists.
element: The element to check ... | simplelr_Filter | [
{
"content": "Question:\nThe problem I'd like to solve:\n\nI have a dictionary where keys are strings and values are lists.\n\nI want to\n\n1. Iterate through all the values (lists) in the dictionary.\n2. Check if a specific element is present in each of the lists.\n3. Based on the presence or absence of the el... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6242,
"level": 1,
"question": "The problem I'd like to solve:\n\nI have a dictionary where keys are strings and values are lists.\n\nI want to\n\n1. Iterate through all the values (lists) in the dictionary.\n2. Check if a specific element is present in each of the lists.\n3. Based o... |
from PIL import Image
import numpy as np
def convert_to_grayscale(image_path: str, output_path: str, method: str = "average") -> None:
allowed_methods = ["average", "luminosity", "lightness"]
if method not in allowed_methods:
raise ValueError(f"Invalid method: {method}. Must be one of {allowed_methods}... | simplelr_Package | [
{
"content": "Question:\n**Image Processing: Grayscale Transformation**\n\nIn this problem, you are tasked with writing a function called `convert_to_grayscale` that takes an image file as input and converts it to a grayscale image using the `Pillow` library. This exercise will test your ability to handle image... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6243,
"level": 1,
"question": "**Image Processing: Grayscale Transformation**\n\nIn this problem, you are tasked with writing a function called `convert_to_grayscale` that takes an image file as input and converts it to a grayscale image using the `Pillow` library. This exercise wil... |
def binary_exponentiation(base: int, exp: int, mod: int = None) -> int:
"""
Calculate base ^ exp using binary exponentiation.
If mod is provided, return the result modulo mod.
:param base: The base number (an integer)
:param exp: The exponent (a non-negative integer)
:param mod: An optional... | simplelr_Data_Structure | [
{
"content": "Question:\n### Binary Exponentiation Challenge\n\n#### Context:\nIn many computational problems, particularly those involving large numbers, efficient computation of powers is crucial. Binary exponentiation is one such method that speeds up the process significantly compared to the naive approach.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6244,
"level": 1,
"question": "### Binary Exponentiation Challenge\n\n#### Context:\nIn many computational problems, particularly those involving large numbers, efficient computation of powers is crucial. Binary exponentiation is one such method that speeds up the process significan... |
def find_max(array):
if len(array) == 0:
return None
current_max = array[0]
for number in array[1:]:
if number > current_max:
current_max = number
return current_max
# Example usage:
numbers = [2, 3, 5, 1, 8, 9]
print(find_max(numbers)) # Output: 9 | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the maximum value in an array of integers `[2, 3, 5, 1, 8, 9]`. The function should iteratively solve the problem and not use any built-in functions like `max()`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6245,
"level": 1,
"question": "Write a function to find the maximum value in an array of integers `[2, 3, 5, 1, 8, 9]`. The function should iteratively solve the problem and not use any built-in functions like `max()`.",
"split": "train"
} |
def count_tabs(s):
"""
Calculate the number of tab characters in a given string.
Args:
s (str): The input string to be analyzed.
Returns:
int: The number of tab characters in the string.
"""
return s.count('\t') | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the number of tabs in a given string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6246,
"level": 1,
"question": "Write a function to calculate the number of tabs in a given string.",
"split": "train"
} |
def sort_list(input_list):
"""
This function takes a list of integers as input, sorts it in ascending order, and returns the sorted list.
Args:
input_list (list): A list of integers.
Returns:
list: A new sorted list in ascending order.
"""
# Create a copy of the input l... | simplelr_Filter | [
{
"content": "Question:\nAssume I have a list named 'x' that has the following data: [9, 5, 2, 6, 3]. I want to sort this list and print all the numbers in ascending order. Can you write a simple python script to solve this problem? Additionally, can you encapsulate this functionality in a function that accepts... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6247,
"level": 1,
"question": "Assume I have a list named 'x' that has the following data: [9, 5, 2, 6, 3]. I want to sort this list and print all the numbers in ascending order. Can you write a simple python script to solve this problem? Additionally, can you encapsulate this funct... |
def fibonacci_up_to_n(n):
if n < 0:
return []
fib_list = []
if n >= 0:
fib_list.append(0)
if n >= 1:
fib_list.append(1)
prev, curr = 0, 1
while True:
next_num = prev + curr
if next_num > n:
break
fib_list.append(next_num)
prev, ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to generate a list of Fibonacci numbers up to a given number `n`. The function should take an integer `n` as input and return a list of Fibonacci numbers that are less than or equal to `n`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6248,
"level": 1,
"question": "Write a function to generate a list of Fibonacci numbers up to a given number `n`. The function should take an integer `n` as input and return a list of Fibonacci numbers that are less than or equal to `n`.",
"split": "train"
} |
def isAnagramPair(str1, str2):
# Process each string to include only lowercase letters
s1 = [c.lower() for c in str1 if c.isalpha()]
s2 = [c.lower() for c in str2 if c.isalpha()]
# Compare the sorted lists of characters
return sorted(s1) == sorted(s2) | simplelr_Apps | [
{
"content": "Question:\nYour task is to implement the function **isAnagramPair** which takes two strings, **str1** and **str2**. The function should return **True** if the two strings are anagrams of each other, and **False** otherwise.\n\n### Considerations:\n- Ignore case differences (e.g., \"Listen\" and \"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6249,
"level": 1,
"question": "Your task is to implement the function **isAnagramPair** which takes two strings, **str1** and **str2**. The function should return **True** if the two strings are anagrams of each other, and **False** otherwise.\n\n### Considerations:\n- Ignore case d... |
import math
from typing import List, Union
def cholesky_decomposition(A: List[List[float]]) -> Union[List[List[float]], None]:
n = len(A)
for row in A:
if len(row) != n:
return None
# Check if A is symmetric
for i in range(n):
for j in range(n):
if abs(A[i][... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a square Hermitian positive-definite matrix `A`. Your task is to write a function `cholesky_decomposition(A)` that performs Cholesky decomposition on matrix `A` and returns the lower triangular matrix `V` such that \\(V \\cdot V^* = A\\).\n\n### Function Signature\n```pyth... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6250,
"level": 1,
"question": "You are given a square Hermitian positive-definite matrix `A`. Your task is to write a function `cholesky_decomposition(A)` that performs Cholesky decomposition on matrix `A` and returns the lower triangular matrix `V` such that \\(V \\cdot V^* = A\\).... |
def remove_duplicates(lst):
seen = set()
return [x for x in lst if x not in seen and not seen.add(x)] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove duplicates from a list of integers while maintaining the original order of the list. How can I accomplish this using list comprehension? Additionally, how can I ensure the solution is efficient?\nAnswer:\nLet's think step by step.\n",
"role": "user"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6251,
"level": 1,
"question": "Write a python function to remove duplicates from a list of integers while maintaining the original order of the list. How can I accomplish this using list comprehension? Additionally, how can I ensure the solution is efficient?",
"split": "train"
} |
import seaborn as sns
import matplotlib.pyplot as plt
def generate_health_exp_plot():
# Load the healthexp dataset
health_df = sns.load_dataset('healthexp')
# Create a dictionary of 1970 spending for each country
base_values = health_df[health_df['Year'] == 1970].set_index('Country')['Spending_USD... | simplelr_Docs | [
{
"content": "Question:\nYou are provided with a dataset containing information on health expenditures of various countries over several years. The dataset is loaded using `seaborn.load_dataset`. Your task is to generate a plot using seaborn that demonstrates your understanding of normalization and labeling usi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6252,
"level": 1,
"question": "You are provided with a dataset containing information on health expenditures of various countries over several years. The dataset is loaded using `seaborn.load_dataset`. Your task is to generate a plot using seaborn that demonstrates your understandin... |
import pandas as pd
def daily_temperature_fluctuations(data: pd.DataFrame) -> pd.DataFrame:
# Ensure the 'date' column is of datetime type
data['date'] = pd.to_datetime(data['date'])
# Group by 'date' and calculate max and min temperatures
agged = data.groupby('date')['temperature'].agg(['max', 'm... | simplelr_Package | [
{
"content": "Question:\nWrite a function named `daily_temperature_fluctuations` that takes a single argument `data`, which is a pandas DataFrame. The DataFrame contains daily temperature records with columns ['date', 'temperature']. The objective of the function is to calculate the daily temperature difference... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6253,
"level": 1,
"question": "Write a function named `daily_temperature_fluctuations` that takes a single argument `data`, which is a pandas DataFrame. The DataFrame contains daily temperature records with columns ['date', 'temperature']. The objective of the function is to calcula... |
from collections import defaultdict
def count_documents(documents):
field_counts = defaultdict(int)
for document in documents:
for key in document:
field_counts[key] += 1
return dict(field_counts) | simplelr_Filter | [
{
"content": "Question:\nYou've been tasked with writing a function `count_documents`: This function takes in a list of documents where each document is represented as a dictionary. The keys of the dictionary are the fields in the document and the values are the corresponding field values. The function should r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6254,
"level": 1,
"question": "You've been tasked with writing a function `count_documents`: This function takes in a list of documents where each document is represented as a dictionary. The keys of the dictionary are the fields in the document and the values are the corresponding ... |
from typing import List
def binary_search(nums: List[int], target: int) -> int:
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif target < nums[mid]:
high = mid - 1
else:
low = ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Objective\nImplement a function to find the index of a target element in a sorted array using binary search.\n\n### Problem Statement\nYou are given a sorted (in non-decreasing order) integer array `nums` and an integer `target`. Implement the function `binary_search(nums: List[int]... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6255,
"level": 1,
"question": "### Objective\nImplement a function to find the index of a target element in a sorted array using binary search.\n\n### Problem Statement\nYou are given a sorted (in non-decreasing order) integer array `nums` and an integer `target`. Implement the func... |
from typing import List
def calculate_subarray_averages(data: List[int], k: int) -> List[float]:
n = len(data)
if k <= 0 or k > n:
return []
current_sum = sum(data[:k])
averages = [current_sum / k]
for i in range(1, n - k + 1):
current_sum = current_sum - data[i - 1] + data[i + k - ... | simplelr_Evol | [
{
"content": "Question:\nIn the context of data analysis, where sequences of numeric data points are periodically recorded, design an algorithm to calculate the average of every contiguous subarray of a specified length within a larger array of integers. For example, given an array of integers:\ndata = [1, 3, 4... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6256,
"level": 1,
"question": "In the context of data analysis, where sequences of numeric data points are periodically recorded, design an algorithm to calculate the average of every contiguous subarray of a specified length within a larger array of integers. For example, given an ... |
def list_processing(strings: list) -> list:
return sorted(s.upper() for s in strings if len(s) >= 5) | simplelr_Package | [
{
"content": "Question:\nThe task is to practice list manipulations and basic string operations. You need to write a function named `list_processing()`, which will perform the following operations:\n\n1. Accept a list of strings as input.\n2. Filter out strings that are less than 5 characters long.\n3. Convert ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6257,
"level": 1,
"question": "The task is to practice list manipulations and basic string operations. You need to write a function named `list_processing()`, which will perform the following operations:\n\n1. Accept a list of strings as input.\n2. Filter out strings that are less t... |
import math
def sum_of_positive_divisors(n):
if n <= 0:
return 0
total = 0
sqrt_n = int(math.sqrt(n))
for i in range(1, sqrt_n + 1):
if n % i == 0:
j = n // i
if i == j:
total += i
else:
total += i + j
return total | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the sum of all positive divisors of a given number. A positive divisor of a number is an integer that divides that number without leaving a remainder.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6258,
"level": 1,
"question": "Write a python function to calculate the sum of all positive divisors of a given number. A positive divisor of a number is an integer that divides that number without leaving a remainder.",
"split": "train"
} |
def trap(height):
n = len(height)
if n < 3:
return 0
max_left = [0] * n
max_right = [0] * n
max_so_far = 0
for i in range(n):
max_left[i] = max_so_far
if height[i] > max_so_far:
max_so_far = height[i]
max_so_far = 0
for i in range(n - 1,... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of non-negative integers representing the amount of rainfall recorded at regular intervals. Write a function to determine the maximum amount of water that can be trapped between these intervals after it rains. The array represents the elevation map where the width o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6259,
"level": 1,
"question": "You are given a list of non-negative integers representing the amount of rainfall recorded at regular intervals. Write a function to determine the maximum amount of water that can be trapped between these intervals after it rains. The array represents ... |
def next_bigger(num: int) -> int:
digits = list(map(int, str(num)))
i = len(digits) - 2
# Find the first digit from the end that is smaller than the next digit
while i >= 0 and digits[i] >= digits[i + 1]:
i -= 1
if i == -1:
return -1
# Find the smallest digit larger than digit... | simplelr_Data_Structure | [
{
"content": "Question:\nGiven a number, write a function `next_bigger(num: int) -> int` to find the next higher number using the exact same set of digits as the original number. If no such number exists, return -1.\n\n#### Input\n- A single integer `num` where `1 <= num <= 10^9`.\n\n#### Output\n- An integer r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6260,
"level": 1,
"question": "Given a number, write a function `next_bigger(num: int) -> int` to find the next higher number using the exact same set of digits as the original number. If no such number exists, return -1.\n\n#### Input\n- A single integer `num` where `1 <= num <= 10... |
from collections import defaultdict
def find_min_lex_subsequence(s):
n = len(s)
if n == 0:
return ""
# Precompute the positions for each character
pos_dict = defaultdict(list)
for idx, c in enumerate(s):
pos_dict[c].append(idx)
# Precompute the set of characters presen... | simplelr_Taco | [
{
"content": "Question:\nSammy has a sequence of letters $s$ which consists of lowercase English letters only. He wants to find the lexicographically smallest subsequence of $s$ that contains all the distinct characters present in $s$. \n\nA subsequence is a sequence that can be derived from another sequence by... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6261,
"level": 1,
"question": "Sammy has a sequence of letters $s$ which consists of lowercase English letters only. He wants to find the lexicographically smallest subsequence of $s$ that contains all the distinct characters present in $s$. \n\nA subsequence is a sequence that can ... |
def findLengthOfLCIS(nums):
if not nums:
return 0
max_length = 1
current_length = 1
for i in range(1, len(nums)):
if nums[i] > nums[i-1]:
current_length += 1
else:
current_length = 1
if current_length > max_length:
max_length = current_... | simplelr_Filter | [
{
"content": "Question:\nThis is a problem from an online coding challenge platform:\n\n**Problem statement:**\n\nYou are given an array of integers `nums`. You need to find the length of the longest continuous increasing subarray.\n\n\n**Example:**\n\n```\nInput: nums = [1,3,5,4,7]\nOutput: 3\nExplanation: The... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6262,
"level": 1,
"question": "This is a problem from an online coding challenge platform:\n\n**Problem statement:**\n\nYou are given an array of integers `nums`. You need to find the length of the longest continuous increasing subarray.\n\n\n**Example:**\n\n```\nInput: nums = [1,3,... |
def intersect(nums1, nums2):
# Create a frequency dictionary for nums2
count = {}
for num in nums2:
if num in count:
count[num] += 1
else:
count[num] = 1
result = []
for num in nums1:
if num in count and count[num] > 0:
result.append(n... | simplelr_Filter | [
{
"content": "Question:\ndef intersect(nums1, nums2):\n return [num for num in nums1 if num in nums2]\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6263,
"level": 1,
"question": "def intersect(nums1, nums2):\n return [num for num in nums1 if num in nums2]",
"split": "train"
} |
def is_binary_palindrome(n: int) -> bool:
bin_str = bin(n)[2:] # Convert to binary and remove the '0b' prefix
left = 0
right = len(bin_str) - 1
while left < right:
if bin_str[left] != bin_str[right]:
return False
left += 1
right -= 1
return True | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function `is_binary_palindrome` that checks if the binary representation of a given positive integer is a palindrome. The function should take an integer as input and return `True` if its binary representation is a palindrome, and `False` otherwise. A palindrome is a sequence th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6264,
"level": 1,
"question": "Write a function `is_binary_palindrome` that checks if the binary representation of a given positive integer is a palindrome. The function should take an integer as input and return `True` if its binary representation is a palindrome, and `False` other... |
import re
def transform_print_statements(code: str) -> str:
lines = code.split('\n')
transformed_lines = []
for line in lines:
# Split the line into code and comment parts
if '#' in line:
code_part, _, comment_part = line.partition('#')
else:
code_part, comme... | simplelr_Docs | [
{
"content": "Question:\n### Python 2 to 3 Code Transformer\n\nWrite a Python function that performs a specific transformation on Python 2.x code to convert it to Python 3.x code. Your task is to implement a simple fixer that converts Python 2-style `print` statements to Python 3-style `print` function calls.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6265,
"level": 1,
"question": "### Python 2 to 3 Code Transformer\n\nWrite a Python function that performs a specific transformation on Python 2.x code to convert it to Python 3.x code. Your task is to implement a simple fixer that converts Python 2-style `print` statements to Pytho... |
def hello_world():
print("Hello, World!") | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that implements the classic \"Hello, World!\" program in Python. Ensure the function prints \"Hello, World!\" to the console.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6266,
"level": 1,
"question": "Create a function that implements the classic \"Hello, World!\" program in Python. Ensure the function prints \"Hello, World!\" to the console.",
"split": "train"
} |
def removeDuplicates(nums):
if not nums:
return 0
i = 1
for j in range(1, len(nums)):
if nums[j] != nums[j - 1]:
nums[i] = nums[j]
i += 1
# Truncate the array to the new length
nums[:] = nums[:i]
return i
# Test cases
print(removeDuplicates([1,1... | simplelr_Filter | [
{
"content": "Question:\n### Remove Duplicates from Sorted Array\n#### Problem Statement\nGiven a sorted array `nums`, remove the duplicates in-place such that each element appear only once and return the new length.\nDo not allocate extra space for another array, you must do this by **modifying the input array... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6267,
"level": 1,
"question": "### Remove Duplicates from Sorted Array\n#### Problem Statement\nGiven a sorted array `nums`, remove the duplicates in-place such that each element appear only once and return the new length.\nDo not allocate extra space for another array, you must do ... |
from typing import List
def maxProfit(prices: List[int]) -> int:
if not prices or len(prices) < 2:
return 0
max_profit = 0
min_price = prices[0]
for price in prices[1:]:
current_profit = price - min_price
if current_profit > max_profit:
max_profit = current_profit
... | simplelr_Apps | [
{
"content": "Question:\nYou are given an array of integers where each element represents the price of a stock on that particular day.\n\nYou are only allowed to complete at most one transaction (i.e., buy one and sell one share of the stock), but you cannot sell a stock before you buy one. Your task is to dete... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6268,
"level": 1,
"question": "You are given an array of integers where each element represents the price of a stock on that particular day.\n\nYou are only allowed to complete at most one transaction (i.e., buy one and sell one share of the stock), but you cannot sell a stock befor... |
def count_uppercase_letters(strings):
return [sum(1 for c in s if c.isupper()) for s in strings] | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a list of strings as input and returns a new list containing the number of uppercase letters in each string from the input list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6269,
"level": 1,
"question": "Create a Python function that takes a list of strings as input and returns a new list containing the number of uppercase letters in each string from the input list.",
"split": "train"
} |
def rearrange(arr):
i = 0
n = len(arr)
for j in range(n):
if arr[j] < 0:
arr[i], arr[j] = arr[j], arr[i]
i += 1
return arr
| simplelr_Taco | [
{
"content": "Question:\n## Task\nGiven an array of integers, rearrange the elements in such a way that all the negative numbers appear before all the positive numbers, without using any extra space. The order of appearance of elements within the same group (negative or positive) does not matter.\n\n### Input/O... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6270,
"level": 1,
"question": "## Task\nGiven an array of integers, rearrange the elements in such a way that all the negative numbers appear before all the positive numbers, without using any extra space. The order of appearance of elements within the same group (negative or positi... |
import cmath
def find_roots(a, b, c):
if a == 0:
raise ValueError("The equation is not quadratic.")
discriminant = b**2 - 4 * a * c
sqrt_discriminant = cmath.sqrt(discriminant)
root1 = (-b + sqrt_discriminant) / (2 * a)
root2 = (-b - sqrt_discriminant) / (2 * a)
return root1, root2 | simplelr_Filter | [
{
"content": "Question:\nI need to create a Python function that can find the roots of a given quadratic equation. How can I write a function that takes the coefficients of a quadratic equation (a, b, c) as inputs and returns the solutions? The equation is in the form of ax^2 + bx + c = 0.\nAnswer:\nLet's think... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6271,
"level": 1,
"question": "I need to create a Python function that can find the roots of a given quadratic equation. How can I write a function that takes the coefficients of a quadratic equation (a, b, c) as inputs and returns the solutions? The equation is in the form of ax^2 ... |
import math
def find_next_perfect_square(num):
n = math.isqrt(num)
if n * n == num:
return (n + 1) ** 2
else:
return -1 | simplelr_Data_Structure | [
{
"content": "Question:\n**Perfect Square and Next Perfect Square**\n\n### Problem Scenario\nYou're developing a game where certain levels require identification of perfect squares and progression to the next highest perfect square. To achieve this, you need a function that can determine if a given positive int... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6272,
"level": 1,
"question": "**Perfect Square and Next Perfect Square**\n\n### Problem Scenario\nYou're developing a game where certain levels require identification of perfect squares and progression to the next highest perfect square. To achieve this, you need a function that ca... |
def second_largest(nums):
if len(nums) < 2:
return None
max_num = max(nums)
new_list = [num for num in nums if num != max_num]
if not new_list:
return None
return max(new_list) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the second largest number in a list. If there is no distinct second largest number, return None. Ensure your function works for both positive and negative numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6273,
"level": 1,
"question": "Write a function to find the second largest number in a list. If there is no distinct second largest number, return None. Ensure your function works for both positive and negative numbers.",
"split": "train"
} |
def sum_neighbors(nums):
if not nums:
return []
result = []
n = len(nums)
for i in range(n):
left = nums[i-1] if i > 0 else 0
right = nums[i+1] if i < n-1 else 0
total = left + nums[i] + right
result.append(total)
return result | simplelr_Apps | [
{
"content": "Question:\nGiven a list of integers, return a new list in which each element is the sum of its neighbors and itself. For elements at the beginning and end of the list, assume their \"outside\" neighbors are zero.\n\nFor example:\n\n```python\nsum_neighbors([1, 2, 3, 4]) => [3, 6, 9, 7]\nsum_neighb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6274,
"level": 1,
"question": "Given a list of integers, return a new list in which each element is the sum of its neighbors and itself. For elements at the beginning and end of the list, assume their \"outside\" neighbors are zero.\n\nFor example:\n\n```python\nsum_neighbors([1, 2,... |
def middle_character(s):
length = len(s)
mid = length // 2
if length % 2 == 0:
return s[mid - 1:mid + 1]
else:
return s[mid]
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes in a string and returns the middle character(s) of the string. If the string length is odd, return the single middle character. If the string length is even, return the two middle characters.\n\nExamples:\n```\nmiddle_character(\"hello\") should return \"l\"\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6275,
"level": 1,
"question": "Write a function that takes in a string and returns the middle character(s) of the string. If the string length is odd, return the single middle character. If the string length is even, return the two middle characters.\n\nExamples:\n```\nmiddle_charac... |
def add_binary(a: str, b: str) -> str:
rev_a = a[::-1]
rev_b = b[::-1]
max_len = max(len(rev_a), len(rev_b))
carry = 0
result = []
for i in range(max_len):
a_bit = int(rev_a[i]) if i < len(rev_a) else 0
b_bit = int(rev_b[i]) if i < len(rev_b) else 0
total = a_bit + b... | simplelr_Taco | [
{
"content": "Question:\nYou are given two binary numbers represented as strings. Your task is to write a function that adds these two binary numbers and returns the result as a binary string.\n\nInput\n\nThe input consists of two non-empty binary strings. Each string represents a binary number. The length of e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6276,
"level": 1,
"question": "You are given two binary numbers represented as strings. Your task is to write a function that adds these two binary numbers and returns the result as a binary string.\n\nInput\n\nThe input consists of two non-empty binary strings. Each string represen... |
def index_of_max(lst):
if not lst:
return None # Return None for an empty list
max_value = lst[0]
max_index = 0
for index in range(1, len(lst)):
if lst[index] > max_value:
max_value = lst[index]
max_index = index
return max_index | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the index of the maximum value in a given list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6277,
"level": 1,
"question": "Write a python function to find the index of the maximum value in a given list.",
"split": "train"
} |
def filter_and_sort_odds(numbers):
return sorted([num for num in numbers if num % 2 != 0], reverse=True) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that achieves the following: it should take a list of integers as input and return a new list that only contains the odd numbers from the original list, but these odd numbers should be sorted in descending order in the new list.\nAnswer:\nLet's think step by step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6278,
"level": 1,
"question": "Write a Python function that achieves the following: it should take a list of integers as input and return a new list that only contains the odd numbers from the original list, but these odd numbers should be sorted in descending order in the new list.... |
import re
def validate_prices(prices):
pattern = r'^(?:\d{1,6}(?:\.\d{1,2})?|\.\d{1,2})$'
regex = re.compile(pattern)
return [bool(regex.fullmatch(price)) for price in prices] | simplelr_Filter | [
{
"content": "Question:\nI have a list of dynamic data, let's say prices of items in an online store. I want to check if the prices are in a valid format, which means they must be decimal numbers with a maximum of 2 decimal places and a maximum of 6 digits before the decimal point. I want to use regular express... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6279,
"level": 1,
"question": "I have a list of dynamic data, let's say prices of items in an online store. I want to check if the prices are in a valid format, which means they must be decimal numbers with a maximum of 2 decimal places and a maximum of 6 digits before the decimal p... |
def sum_numbers_at_indices(numbers, indices):
return sum(numbers[i] for i in indices)
# Test cases
numbers = [1, 2, 3, 4, 5]
indices = [0, 3]
print(sum_numbers_at_indices(numbers, indices)) # Output: 5
numbers = [1, 2, 3, 4, 5]
indices = [0, 3, 0]
print(sum_numbers_at_indices(numbers, indices)) # Output: 6 | simplelr_Filter | [
{
"content": "Question:\nI have two lists. \nOne contains some numbers\nThe other contains the index of the number in the first list that I would like to add to another number. \nFor example, if my first list contains [1, 2, 3, 4, 5] and my second list contains [0, 3], then the output should be 1 + 4 = 5.\nHowe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6280,
"level": 1,
"question": "I have two lists. \nOne contains some numbers\nThe other contains the index of the number in the first list that I would like to add to another number. \nFor example, if my first list contains [1, 2, 3, 4, 5] and my second list contains [0, 3], then th... |
def decode_string(s):
stack = []
currentString = ''
currentNumber = 0
for char in s:
if char.isdigit():
currentNumber = currentNumber * 10 + int(char)
elif char == '[':
stack.append((currentString, currentNumber))
currentString = ''
current... | simplelr_Apps | [
{
"content": "Question:\nGiven an encoded string, return its decoded string.\n\nThe encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times. Note that k is guaranteed to be a positive integer.\n\nAssume that the input string is always valid. No extra ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6281,
"level": 1,
"question": "Given an encoded string, return its decoded string.\n\nThe encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times. Note that k is guaranteed to be a positive integer.\n\nAssume that the inpu... |
def calculate_flights(destinations: dict, max_capacity: int) -> int:
total = 0
for passengers in destinations.values():
if passengers == 0:
continue
flights = (passengers + max_capacity - 1) // max_capacity
total += flights
return total | simplelr_Package | [
{
"content": "Question:\nYour task is to implement the `calculate_flights()` function which determines the minimum number of planes needed to transport a specified number of passengers across multiple destinations. Each route has a fixed passenger capacity, and planes can only carry up to a maximum number of pa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6282,
"level": 1,
"question": "Your task is to implement the `calculate_flights()` function which determines the minimum number of planes needed to transport a specified number of passengers across multiple destinations. Each route has a fixed passenger capacity, and planes can only... |
def minPathSum(grid):
m = len(grid)
n = len(grid[0]) if m > 0 else 0
if m == 0 or n == 0:
return 0
# Initialize the first row
dp_prev = [0] * n
dp_prev[0] = grid[0][0]
for j in range(1, n):
dp_prev[j] = dp_prev[j-1] + grid[0][j]
for i in range(1, m):
dp_current... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a grid with `m` rows and `n` columns, represented by a two-dimensional list. Each cell in the grid contains a non-negative integer, where each integer represents the cost to pass through that cell. You need to find a path from the top-left cell to the bottom-right cell tha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6283,
"level": 1,
"question": "You are given a grid with `m` rows and `n` columns, represented by a two-dimensional list. Each cell in the grid contains a non-negative integer, where each integer represents the cost to pass through that cell. You need to find a path from the top-lef... |
def compress_string(s: str) -> str:
if not s:
return s
compressed = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
compressed.append(current_char + str(count))
current_char = char
... | simplelr_Taco | [
{
"content": "Question:\nA common task in programming competitions involves working with strings. In this kata, you will implement a simple compression algorithm that works by replacing substrings of repeated characters with a single instance of the character followed by the number of times it appears consecuti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6284,
"level": 1,
"question": "A common task in programming competitions involves working with strings. In this kata, you will implement a simple compression algorithm that works by replacing substrings of repeated characters with a single instance of the character followed by the n... |
def is_unique(string: str) -> bool:
checker = 0
for char in string:
ord_val = ord(char)
mask = 1 << ord_val
if checker & mask:
return False
checker |= mask
return True | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\n**Uniqueness of Strings**\n\nYou are tasked with writing a function that determines if a given string consists of all unique characters. Your challenge is to accomplish this with O(n) time complexity and O(1) space complexity without using any additional data st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6285,
"level": 1,
"question": "### Problem Statement\n\n**Uniqueness of Strings**\n\nYou are tasked with writing a function that determines if a given string consists of all unique characters. Your challenge is to accomplish this with O(n) time complexity and O(1) space complexity w... |
import re
def exclude_alphanumeric(arr):
pattern = r'^[a-zA-Z0-9]+$'
result = []
for s in arr:
if not re.fullmatch(pattern, s):
result.append(s)
return result | simplelr_Filter | [
{
"content": "Question:\nGiven the following erroneous piece of code as a reference, devise a correct regex pattern to identify and exclude the series of alphanumeric characters. Additionally, write a function in Python to implement this pattern and correct the error in the reference code to increase its functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6286,
"level": 1,
"question": "Given the following erroneous piece of code as a reference, devise a correct regex pattern to identify and exclude the series of alphanumeric characters. Additionally, write a function in Python to implement this pattern and correct the error in the re... |
def max_product_of_pairs(lst):
if len(lst) < 2:
return -1
sorted_lst = sorted(lst)
product1 = sorted_lst[-1] * sorted_lst[-2]
product2 = sorted_lst[0] * sorted_lst[1]
return max(product1, product2) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum product of pairs in a given list. The function should take a list of integers as input and return the maximum product of any two distinct elements in the list. If the list contains less than 2 elements, return `-1` as no valid pair can be form... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6287,
"level": 1,
"question": "Write a python function to find the maximum product of pairs in a given list. The function should take a list of integers as input and return the maximum product of any two distinct elements in the list. If the list contains less than 2 elements, retur... |
def merge_sorted_lists(listA, listB):
# Initialize indices for both lists
indexA = indexB = 0
merged_list = []
# Merge smaller elements first
while indexA < len(listA) and indexB < len(listB):
if listA[indexA] < listB[indexB]:
merged_list.append(listA[indexA])
in... | simplelr_Filter | [
{
"content": "Question:\nI'm trying to implement the merging of two sorted lists into one sorted list. However, I keep running into the issue of losing the original data of one list because it is being modified in-place. How can I avoid this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6288,
"level": 1,
"question": "I'm trying to implement the merging of two sorted lists into one sorted list. However, I keep running into the issue of losing the original data of one list because it is being modified in-place. How can I avoid this?",
"split": "train"
} |
from typing import List
def max_rob_amount(houses: List[int]) -> int:
if not houses:
return 0
prev, curr = 0, houses[0]
for house in houses[1:]:
new_curr = max(curr, prev + house)
prev, curr = curr, new_curr
return curr | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\n\nYou are a professional programmer who needs to design a solution for a security company. The company wants to create a system to help robbers determine the maximum amount of money they can rob from houses arranged linearly without triggering an alarm. The constraints sti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6289,
"level": 1,
"question": "### Question\n\nYou are a professional programmer who needs to design a solution for a security company. The company wants to create a system to help robbers determine the maximum amount of money they can rob from houses arranged linearly without trigg... |
def length_of_longest_substring_two_distinct(s):
char_count = {}
left = 0
max_len = 0
for right in range(len(s)):
char = s[right]
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# Ensure the window has at most two d... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s`, you need to find the longest substring that contains at most two distinct characters.\n\n**Examples:**\n\n1. Input: `s = \"eceba\"`\n Output: `3`\n Explanation: The substring is `\"ece\"` which its length is 3.\n\n2. Input: `s = \"ccaabbb\"`\n Output: `5`\n E... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6290,
"level": 1,
"question": "Given a string `s`, you need to find the longest substring that contains at most two distinct characters.\n\n**Examples:**\n\n1. Input: `s = \"eceba\"`\n Output: `3`\n Explanation: The substring is `\"ece\"` which its length is 3.\n\n2. Input: `s =... |
from typing import List
def maxRob(nums: List[int]) -> int:
if not nums:
return 0
n = len(nums)
if n == 1:
return nums[0]
prev_prev = 0
prev = nums[0]
for i in range(1, n):
current = max(prev, prev_prev + nums[i])
prev_prev, prev = prev, current
return prev | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of non-negative integers representing the amounts of money of each house in a row of houses. Each house is connected to the next one, forming a neighborhood. There is a rule that states if you rob a house, you cannot rob its directly connected neighboring houses. De... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6291,
"level": 1,
"question": "You are given a list of non-negative integers representing the amounts of money of each house in a row of houses. Each house is connected to the next one, forming a neighborhood. There is a rule that states if you rob a house, you cannot rob its direct... |
from typing import List
def longest_consecutive_sequence(arr: List[int]) -> int:
if not arr:
return 0
s = set(arr)
max_length = 0
for num in s:
if (num - 1) not in s:
current = num
current_length = 0
while current in s:
current_length ... | simplelr_Evol | [
{
"content": "Question:\nYou are required to program a function that takes a list of integers and determines the length of the longest consecutive sequence of unique numbers. The list may contain both positive and negative integers, and duplicate values should be ignored when counting the sequence length.\n\nFu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6292,
"level": 1,
"question": "You are required to program a function that takes a list of integers and determines the length of the longest consecutive sequence of unique numbers. The list may contain both positive and negative integers, and duplicate values should be ignored when ... |
import re
def extract_emails(s):
pattern = r'\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b'
emails = re.findall(pattern, s)
return emails
# Example usage:
if __name__ == "__main__":
user_input = input("Please enter a string: ")
emails = extract_emails(user_input)
print("Extracted emails:"... | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that takes a string input from the user and processes it to extract all the email addresses found in the string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6293,
"level": 1,
"question": "How can I create a Python function that takes a string input from the user and processes it to extract all the email addresses found in the string?",
"split": "train"
} |
def sort_strings(arr):
return sorted(arr, key=lambda x: (-len(x), x.lower())) | simplelr_Filter | [
{
"content": "Question:\nWrite code to sort a given array of strings in descending order based on the length of each string. Also, for strings of equal lengths, sort them alphabetically. Ignore case sensitivity for the alphabetical sorting.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6294,
"level": 1,
"question": "Write code to sort a given array of strings in descending order based on the length of each string. Also, for strings of equal lengths, sort them alphabetically. Ignore case sensitivity for the alphabetical sorting.",
"split": "train"
} |
import numpy as np
from sklearn.covariance import EmpiricalCovariance, LedoitWolf, GraphicalLasso
def compare_covariance_methods(data):
"""
Compute and print covariance matrices using Empirical, Ledoit-Wolf, and Sparse Inverse methods.
Parameters:
- data: NumPy array of shape (n_samples, n_feature... | simplelr_Docs | [
{
"content": "Question:\n<|Analysis Begin|>\n\nThe provided document outlines various techniques and classes available in the `sklearn.covariance` module for estimating covariance matrices. The methods discussed include empirical covariance, shrunk covariance, Ledoit-Wolf shrinkage, Oracle Approximating Shrinka... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6295,
"level": 1,
"question": "<|Analysis Begin|>\n\nThe provided document outlines various techniques and classes available in the `sklearn.covariance` module for estimating covariance matrices. The methods discussed include empirical covariance, shrunk covariance, Ledoit-Wolf shri... |
def product_except_self(nums):
n = len(nums)
prefix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]
suffix = 1
res = [0] * n
for i in range(n-1, -1, -1):
res[i] = prefix[i] * suffix
suffix *= nums[i]
return res | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers, you need to write a function that returns a new array where each element at position `i` is the product of all the elements in the original array except the one at `i`.\n\nFor example, given `[1, 2, 3, 4]`, the output should be `[24, 12, 8, 6]`.\n\nYou should... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6296,
"level": 1,
"question": "Given an array of integers, you need to write a function that returns a new array where each element at position `i` is the product of all the elements in the original array except the one at `i`.\n\nFor example, given `[1, 2, 3, 4]`, the output should... |
from typing import List
def limit_occurrences(lst: List[int], N: int) -> List[int]:
counts = {}
result = []
for num in lst:
current = counts.get(num, 0)
if current < N:
result.append(num)
counts[num] = current + 1
return result | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are given a list of numbers and a maximum occurrence limit `N`. Your task is to create a function that processes the list and returns a new list where each number appears at most `N` times while preserving the order of their first occurrences.\n\n### Function Signature... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6297,
"level": 1,
"question": "### Scenario\nYou are given a list of numbers and a maximum occurrence limit `N`. Your task is to create a function that processes the list and returns a new list where each number appears at most `N` times while preserving the order of their first occ... |
def compress_string(s):
if not s:
return s
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(current_char + str(count))
current_char = char
count = 1
result.... | simplelr_Package | [
{
"content": "Question:\nYou need to implement a function `compress_string(s)` that compresses a given string by replacing sequences of the same character with that character followed by the count of repetitions. If the compressed version of the string is not shorter than the original string, the function shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6298,
"level": 1,
"question": "You need to implement a function `compress_string(s)` that compresses a given string by replacing sequences of the same character with that character followed by the count of repetitions. If the compressed version of the string is not shorter than the ... |
def custom_sort(lst):
evens = []
odds = []
for num in lst:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens + odds | simplelr_Apps | [
{
"content": "Question:\nImplement an algorithm that takes a list of integers and sorts it in a custom order such that all even numbers appear before all odd numbers, while preserving the relative order of the even and odd numbers. \n\nSpecifically:\n- Your function should accept a single list of integers `[a1,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6299,
"level": 1,
"question": "Implement an algorithm that takes a list of integers and sorts it in a custom order such that all even numbers appear before all odd numbers, while preserving the relative order of the even and odd numbers. \n\nSpecifically:\n- Your function should acc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.