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 calculate_expression(expression):
try:
return eval(expression)
except:
return "Error: Invalid expression" | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the result of a provided arithmetic expression using eval()\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2800,
"level": 1,
"question": "Write a python function to calculate the result of a provided arithmetic expression using eval()",
"split": "train"
} |
from typing import List, Optional
def filter_by_range(arr: List[int], min_value: Optional[int], max_value: Optional[int]) -> List[int]:
result = []
for num in arr:
if (min_value is None or num >= min_value) and (max_value is None or num <= max_value):
result.append(num)
return result | simplelr_Data_Structure | [
{
"content": "Question:\n### Filtering Array by Value Range\n\n#### Context\nYou have a dataset represented as an array of numeric values. Sometimes, you need to extract a subset of this data that falls within a specific range of values. You want to implement a function that will filter the array based on minim... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2801,
"level": 1,
"question": "### Filtering Array by Value Range\n\n#### Context\nYou have a dataset represented as an array of numeric values. Sometimes, you need to extract a subset of this data that falls within a specific range of values. You want to implement a function that w... |
import torch
def hip_compatibility_memory_management():
"""
This function performs device allocation, tensor operations, and provides memory usage details.
It checks for CUDA availability and uses the appropriate backend (HIP or CUDA) if available.
If neither is available, it defaults to CPU and memory... | simplelr_Docs | [
{
"content": "Question:\n### PyTorch HIP Compatibility Check and Memory Management\n\n**Objective:**\nImplement a function that performs device allocation, tensor operations, and provides memory usage details for PyTorch compatible with HIP and CUDA.\n\n### Function Specifications\n\n**Function Signature:**\n``... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2802,
"level": 1,
"question": "### PyTorch HIP Compatibility Check and Memory Management\n\n**Objective:**\nImplement a function that performs device allocation, tensor operations, and provides memory usage details for PyTorch compatible with HIP and CUDA.\n\n### Function Specificat... |
import random
def generate_confrontational_message(name):
messages = [
"I'm really disappointed in you, {name}. What were you thinking?",
"Seriously, {name}? That was really thoughtless.",
"You really let me down, {name}. What's going on with you?",
"I need to talk to you about some... | simplelr_Filter | [
{
"content": "Question:\nHere is a simple Python script that generates a confrontational message for a friend:\n```python\ndef generate_confrontational_message(name):\n messages = [\n \"I'm really disappointed in you, {name}. What were you thinking?\",\n \"Seriously, {name}? That was really tho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2803,
"level": 1,
"question": "Here is a simple Python script that generates a confrontational message for a friend:\n```python\ndef generate_confrontational_message(name):\n messages = [\n \"I'm really disappointed in you, {name}. What were you thinking?\",\n \"Ser... |
def running_sum(arr):
result = []
current_sum = 0
for num in arr:
current_sum += num
result.append(current_sum)
return result
| simplelr_Taco | [
{
"content": "Question:\nCreate a function that calculates the running sum of a one-dimensional array of integers. Test arrays are limited to a size of 1-50.\n\nRunning sum is defined as the cumulative total of the array elements as you iterate through the array.\n\nFirst Example:\n\nInput: [1, 2, 3, 4]\n\nStep... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2804,
"level": 1,
"question": "Create a function that calculates the running sum of a one-dimensional array of integers. Test arrays are limited to a size of 1-50.\n\nRunning sum is defined as the cumulative total of the array elements as you iterate through the array.\n\nFirst Exam... |
def calculateTrappedWater(heights):
if not heights:
return 0
left = 0
right = len(heights) - 1
max_left = max_right = 0
result = 0
while left <= right:
if heights[left] < heights[right]:
if heights[left] >= max_left:
max_left = heights[left]
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of integers representing the elevation of a terrain. Your task is to compute the volume of water that can be trapped between these elevations after raining. The water trapped at each position is determined by the heights of the tallest elevations to the left and rig... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2805,
"level": 1,
"question": "You are given a list of integers representing the elevation of a terrain. Your task is to compute the volume of water that can be trapped between these elevations after raining. The water trapped at each position is determined by the heights of the tal... |
def min_flowers_after_nights(nums, d):
return min(nums) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` representing the number of flowers in each garden along a straight path. Every night, the fairy visits and the flowers in each garden either grow or shrink according to pre-defined rules. Specifically, for each garden at position `i`, the number of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2806,
"level": 1,
"question": "You are given an integer array `nums` representing the number of flowers in each garden along a straight path. Every night, the fairy visits and the flowers in each garden either grow or shrink according to pre-defined rules. Specifically, for each gar... |
from typing import List
def remove_min_elements(stack: List[int]) -> List[int]:
if not stack:
return []
min_val = min(stack)
return [x for x in stack if x != min_val] | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario:\nYou have a stack representing a sequence of integers, and you need to design a function that removes all occurrences of the smallest value, keeping the relative order of other elements intact. For this, you need to implement an optimal algorithm using an auxiliary stack o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2807,
"level": 1,
"question": "### Scenario:\nYou have a stack representing a sequence of integers, and you need to design a function that removes all occurrences of the smallest value, keeping the relative order of other elements intact. For this, you need to implement an optimal a... |
def find_common_elements(list1, list2):
seen = {}
for num in list1:
if num not in seen:
seen[num] = True
added = {}
result = []
for num in list2:
if num in seen and num not in added:
result.append(num)
added[num] = True
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two lists of integers as input and returns a list with elements that are common in both lists. Avoid using built-in functions or additional libraries. You should also ensure the function runs in linear time, i.e., O(n+m), where n and m are the lengths of the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2808,
"level": 1,
"question": "Create a function that takes two lists of integers as input and returns a list with elements that are common in both lists. Avoid using built-in functions or additional libraries. You should also ensure the function runs in linear time, i.e., O(n+m), w... |
def max_subarray_sum(arr):
current_max = max_so_far = arr[0]
for num in arr[1:]:
current_max = max(num, current_max + num)
if current_max > max_so_far:
max_so_far = current_max
return max_so_far | simplelr_Codeforces | [
{
"content": "Question:\nYash loves solving puzzles. He recently discovered a unique kind of puzzle which involves manipulating a list of integers. The list can have both positive and negative numbers, and Yash's task is to find a contiguous subarray with the maximum possible sum.\n\nGiven an array of integers,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2809,
"level": 1,
"question": "Yash loves solving puzzles. He recently discovered a unique kind of puzzle which involves manipulating a list of integers. The list can have both positive and negative numbers, and Yash's task is to find a contiguous subarray with the maximum possible ... |
def are_rotations(s1, s2):
if len(s1) != len(s2):
return False
return s2 in s1 + s1 | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to check if two strings are rotations of each other.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2810,
"level": 1,
"question": "Write a Python function to check if two strings are rotations of each other.",
"split": "train"
} |
def max_distance_between_consecutive_integers(nums):
sorted_nums = sorted(nums)
max_gap = 0
for i in range(len(sorted_nums) - 1):
gap = sorted_nums[i+1] - sorted_nums[i]
if gap > max_gap:
max_gap = gap
return max_gap | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of `n` integers where each integer represents a position on a number line, return the maximum distance between any two consecutive integers after sorting the list. The list is guaranteed to have at least two elements.\nAnswer:\nLet's think step by step.\n",
"role": "us... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2811,
"level": 1,
"question": "Given a list of `n` integers where each integer represents a position on a number line, return the maximum distance between any two consecutive integers after sorting the list. The list is guaranteed to have at least two elements.",
"split": "train"... |
def uniqueActions(log, user_id):
actions = set()
for entry in log:
parts = entry.split()
if parts[0] == user_id:
actions.add(parts[1])
return len(actions)
| simplelr_Taco | [
{
"content": "Question:\nA company has a server which maintains a log of user activities. Each activity log is represented as a string in the format \"user_id action timestamp\". The log contains multiple entries for various users and actions. Your task is to write a function that processes the log and returns ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2812,
"level": 1,
"question": "A company has a server which maintains a log of user activities. Each activity log is represented as a string in the format \"user_id action timestamp\". The log contains multiple entries for various users and actions. Your task is to write a function ... |
def triangle_area(base, height):
"""Calculates the area of a triangle given its base and height.
Args:
base (int or float): The base of the triangle. Must be a positive number.
height (int or float): The height of the triangle. Must be a positive number.
Returns:
float: The... | simplelr_Filter | [
{
"content": "Question:\nThis program calculates the area of a triangle given its base and height.\n\nFunction:\n Takes two input arguments: `base` and `height`.\n Calculates the area using the formula: `area = 0.5 base height`.\n Returns the calculated area.\n\nCode (Python):\n\n```python\ndef triangle_area(... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2813,
"level": 1,
"question": "This program calculates the area of a triangle given its base and height.\n\nFunction:\n Takes two input arguments: `base` and `height`.\n Calculates the area using the formula: `area = 0.5 base height`.\n Returns the calculated area.\n\nCode (Python... |
def factorial(n):
if not isinstance(n, int):
raise TypeError("Input must be an integer.")
if n < 0:
raise ValueError("Input must be a non-negative integer.")
result = 1
for i in range(1, n + 1):
result *= i
return result | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that calculates the factorial of a number and handles errors for negative inputs?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2814,
"level": 1,
"question": "How can I create a Python function that calculates the factorial of a number and handles errors for negative inputs?",
"split": "train"
} |
def min_total_range(arr, k):
if k == 0:
return 0
arr.sort()
n = len(arr)
if n == 0:
return 0
if k >= n:
return 0
gaps = []
for i in range(n - 1):
gaps.append(arr[i+1] - arr[i])
gaps.sort(reverse=True)
sum_gaps = sum(gaps[:k-1])
return arr[-1] - arr... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `arr` of size `n` which represents the locations of `n` stores on a number line. Additionally, you are given an integer `k` representing the number of warehouses to build. Each warehouse can provide supplies to all stores within a certain range to the left... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2815,
"level": 1,
"question": "You are given an integer array `arr` of size `n` which represents the locations of `n` stores on a number line. Additionally, you are given an integer `k` representing the number of warehouses to build. Each warehouse can provide supplies to all stores... |
def count_uppercase(s):
return sum(1 for char in s if char.isupper()) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function `count_uppercase` that takes a string input and returns the number of uppercase letters present in the string. An uppercase letter is any of the 26 letters from A to Z.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2816,
"level": 1,
"question": "Create a Python function `count_uppercase` that takes a string input and returns the number of uppercase letters present in the string. An uppercase letter is any of the 26 letters from A to Z.",
"split": "train"
} |
def kth_largest_unique(nums: list, k: int) -> int:
unique = list(set(nums))
unique_sorted = sorted(unique, reverse=True)
if k <= len(unique_sorted):
return unique_sorted[k-1]
else:
return None | simplelr_Package | [
{
"content": "Question:\nCreate a function that takes a list of numbers and an integer `k`, then returns the k-th largest unique number in the list. If there are fewer than k unique numbers, the function should return None.\n\nThe function should be defined as follows:\n```python\ndef kth_largest_unique(nums: l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2817,
"level": 1,
"question": "Create a function that takes a list of numbers and an integer `k`, then returns the k-th largest unique number in the list. If there are fewer than k unique numbers, the function should return None.\n\nThe function should be defined as follows:\n```pyt... |
def character_frequency(s):
frequency = {}
for char in s:
frequency[char] = frequency.get(char, 0) + 1
return frequency | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the frequency of each character in a string s.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2818,
"level": 1,
"question": "Write a function to find the frequency of each character in a string s.",
"split": "train"
} |
def findInsertPosition(arr, value):
left, right = 0, len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] < value:
left = mid + 1
else:
right = mid
return left | simplelr_Apps | [
{
"content": "Question:\nBinary Search - Find Insert Position\n\nWrite a `findInsertPosition()` function that determines the index position at which a value should be inserted into a sorted (ascending) array to maintain its sorted order. The function takes a sorted array and a value as arguments and returns the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2819,
"level": 1,
"question": "Binary Search - Find Insert Position\n\nWrite a `findInsertPosition()` function that determines the index position at which a value should be inserted into a sorted (ascending) array to maintain its sorted order. The function takes a sorted array and a... |
def findPairs(array, K):
sorted_arr = sorted(array)
n = len(sorted_arr)
left = 0
right = n - 1
result = []
while left < right:
current_sum = sorted_arr[left] + sorted_arr[right]
if current_sum == K:
result.append((sorted_arr[left], sorted_arr[right]))
... | simplelr_Taco | [
{
"content": "Question:\nGiven an unsorted array of N integers and a sum K, find all unique pairs of elements in the array that add up to the sum K.\n\nExample 1:\nInput: N = 5, K = 9, \narray = [2, 7, 4, 5, 3]\nOutput: [(2, 7), (4, 5)]\nExample 2:\nInput: N = 4, K = 6, \narray = [1, 5, 1, 0]\nOutput: [(5, 1)]\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2820,
"level": 1,
"question": "Given an unsorted array of N integers and a sum K, find all unique pairs of elements in the array that add up to the sum K.\n\nExample 1:\nInput: N = 5, K = 9, \narray = [2, 7, 4, 5, 3]\nOutput: [(2, 7), (4, 5)]\nExample 2:\nInput: N = 4, K = 6, \narra... |
from typing import List, Tuple
def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if not intervals:
return []
# Sort intervals based on the start time
sorted_intervals = sorted(intervals, key=lambda x: x[0])
# Initialize the merged list with the first inte... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Problem Statement\nA company is trying to optimize their meeting schedules. They need to merge overlapping and adjacent time intervals in a schedule. You are provided with a list of intervals where each interval is a tuple of two integers represent... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2821,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Problem Statement\nA company is trying to optimize their meeting schedules. They need to merge overlapping and adjacent time intervals in a schedule. You are provided with a list of intervals where each interval i... |
def count_positive_integers(lst):
count = 0
for x in lst:
if type(x) is int and x > 0:
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to count the number of positive integers in a given list. The function should return the count of positive integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2822,
"level": 1,
"question": "Write a Python function to count the number of positive integers in a given list. The function should return the count of positive integers.",
"split": "train"
} |
def reverse_string(s):
reversed_str = ""
for i in range(len(s) - 1, -1, -1):
reversed_str += s[i]
return reversed_str | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that reverses an input string without utilizing any built-in functions specifically designed for string manipulation?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2823,
"level": 1,
"question": "How can I create a Python function that reverses an input string without utilizing any built-in functions specifically designed for string manipulation?",
"split": "train"
} |
def count_even_odd(numbers):
even = sum(1 for num in numbers if num % 2 == 0)
return (even, len(numbers) - even) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list of integers and returns a tuple containing the total number of even and odd numbers in the list. For example, given the list [1, 2, 3, 4, 5], the function should return (2, 3) because 2 even numbers (2, 4) and 3 odd numbers (1, 3, 5) are present.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2824,
"level": 1,
"question": "Create a function that takes in a list of integers and returns a tuple containing the total number of even and odd numbers in the list. For example, given the list [1, 2, 3, 4, 5], the function should return (2, 3) because 2 even numbers (2, 4) and 3 o... |
from typing import List, Union
def find_second_largest(nums: List[int]) -> Union[int, None]:
seen = set()
first = None
second = None
for num in nums:
if num not in seen:
seen.add(num)
if first is None or num > first:
second = first
first =... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are required to implement a function that, given a list of integers, returns the second largest unique integer in the list. If there is no such second largest unique integer, return `None`.\n\n**Function Signature**:\n```python\ndef find_second_largest(nums: L... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2825,
"level": 1,
"question": "### Problem Statement\nYou are required to implement a function that, given a list of integers, returns the second largest unique integer in the list. If there is no such second largest unique integer, return `None`.\n\n**Function Signature**:\n```pyth... |
def max_sum_submatrix(matrix):
if not matrix or not matrix[0]:
return 0
rows = len(matrix)
cols = len(matrix[0])
max_sum = float('-inf')
for left in range(cols):
temp = [0] * rows
for right in range(left, cols):
# Update temp array with the next right column ... | simplelr_Filter | [
{
"content": "Question:\nThis problem is similar to the one I solved in the previous question. The problem is to find the maximum sum of elements in a subarray within an array. In this case, we are given a 2D array, and we are allowed to move in two directions: either move right from the current element to the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2826,
"level": 1,
"question": "This problem is similar to the one I solved in the previous question. The problem is to find the maximum sum of elements in a subarray within an array. In this case, we are given a 2D array, and we are allowed to move in two directions: either move rig... |
from typing import List
def trapWater(heights: List[int]) -> int:
if not heights or len(heights) < 3:
return 0
n = len(heights)
left_max = [0] * n
right_max = [0] * n
# Populate left_max array
for i in range(1, n):
left_max[i] = max(left_max[i-1], heights[i-1])
# P... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of non-negative integers representing the heights of a collection of blocks. Each block is 1 unit wide, and the heights of the blocks are integers. Suppose it will rain, and the water will be trapped between some blocks after raining. You need to compute how much wa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2827,
"level": 1,
"question": "You are given a list of non-negative integers representing the heights of a collection of blocks. Each block is 1 unit wide, and the heights of the blocks are integers. Suppose it will rain, and the water will be trapped between some blocks after raini... |
def num_digits(n):
if n == 0:
return 1
return len(str(abs(n))) | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are developing a software system that performs various numerical computations, and one of the tasks is to quickly determine how many digits an integer has. Efficiently calculating the number of digits in an integer is crucial for this part of the system to ensure it ca... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2828,
"level": 1,
"question": "### Scenario\nYou are developing a software system that performs various numerical computations, and one of the tasks is to quickly determine how many digits an integer has. Efficiently calculating the number of digits in an integer is crucial for this... |
def max_subarray_sum(nums):
if not nums:
return 0 # Though the problem states the array is non-empty, this handles edge cases.
max_current = max_global = nums[0]
for num in nums[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_... | simplelr_Leetcode | [
{
"content": "Question:\nYou have a `0-indexed` integer array `nums`. Your task is to find and return the maximum sum of any non-empty subarray of `nums`. A subarray is a contiguous part of an array. Note that a subarray of length `1` is considered valid. If the array contains only negative numbers, return the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2829,
"level": 1,
"question": "You have a `0-indexed` integer array `nums`. Your task is to find and return the maximum sum of any non-empty subarray of `nums`. A subarray is a contiguous part of an array. Note that a subarray of length `1` is considered valid. If the array contains... |
def find_longest_substring(s, k):
if k == 0:
return 0
char_count = {}
left = 0
max_length = 0
for right in range(len(s)):
current_char = s[right]
if current_char in char_count:
char_count[current_char] += 1
else:
char_count[current_char] = 1
... | simplelr_Package | [
{
"content": "Question:\nYou are required to implement a function `find_longest_substring(s, k)` that finds the length of the longest substring of the given string `s` that contains at most `k` distinct characters. \n\n#### Function Signature:\n```python\ndef find_longest_substring(s, k):\n pass\n```\n\n####... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2830,
"level": 1,
"question": "You are required to implement a function `find_longest_substring(s, k)` that finds the length of the longest substring of the given string `s` that contains at most `k` distinct characters. \n\n#### Function Signature:\n```python\ndef find_longest_subs... |
def max_length_of_good_substring(s):
char_dict = {}
max_len = 0
left = 0
for right in range(len(s)):
char = s[right]
if char in char_dict and char_dict[char] >= left:
left = char_dict[char] + 1
char_dict[char] = right
current_len = right - left + 1
if ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** string `s` consisting of lowercase English letters. A **good substring** is a substring that contains no repeated characters. Return _the maximum length of a good substring_ in `s`. If no such substring exists, return 0.\nAnswer:\nLet's think step by step.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2831,
"level": 1,
"question": "You are given a **0-indexed** string `s` consisting of lowercase English letters. A **good substring** is a substring that contains no repeated characters. Return _the maximum length of a good substring_ in `s`. If no such substring exists, return 0.",... |
def generatePascalsTriangle(n):
if n == 0:
return ""
triangle = []
current_row = [1]
triangle.append(current_row)
for i in range(1, n):
new_row = [1]
for j in range(len(current_row) - 1):
new_row.append(current_row[j] + current_row[j+1])
new_row.append(1)
... | simplelr_Codeforces | [
{
"content": "Question:\nGiven an integer n, you need to construct a Pascal’s triangle of height n. Pascal's triangle is a triangular array of binomial coefficients. The rows of Pascal's triangle are conventionally enumerated starting with row r = 0 at the top.\n\nFor example, the Pascal's triangle up to height... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2832,
"level": 1,
"question": "Given an integer n, you need to construct a Pascal’s triangle of height n. Pascal's triangle is a triangular array of binomial coefficients. The rows of Pascal's triangle are conventionally enumerated starting with row r = 0 at the top.\n\nFor example,... |
def filter_non_negative(lst):
return [x for x in lst if x >= 0]
| simplelr_Taco | [
{
"content": "Question:\nPlease write a function that takes a list of integers and returns a new list containing only the non-negative integers from the original list, in the original order.\n\nFor example, for the list [-1, 2, -3, 4, 0], the function should return [2, 4, 0].\nAnswer:\nLet's think step by step.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2833,
"level": 1,
"question": "Please write a function that takes a list of integers and returns a new list containing only the non-negative integers from the original list, in the original order.\n\nFor example, for the list [-1, 2, -3, 4, 0], the function should return [2, 4, 0]."... |
def group_sort_items(items):
grouped = {}
for item, category in items:
if category not in grouped:
grouped[category] = []
grouped[category].append(item)
for category in grouped:
grouped[category].sort()
return grouped | simplelr_Package | [
{
"content": "Question:\nYou are given a list of tuples, where each tuple contains an item and its corresponding category. Your task is to create a function `group_sort_items(items)` that groups the items by their categories and then sorts the items within each category in alphabetical order.\n\nHere are the st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2834,
"level": 1,
"question": "You are given a list of tuples, where each tuple contains an item and its corresponding category. Your task is to create a function `group_sort_items(items)` that groups the items by their categories and then sorts the items within each category in alp... |
from typing import List, Tuple
def optimal_matrix_chain_multiplication(p: List[int]) -> Tuple[int, List[List[int]]]:
n = len(p) - 1
dp = [[0] * (n + 1) for _ in range(n + 1)]
for l in range(2, n + 1):
for i in range(1, (n - l + 1) + 1):
j = i + l - 1
dp[i][j] = float('i... | simplelr_Data_Structure | [
{
"content": "Question:\n### Context\nMatrix Chain Multiplication is a classic problem in dynamic programming with applications in optimizing the cost of multiplying multiple matrices. Given a sequence of matrices, the order in which pairs of matrices are multiplied greatly affects the number of operations need... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2835,
"level": 1,
"question": "### Context\nMatrix Chain Multiplication is a classic problem in dynamic programming with applications in optimizing the cost of multiplying multiple matrices. Given a sequence of matrices, the order in which pairs of matrices are multiplied greatly af... |
def findMaxConsecutiveOnes(nums):
left = 0
max_length = 0
zero_count = 0
n = len(nums)
for right in range(n):
if nums[right] == 0:
zero_count += 1
# If we have more than one zero, move left pointer to reduce the count
while zero_count > 1:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums` of size `n` where each element is either `0` or `1`, return _the **maximum** number of consecutive `1`s in the array if you can flip at most **one** `0` to `1`_. If the array contains no `0`s, return the length of the array.\nAnswer:\nLet's think step by st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2836,
"level": 1,
"question": "Given an integer array `nums` of size `n` where each element is either `0` or `1`, return _the **maximum** number of consecutive `1`s in the array if you can flip at most **one** `0` to `1`_. If the array contains no `0`s, return the length of the arra... |
from collections import Counter
def isPalindromePermutation(s: str) -> bool:
# Remove all spaces from the string
s = s.replace(' ', '')
# Handle empty string case
if len(s) == 0:
return True
# Count the frequency of each character
counts = Counter(s)
odd_count = 0
for count in c... | simplelr_Taco | [
{
"content": "Question:\n### Palindrome Permutation Checker\n\nA palindrome is a word or phrase that reads the same forwards and backwards, ignoring spaces, punctuation, and capitalization. A permutation is a rearrangement of letters. Your task is to determine if a given string is a permutation of a palindrome.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2837,
"level": 1,
"question": "### Palindrome Permutation Checker\n\nA palindrome is a word or phrase that reads the same forwards and backwards, ignoring spaces, punctuation, and capitalization. A permutation is a rearrangement of letters. Your task is to determine if a given strin... |
def searchFirst(nums, target):
if not nums:
return -1
# Check if the array is sorted in non-decreasing order
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
return -1
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
... | simplelr_Filter | [
{
"content": "Question:\nHere is a simple algorithm problem:\nGiven a sorted array of integers, design a function to find the index of the first occurrence of a target value using binary search. If the target is not found, return -1.\n\nExample 1:\nInput: nums = [1,2,3,3,3,3,3,4,5], target = 3\nOutput: 1\n\nE... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2838,
"level": 1,
"question": "Here is a simple algorithm problem:\nGiven a sorted array of integers, design a function to find the index of the first occurrence of a target value using binary search. If the target is not found, return -1.\n\nExample 1:\nInput: nums = [1,2,3,3,3,3,... |
def partition_list(input_list, pivot):
less_than = []
greater_or_equal = []
for num in input_list:
if num < pivot:
less_than.append(num)
else:
greater_or_equal.append(num)
return (less_than, greater_or_equal) | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Description\nWrite a function `partition_list` that takes in a list of integers and a pivot integer. The function should partition the list into two sublists: one containing all elements less than the pivot, and the other containing all elements greater than or equal to the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2839,
"level": 1,
"question": "### Problem Description\nWrite a function `partition_list` that takes in a list of integers and a pivot integer. The function should partition the list into two sublists: one containing all elements less than the pivot, and the other containing all ele... |
from collections import Counter
def longestSubsequence(arr):
if not arr:
return 0
count = Counter(arr)
max_len = 0
for x in count:
current_sum = count[x] + count.get(x + 1, 0)
if current_sum > max_len:
max_len = current_sum
return max_len
| simplelr_Taco | [
{
"content": "Question:\nTask\n\nGiven a list of integers, your task is to find the longest subsequence where the difference between the maximum number and the minimum number in the subsequence is no greater than 1. \n\nInput\n\nThe input consists of a list of integers.\n\nOutput\n\nReturn the length of the lon... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2840,
"level": 1,
"question": "Task\n\nGiven a list of integers, your task is to find the longest subsequence where the difference between the maximum number and the minimum number in the subsequence is no greater than 1. \n\nInput\n\nThe input consists of a list of integers.\n\nOut... |
def max_product(arr):
arr.sort()
candidate1 = arr[-1] * arr[-2]
candidate2 = arr[0] * arr[1]
return max(candidate1, candidate2)
| simplelr_Taco | [
{
"content": "Question:\nWrite a `max_product` function that receives an array of integers and returns the maximum product that can be obtained by multiplying two distinct elements from the array. The array will contain at least two integers.\n\nExamples:\n```\n[1, 2, 3, 4] => 12 (4 * 3)\n[-10, -20, 5, 6] => 20... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2841,
"level": 1,
"question": "Write a `max_product` function that receives an array of integers and returns the maximum product that can be obtained by multiplying two distinct elements from the array. The array will contain at least two integers.\n\nExamples:\n```\n[1, 2, 3, 4] =>... |
def prime_factors(n):
"""
Computes the prime factors of a given integer n and returns them in ascending order as a list.
:param n: The integer to find prime factors for.
:return: A list of prime factors in ascending order.
"""
if n < 2:
return []
factors = []
# Handle the fa... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a Python function named `prime_factors` that computes the prime factors of a given integer. The function should return a list containing the prime factors in ascending order. The function signature is as follows:\n```python\ndef prime_factors(n):\n \"\"\"\n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2842,
"level": 1,
"question": "You are required to write a Python function named `prime_factors` that computes the prime factors of a given integer. The function should return a list containing the prime factors in ascending order. The function signature is as follows:\n```python\nd... |
def max_distinct_chars_in_substring(s: str, k: int) -> int:
freq = {}
left = 0
max_distinct = 0
for right in range(len(s)):
char = s[right]
if char in freq:
freq[char] += 1
else:
freq[char] = 1
# Ensure the window size does not exceed k
... | simplelr_Evol | [
{
"content": "Question:\nYou are given a string consisting of lowercase English letters only. You need to write a function that finds the maximum number of distinct characters in any substring of the given string of a specified length.\n\n**Function Signature:**\n```python\ndef max_distinct_chars_in_substring(s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2843,
"level": 1,
"question": "You are given a string consisting of lowercase English letters only. You need to write a function that finds the maximum number of distinct characters in any substring of the given string of a specified length.\n\n**Function Signature:**\n```python\nde... |
import matplotlib.pyplot as plt
import seaborn as sns
def create_comparative_plots(data, x_col, y_col):
"""
Generates two line plots with different plotting context styles and saves them as images.
Parameters:
data (DataFrame): DataFrame containing the data to plot.
x_col (str): Name of the column... | simplelr_Docs | [
{
"content": "Question:\nUsing Seaborn Plotting Context\n\n**Objective:** \n\nWrite a function `create_comparative_plots(data, x_col, y_col)` that generates two comparative line plots from the input data using Seaborn. The function should demonstrate the use of seaborn's `plotting_context` to temporarily change... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2844,
"level": 1,
"question": "Using Seaborn Plotting Context\n\n**Objective:** \n\nWrite a function `create_comparative_plots(data, x_col, y_col)` that generates two comparative line plots from the input data using Seaborn. The function should demonstrate the use of seaborn's `plot... |
def is_peak_arrangement(heights):
max_val = max(heights)
max_index = heights.index(max_val)
n = len(heights)
center = n // 2
if max_index != center:
return False
# Check left side is strictly increasing
for i in range(center):
if heights[i] >= heights[i + 1]:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `heights` representing the height of buildings in a city. The array satisfies the following properties: \n1. `heights.length` is odd.\n2. There is a unique index `i` such that `heights[i]` is the maximum height in the array.\n\nA **peak arrang... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2845,
"level": 1,
"question": "You are given a **0-indexed** integer array `heights` representing the height of buildings in a city. The array satisfies the following properties: \n1. `heights.length` is odd.\n2. There is a unique index `i` such that `heights[i]` is the maximum heig... |
def max_satisfied_employees(employee_appetites: list[int], cookie_sizes: list[int]) -> int:
employees = sorted(employee_appetites)
cookies = sorted(cookie_sizes)
i = j = count = 0
while i < len(employees) and j < len(cookies):
if employees[i] <= cookies[j]:
count += 1
i +... | simplelr_Algorithm | [
{
"content": "Question:\nA company wants to distribute cookies to its employees, but each employee has a unique appetite level, meaning they need a minimum number of cookies to be satisfied. The company also has a list of cookie sizes available. Each cookie can only be given to one employee, and an employee can... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2846,
"level": 1,
"question": "A company wants to distribute cookies to its employees, but each employee has a unique appetite level, meaning they need a minimum number of cookies to be satisfied. The company also has a list of cookie sizes available. Each cookie can only be given t... |
from itertools import accumulate
def sort_array_by_length(arr):
# Flatten the 2D array into a 1D list
flat = [word for sublist in arr for word in sublist]
# Sort the flattened list by the length of each element
flat_sorted = sorted(flat, key=lambda x: len(x))
# Determine the structure of the origin... | simplelr_Filter | [
{
"content": "Question:\nGiven a 2D array of strings, sort the array in ascending order by each element's length.\n\nHere is a 2D array example: `[[\"apple\", \"banana\", \"cherry\"], [\"date\", \"elderberry\", \"fig\"]]`\n\nThe sorted array should be: `[[\"apple\", \"date\", \"fig\"], [\"banana\", \"cherry\", ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2847,
"level": 1,
"question": "Given a 2D array of strings, sort the array in ascending order by each element's length.\n\nHere is a 2D array example: `[[\"apple\", \"banana\", \"cherry\"], [\"date\", \"elderberry\", \"fig\"]]`\n\nThe sorted array should be: `[[\"apple\", \"date\", ... |
def matrix_multiply(matrix1, matrix2):
# Get the dimensions of the matrices
rows_matrix1 = len(matrix1)
cols_matrix1 = len(matrix1[0])
rows_matrix2 = len(matrix2)
cols_matrix2 = len(matrix2[0])
# Check if multiplication is possible
if cols_matrix1 != rows_matrix2:
raise ValueErr... | simplelr_Filter | [
{
"content": "Question:\nCreate a code in Python to multiply two matrices. However, instead of using nested loops, use list comprehensions or the map() function to perform the multiplication. Additionally, ensure that the multiplication operation is performed using SIMD (Single Instruction, Multiple Data) instr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2848,
"level": 1,
"question": "Create a code in Python to multiply two matrices. However, instead of using nested loops, use list comprehensions or the map() function to perform the multiplication. Additionally, ensure that the multiplication operation is performed using SIMD (Singl... |
from collections import Counter
def can_rearrange_no_adjacent(s):
if not s:
return True
counts = Counter(s)
max_freq = max(counts.values())
n = len(s)
return max_freq <= (n + 1) // 2 | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters. You want to form a new string by reordering the characters of `s` so that no two adjacent characters are the same. Return `true` if it is possible to form such a string, otherwise return `false`.\nAnswer:\nLet's think s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2849,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters. You want to form a new string by reordering the characters of `s` so that no two adjacent characters are the same. Return `true` if it is possible to form such a string, otherwise retu... |
def rotate_list(lst, k):
n = len(lst)
if n == 0:
return []
effective_k = k % n
if effective_k == 0:
return list(lst)
return lst[-effective_k:] + lst[:-effective_k] | simplelr_Package | [
{
"content": "Question:\nGiven a list of integers, your task is to write a Python function `rotate_list` that rotates the elements of the list to the right by a specified number of steps. If the rotation number is greater than the length of the list, it should continue rotating from the starting element.\n\nFor... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2850,
"level": 1,
"question": "Given a list of integers, your task is to write a Python function `rotate_list` that rotates the elements of the list to the right by a specified number of steps. If the rotation number is greater than the length of the list, it should continue rotatin... |
def find_max_consecutive_ones(nums):
max_ones = 0
current_ones = 0
for num in nums:
if num == 1:
current_ones += 1
if current_ones > max_ones:
max_ones = current_ones
else:
current_ones = 0
return max_ones | simplelr_Filter | [
{
"content": "Question:\ndef find_max_consecutive_ones(nums):\n max_ones = 0\n current_ones = 0\n for num in nums:\n if num == 1:\n current_ones += 1\n max_ones = max(max_ones, current_ones)\n else:\n current_ones = 0\n return max_ones\nAnswer:\nLet's t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2851,
"level": 1,
"question": "def find_max_consecutive_ones(nums):\n max_ones = 0\n current_ones = 0\n for num in nums:\n if num == 1:\n current_ones += 1\n max_ones = max(max_ones, current_ones)\n else:\n current_ones = 0\n ... |
def longest_even_subarray_length(arr):
max_len = 0
current_len = 0
for num in arr:
if num % 2 == 0:
current_len += 1
else:
if current_len > max_len:
max_len = current_len
current_len = 0
# Check one last time after loop ends
if curr... | simplelr_Leetcode | [
{
"content": "Question:\n**[Question 4]:** Given an integer array `arr`, return the _length of the longest subarray that contains only even numbers_. Subarrays must be contiguous. For example, given the input `[1, 2, 4, 6, 3, 8, 10]`, the longest subarray of even numbers is `[2, 4, 6]` with a length of `3`.\nAn... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2852,
"level": 1,
"question": "**[Question 4]:** Given an integer array `arr`, return the _length of the longest subarray that contains only even numbers_. Subarrays must be contiguous. For example, given the input `[1, 2, 4, 6, 3, 8, 10]`, the longest subarray of even numbers is `[... |
import requests
cache = {}
def get_book_details(book_id: int, update_cache: bool = False) -> dict:
global cache
if update_cache:
try:
url = f"https://api.onlinebookstore.com/book/{book_id}"
response = requests.get(url, timeout=5)
if response.status_code == 200:
... | simplelr_Package | [
{
"content": "Question:\nYou are developing an application that interacts with an online bookstore's API. One of the requirements is to implement a caching mechanism to minimize the number of API requests. The cache should store the results of API calls and return the cached result for subsequent requests with ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2853,
"level": 1,
"question": "You are developing an application that interacts with an online bookstore's API. One of the requirements is to implement a caching mechanism to minimize the number of API requests. The cache should store the results of API calls and return the cached r... |
def reverse_integer(num):
if num == 0:
return 0
max_int = 2**31 - 1
min_int = -2**31
sign = 1
if num < 0:
sign = -1
abs_num = abs(num)
str_num = str(abs_num)
reversed_str = str_num[::-1]
if sign == -1:
reversed_str = '-' + reversed_str
... | simplelr_Filter | [
{
"content": "Question:\nWrite a program to reverse the digits of an integer. The integer can be positive or negative. Handle edge cases such as when the input is 0 or when reversing the digits causes the number to overflow.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2854,
"level": 1,
"question": "Write a program to reverse the digits of an integer. The integer can be positive or negative. Handle edge cases such as when the input is 0 or when reversing the digits causes the number to overflow.",
"split": "train"
} |
import math
def factorial(n):
if isinstance(n, float):
if not n.is_integer():
raise ValueError("n must be an integer or a whole number.")
n = int(n)
if not isinstance(n, int):
raise TypeError("n must be an integer or a whole number.")
if n < 0:
raise ValueError("... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the factorial of a given number. The function should be efficient and handle large numbers. Use Python's `math` library to achieve this.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2855,
"level": 1,
"question": "Write a function to calculate the factorial of a given number. The function should be efficient and handle large numbers. Use Python's `math` library to achieve this.",
"split": "train"
} |
def is_palindrome(s):
cleaned = ''.join([c.lower() for c in s if c.isalnum()])
return cleaned == cleaned[::-1]
| simplelr_Taco | [
{
"content": "Question:\nAlice recently developed a love for palindromes and she enjoys writing sentences that read the same forward and backward. She wants to write a program that helps her identify whether a given sentence is a palindrome. A sentence is considered a palindrome if, after removing all non-alpha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2856,
"level": 1,
"question": "Alice recently developed a love for palindromes and she enjoys writing sentences that read the same forward and backward. She wants to write a program that helps her identify whether a given sentence is a palindrome. A sentence is considered a palindro... |
def int_to_roman(n):
val = [
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(90, 'XC'),
(50, 'L'),
(40, 'XL'),
(10, 'X'),
(9, 'IX'),
(5, 'V'),
(4, 'IV'),
(1, 'I')
]
res = ''
for (i, r)... | simplelr_Leetcode | [
{
"content": "Question:\nWrite a function that takes an integer `n` and returns a string representing a Roman numeral corresponding to that integer. The integer `n` will be in the range from 1 to 3999.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2857,
"level": 1,
"question": "Write a function that takes an integer `n` and returns a string representing a Roman numeral corresponding to that integer. The integer `n` will be in the range from 1 to 3999.",
"split": "train"
} |
def is_balanced(expression: str) -> bool:
stack = []
pairs = { '(': ')', '{': '}', '[': ']' }
for char in expression:
if char in pairs:
stack.append(pairs[char])
else:
if not stack:
return False
top = stack.pop()
if top != char:... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Implement a Balanced Parentheses Checker using Stack\n\n#### Objective\nWrite a function to check if a given string of parentheses (of different types) is balanced. Parentheses are considered balanced if every opening bracket has a corresponding closing bracket and the pai... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2858,
"level": 1,
"question": "### Question: Implement a Balanced Parentheses Checker using Stack\n\n#### Objective\nWrite a function to check if a given string of parentheses (of different types) is balanced. Parentheses are considered balanced if every opening bracket has a corres... |
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2) | simplelr_Evol | [
{
"content": "Question:\nRefactor and optimize a recursive function:\n\nThe provided Python function aims to recursively calculate the nth term in the Fibonacci sequence. However, it is currently inefficient for large values of n due to excessive redundant calculations. Refactor the function to optimize its per... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2859,
"level": 1,
"question": "Refactor and optimize a recursive function:\n\nThe provided Python function aims to recursively calculate the nth term in the Fibonacci sequence. However, it is currently inefficient for large values of n due to excessive redundant calculations. Refact... |
def sum_except_self(lst):
total = sum(lst)
return [total - num for num in lst] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns a new list where each element is the sum of all the elements in the original list except the element at the same index. For example, if the input list is [1, 2, 3, 4], the output list should be [9, 8, 7, 6].\nAnswer:\nLet... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2860,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns a new list where each element is the sum of all the elements in the original list except the element at the same index. For example, if the input list is [1, 2, 3, 4], the output list sh... |
def sum_even_numbers(numbers):
return sum(num for num in numbers if num % 2 == 0) | simplelr_Filter | [
{
"content": "Question:\nThis is a simple programming puzzle:\n\nYou are given an array of integers. \nWrite a function that will return the sum of all the even numbers in the array.\n\nFor example:\n\nInput: [1, 2, 3, 4, 5, 6]\nOutput: 12\n\nHere's a solution in Python:\n\n```python\ndef sum_even_numbers(numbe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2861,
"level": 1,
"question": "This is a simple programming puzzle:\n\nYou are given an array of integers. \nWrite a function that will return the sum of all the even numbers in the array.\n\nFor example:\n\nInput: [1, 2, 3, 4, 5, 6]\nOutput: 12\n\nHere's a solution in Python:\n\n``... |
def levenshtein_distance(s1: str, s2: str) -> int:
"""
Calculate the minimum number of single-character edits (insertions, deletions, or substitutions)
required to change one string into the other.
Args:
s1 (str): The first string.
s2 (str): The second string.
Returns:
int... | simplelr_Filter | [
{
"content": "Question:\nIn this problem, we need to implement a function that can calculate the minimum number of operations needed to transform one string into another string using only the operations of inserting a character, deleting a character, or replacing a character. \n\nHere is the code with a small b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2862,
"level": 1,
"question": "In this problem, we need to implement a function that can calculate the minimum number of operations needed to transform one string into another string using only the operations of inserting a character, deleting a character, or replacing a character. ... |
from typing import List, Tuple
def word_frequency(strings: List[str]) -> List[Tuple[str, int]]:
freq_dict = {}
for string in strings:
words = string.split()
for word in words:
lower_word = word.lower()
if lower_word in freq_dict:
freq_dict[lower_word] += ... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are provided with a list of strings, each string composed of words separated by spaces. Your task is to implement an algorithm that will count the frequency of each word across all the strings, ignoring case. The return should be a case-insensitive sorted li... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2863,
"level": 1,
"question": "### Problem Statement\n\nYou are provided with a list of strings, each string composed of words separated by spaces. Your task is to implement an algorithm that will count the frequency of each word across all the strings, ignoring case. The return sho... |
def max_sum_substring(k, s):
n = len(s)
if k == 0 or n == 0 or k > n:
return 0
s_list = [int(c) for c in s]
current_sum = sum(s_list[:k])
max_sum = current_sum
for j in range(k, n):
current_sum = current_sum - s_list[j - k] + s_list[j]
if current_sum > max_sum:
... | simplelr_Filter | [
{
"content": "Question:\nIn this task, we consider a non-negative integer k and a binary string s of length n. We need to find the maximum sum of a substring of s that can be obtained by considering a substring of length k and adding all the 1's in that substring. The problem can be solved using a sliding windo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2864,
"level": 1,
"question": "In this task, we consider a non-negative integer k and a binary string s of length n. We need to find the maximum sum of a substring of s that can be obtained by considering a substring of length k and adding all the 1's in that substring. The problem ... |
import string
from collections import Counter
def read_file_and_get_common_words(filename):
word_counts = Counter()
with open(filename, 'r') as f:
for line in f:
line = line.lower()
words = line.split()
for word in words:
stripped_word = word.strip(s... | simplelr_Evol | [
{
"content": "Question:\nWrite a function in Python that reads a file and returns the ten most common words in the file along with their respective counts. Punctuation should be removed and word frequency should be case insensitive. The file will contain a mixture of words, spaces, and punctuation marks. If the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2865,
"level": 1,
"question": "Write a function in Python that reads a file and returns the ten most common words in the file along with their respective counts. Punctuation should be removed and word frequency should be case insensitive. The file will contain a mixture of words, sp... |
def largest_continuous_sum(arr):
if not arr:
return 0
max_sum = current_sum = arr[0]
for num in arr[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum | simplelr_Package | [
{
"content": "Question:\nDesign a function `largest_continuous_sum(arr)` that finds the maximum sum of any contiguous subarray within an array of integers. This problem is often known as \"Maximum Subarray Problem.\"\n\n### Requirements:\n1. Implement the function `largest_continuous_sum(arr)` that takes a sing... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2866,
"level": 1,
"question": "Design a function `largest_continuous_sum(arr)` that finds the maximum sum of any contiguous subarray within an array of integers. This problem is often known as \"Maximum Subarray Problem.\"\n\n### Requirements:\n1. Implement the function `largest_con... |
def memory_address_in_range(memory_address: int, start_offset: int, end_offset: int, target_value: int) -> bool:
"""
This function checks if a target memory address falls within a specific range.
The range is defined by a base memory address and start and end offsets from this address.
Args:
... | simplelr_Filter | [
{
"content": "Question:\nGiven a memory address, a start offset, and an end offset, determine whether a given memory address within a memory region falls within a specific range.\n\nSpecifically, consider the memory address 0x10000000 and memory offsets 0x100 and 0x200. If a value is between 0x10000000 + 0x100 ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2867,
"level": 1,
"question": "Given a memory address, a start offset, and an end offset, determine whether a given memory address within a memory region falls within a specific range.\n\nSpecifically, consider the memory address 0x10000000 and memory offsets 0x100 and 0x200. If a v... |
def two_sum(nums, target):
seen = {}
for index, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], index]
seen[num] = index
return None | simplelr_Filter | [
{
"content": "Question:\nThis is the problem I need to solve:\n\n**Problem:** Given an array of integers `nums` and an integer `target`, return *indices* of the two numbers such that they add up to `target`.\n\nYou may assume that each input would have **exactly one solution**, and you may not use the *same* el... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2868,
"level": 1,
"question": "This is the problem I need to solve:\n\n**Problem:** Given an array of integers `nums` and an integer `target`, return *indices* of the two numbers such that they add up to `target`.\n\nYou may assume that each input would have **exactly one solution**... |
def can_rearrange(arr):
arr.sort()
for i in range(len(arr) - 1):
if arr[i+1] - arr[i] > 1:
return False
return True | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr`, determine if it's possible to rearrange the elements of `arr` such that the absolute difference between any two consecutive elements is never greater than 1. Return `true` if such a rearrangement exists, and `false` otherwise.\nAnswer:\nLet's think step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2869,
"level": 1,
"question": "Given an array of integers `arr`, determine if it's possible to rearrange the elements of `arr` such that the absolute difference between any two consecutive elements is never greater than 1. Return `true` if such a rearrangement exists, and `false` ot... |
def count_ratings(ratings):
ratings_list = ratings.split()
rating_counts = {i: 0 for i in range(1, 6)}
for r_str in ratings_list:
try:
r = int(r_str)
if 1 <= r <= 5:
rating_counts[r] += 1
except ValueError:
pass
output = ' '.join(f'{i}:... | simplelr_Filter | [
{
"content": "Question:\nI have a string with a series of numbers (space separated) that represent ratings for a series of products. For example: \"4 3 5 3 5 1\". I want to write a function that will return a string with the count of each rating. \n\nThe function should:\n- Be named `count_ratings`\n- Accept on... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2870,
"level": 1,
"question": "I have a string with a series of numbers (space separated) that represent ratings for a series of products. For example: \"4 3 5 3 5 1\". I want to write a function that will return a string with the count of each rating. \n\nThe function should:\n- Be... |
def reverse_string(s):
chars = list(s)
left = 0
right = len(chars) - 1
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
return ''.join(chars) | simplelr_Filter | [
{
"content": "Question:\nImplement a function that takes in a string as input and reverses the order of its characters. The function should not use any built-in reverse functions or methods. Additionally, the function should have a time complexity of O(n), where n is the length of the input string. The function... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2871,
"level": 1,
"question": "Implement a function that takes in a string as input and reverses the order of its characters. The function should not use any built-in reverse functions or methods. Additionally, the function should have a time complexity of O(n), where n is the lengt... |
import torch
def special_computation(x: torch.Tensor) -> torch.Tensor:
modified_bessel = torch.special.i0(x)
logged = torch.log1p(modified_bessel)
erf_logged = torch.erf(logged)
return torch.sum(erf_logged)
| simplelr_Docs | [
{
"content": "Question:\n### PyTorch Special Functions Assessment\n\n**Objective:**\n\nYou are required to implement a function that computes a specialized mathematical result utilizing various functions from the `torch.special` module.\n\n### Problem Statement\n\nWrite a function `special_computation` that per... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2872,
"level": 1,
"question": "### PyTorch Special Functions Assessment\n\n**Objective:**\n\nYou are required to implement a function that computes a specialized mathematical result utilizing various functions from the `torch.special` module.\n\n### Problem Statement\n\nWrite a func... |
def count_unique_paths(m: int, n: int) -> int:
if m < 1 or n < 1:
return 0
# Initialize the DP table with zeros
dp = [[0 for _ in range(n)] for _ in range(m)]
# Fill the first row and first column with 1s
for i in range(m):
dp[i][0] = 1
for j in range(n):
dp[0][... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nYou are developing a robotic pathfinder for a grid-based maze. The robot can only move right or down. To help the robot plan its movements, you need to determine the number of unique paths from the top-left corner to the bottom-right corner of a given `m x n` grid.\n\n###... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2873,
"level": 1,
"question": "#### Scenario\nYou are developing a robotic pathfinder for a grid-based maze. The robot can only move right or down. To help the robot plan its movements, you need to determine the number of unique paths from the top-left corner to the bottom-right cor... |
def is_valid_password(password: str) -> bool:
"""
Checks if the given password meets the specified security policy.
The password must:
- Be at least 8 characters long
- Contain at least one uppercase letter
- Contain at least one lowercase letter
- Contain at least one digit
- Conta... | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that checks if a given string meets the password policy requirements? The requirements include having at least 8 characters, containing at least one uppercase letter, one lowercase letter, one digit, and one special character.\nAnswer:\nLet's think ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2874,
"level": 1,
"question": "How can I create a Python function that checks if a given string meets the password policy requirements? The requirements include having at least 8 characters, containing at least one uppercase letter, one lowercase letter, one digit, and one special c... |
def reverse_string(s):
return s[::-1]
print(reverse_string("hello world!")) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse a string, then use the function to reverse the string \"hello world!\"\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2875,
"level": 1,
"question": "Write a python function to reverse a string, then use the function to reverse the string \"hello world!\"",
"split": "train"
} |
import re
def replace_word(text: str, target: str, replacement: str, case_sensitive: bool) -> str:
if not target:
return text
pattern = r'\b{}\b'.format(re.escape(target))
if case_sensitive:
return re.sub(pattern, replacement, text)
else:
return re.sub(pattern, replacement, text... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are developing a word-processing application and need to implement a feature to find and replace a specified word in a given text with another word. This involves creating a function that efficiently processes the text to handle multiple occurrences of the target word ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2876,
"level": 1,
"question": "### Scenario\nYou are developing a word-processing application and need to implement a feature to find and replace a specified word in a given text with another word. This involves creating a function that efficiently processes the text to handle multi... |
def isSpecialNumber(num):
s = str(num)
for i in range(len(s) - 1):
current = s[i]
next_d = s[i+1]
current_even = (int(current) % 2) == 0
next_even = (int(next_d) % 2) == 0
if current_even == next_even:
return False
return True
| simplelr_Taco | [
{
"content": "Question:\nWrite a function to determine if a given number is a \"special number\" or not. A number is considered special if it satisfies the following conditions:\n\n1. The digits of the number alternate between odd and even. For example, 5 (odd) and 4 (even), or 3 (odd) and 8 (even).\n2. If ther... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2877,
"level": 1,
"question": "Write a function to determine if a given number is a \"special number\" or not. A number is considered special if it satisfies the following conditions:\n\n1. The digits of the number alternate between odd and even. For example, 5 (odd) and 4 (even), o... |
def isValidString(s):
prev_char = None
count_a = 0
for char in s:
if char == 'b':
if prev_char == 'b':
return False
prev_char = 'b'
count_a = 0
else:
count_a += 1
if count_a > 2:
return False
... | simplelr_Apps | [
{
"content": "Question:\nYou are given a string containing only characters 'a' and 'b'. The string is considered valid if there are no consecutive 'b's, and there are no more than two 'a's in a row. Write a method that takes the string as an argument and returns a boolean indicating whether the string is valid ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2878,
"level": 1,
"question": "You are given a string containing only characters 'a' and 'b'. The string is considered valid if there are no consecutive 'b's, and there are no more than two 'a's in a row. Write a method that takes the string as an argument and returns a boolean indi... |
import math
from typing import List
def generate_primes(n: int) -> List[int]:
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(math.sqrt(n)) + 1):
if sieve[i]:
sieve[i*i : n+1 : i] = [False] * len(sieve[i*i : n+1 : i])
primes... | simplelr_Algorithm | [
{
"content": "Question:\n### Prime Number Generator\n\nAs part of developing a mathematical toolkit, you need to implement a function that generates prime numbers up to a given integer `n`. A prime number is a natural number greater than 1 that is not divisible by any number other than 1 and itself.\n\n#### Obj... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2879,
"level": 1,
"question": "### Prime Number Generator\n\nAs part of developing a mathematical toolkit, you need to implement a function that generates prime numbers up to a given integer `n`. A prime number is a natural number greater than 1 that is not divisible by any number o... |
from collections import deque
def find_task_order(n, dependencies):
# Initialize the graph and in-degree list
graph = [[] for _ in range(n)]
in_degree = [0] * n
# Build the graph and update in-degrees
for a, b in dependencies:
graph[a].append(b)
in_degree[b] += 1
# Ini... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `n` tasks labeled with unique integers from 0 to `n-1` and a list of `dependencies` where each dependency is a pair `(a, b)` indicating that task `a` must be completed before task `b` can be started. \n\nWrite a function that returns the order in which the tasks ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2880,
"level": 1,
"question": "You are given a list of `n` tasks labeled with unique integers from 0 to `n-1` and a list of `dependencies` where each dependency is a pair `(a, b)` indicating that task `a` must be completed before task `b` can be started. \n\nWrite a function that re... |
def swap_values(a, b):
a, b = b, a
return a, b | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to swap the values of two integers without using a temporary variable. How can this be achieved in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2881,
"level": 1,
"question": "Write a function to swap the values of two integers without using a temporary variable. How can this be achieved in Python?",
"split": "train"
} |
from datetime import datetime
def analyze_user_activity(activity_log, start_date, end_date):
# Convert start and end dates to date objects
start_date_obj = datetime.strptime(start_date, "%Y-%m-%d").date()
end_date_obj = datetime.strptime(end_date, "%Y-%m-%d").date()
# Initialize dictionaries to co... | simplelr_Package | [
{
"content": "Question:\n**Context:**\n\nYou are developing a feature for an e-commerce platform’s recommendation system. The platform keeps track of user activities, including viewing and purchasing products. Your task is to build a function that processes user activity data and identifies the most viewed and ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2882,
"level": 1,
"question": "**Context:**\n\nYou are developing a feature for an e-commerce platform’s recommendation system. The platform keeps track of user activities, including viewing and purchasing products. Your task is to build a function that processes user activity data ... |
def minCostClimbingStairs(nums):
if not nums:
return 0
n = len(nums)
if n == 1:
return nums[0]
if n == 2:
return min(nums[0], nums[1])
prev_prev = nums[0]
prev = nums[1]
for i in range(2, n):
current = nums[i] + min(prev, prev_prev)
prev_prev... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers `nums` where each element represents the cost of a step in a staircase. Each step `i` has a cost `nums[i]` associated with it. You can start from step `0` or step `1`. Once you pay the cost at a step, you can move either one or two steps forward. Return ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2883,
"level": 1,
"question": "You are given a list of integers `nums` where each element represents the cost of a step in a staircase. Each step `i` has a cost `nums[i]` associated with it. You can start from step `0` or step `1`. Once you pay the cost at a step, you can move eithe... |
def find_nth_digit(n: int) -> int:
digits = 1
count = 9
start = 1
while n > digits * count:
n -= digits * count
digits += 1
count *= 10
start *= 10
number = start + (n - 1) // digits
return int(str(number)[(n - 1) % digits]) | simplelr_Data_Structure | [
{
"content": "Question:\nGiven a sequence of natural numbers written in a concatenated form as '123456789101112...', your task is to write a function `find_nth_digit(n)` that returns the nth digit in this sequence. Consider 1-based indexing for the sequence.\n\n### Function Signature\n```python\ndef find_nth_di... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2884,
"level": 1,
"question": "Given a sequence of natural numbers written in a concatenated form as '123456789101112...', your task is to write a function `find_nth_digit(n)` that returns the nth digit in this sequence. Consider 1-based indexing for the sequence.\n\n### Function Si... |
def two_sum(nums, target):
num_dict = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_dict:
return [num_dict[complement], i]
num_dict[num] = i
return [] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to solve the \"Two Sum\" problem. The Two Sum problem is a classic example in algorithms where given an array of integers and a target integer, you need to find two numbers such that they add up to the target. Your function should return the indices of the two nu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2885,
"level": 1,
"question": "Write a python function to solve the \"Two Sum\" problem. The Two Sum problem is a classic example in algorithms where given an array of integers and a target integer, you need to find two numbers such that they add up to the target. Your function shou... |
def minimizeFines(P, projects):
total_fines = 0
for project in projects:
current_time = 0
for j in range(project['N_i']):
current_time += project['times'][j]
if current_time > project['deadlines'][j]:
total_fines += project['fines'][j]
return total_fin... | simplelr_Taco | [
{
"content": "Question:\nA company wants to design a scheduling system to manage its projects more efficiently. Each project has a number of tasks that need to be completed in sequence. Each task has a required time for completion. Furthermore, some tasks have deadlines, and if a task is completed after its dea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2886,
"level": 1,
"question": "A company wants to design a scheduling system to manage its projects more efficiently. Each project has a number of tasks that need to be completed in sequence. Each task has a required time for completion. Furthermore, some tasks have deadlines, and i... |
import html
def convert_html_entities(text):
"""
Converts HTML entities in a string to their corresponding characters.
"""
try:
# Attempt to convert HTML entities
converted_text = html.unescape(text)
return converted_text
except Exception as e:
# Handle any potential... | simplelr_Filter | [
{
"content": "Question:\nI am building a new data pipeline and I need to determine if a string field from a data source contains HTML entities and then convert them to their corresponding characters. \n\nFor example if a string contains `<` it should be replaced with `<` and `>` should be replaced with `>... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2887,
"level": 1,
"question": "I am building a new data pipeline and I need to determine if a string field from a data source contains HTML entities and then convert them to their corresponding characters. \n\nFor example if a string contains `<` it should be replaced with `<` an... |
def reverse_list(arr):
return arr[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to swap elements of a list in reverse order. For example, given the list [1, 2, 3, 4, 5], the function should return [5, 4, 3, 2, 1].\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2888,
"level": 1,
"question": "Write a python function to swap elements of a list in reverse order. For example, given the list [1, 2, 3, 4, 5], the function should return [5, 4, 3, 2, 1].",
"split": "train"
} |
def longest_consecutive_subsequence(arr):
dp = {}
max_len = 0
for num in arr:
prev = num - 1
if prev in dp:
dp[num] = dp[prev] + 1
else:
dp[num] = 1
if dp[num] > max_len:
max_len = dp[num]
return max_len | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes an array of integers and returns the length of the longest subsequence where the difference between consecutive elements is consistent and exactly equal to one.\n\n## Example\nIf the array is `[1, 2, 3, 5, 6, 7, 8, 10]`, then the longest subsequence with cons... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2889,
"level": 1,
"question": "Write a function that takes an array of integers and returns the length of the longest subsequence where the difference between consecutive elements is consistent and exactly equal to one.\n\n## Example\nIf the array is `[1, 2, 3, 5, 6, 7, 8, 10]`, the... |
def count_down(n):
if n <= 0:
return
print(n)
count_down(n - 1) | simplelr_Filter | [
{
"content": "Question:\n### Introduction to Recursion\n#### Overview of Recursion\nRecursion is a programming concept where a function invokes itself in its definition. This allows the function to be repeated several times, since it can call itself during its execution. The process of recursion has two main co... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2890,
"level": 1,
"question": "### Introduction to Recursion\n#### Overview of Recursion\nRecursion is a programming concept where a function invokes itself in its definition. This allows the function to be repeated several times, since it can call itself during its execution. The p... |
from collections import Counter
def can_form_palindrome(s: str) -> bool:
counts = Counter(s)
odd_count = sum(1 for count in counts.values() if count % 2 != 0)
return odd_count == 0 if len(s) % 2 == 0 else odd_count == 1 | simplelr_Algorithm | [
{
"content": "Question:\nPalindrome Permutation\n\n#### Context\nA palindrome is a word or phrase that reads the same forwards and backwards, ignoring spaces, punctuation, and capitalization. A permutation is a rearrangement of letters. Given a string, determine if any permutation of it forms a palindrome.\n\n#... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2891,
"level": 1,
"question": "Palindrome Permutation\n\n#### Context\nA palindrome is a word or phrase that reads the same forwards and backwards, ignoring spaces, punctuation, and capitalization. A permutation is a rearrangement of letters. Given a string, determine if any permuta... |
def two_sum(nums, target):
seen = {}
for index, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], index]
seen[num] = index
return [] | simplelr_Filter | [
{
"content": "Question:\nThis is the problem statement:\n\nYou are given an array of integers nums and an integer target.\n\nReturn indices of the two numbers such that they add up to target.\n\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n\nYou ca... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2892,
"level": 1,
"question": "This is the problem statement:\n\nYou are given an array of integers nums and an integer target.\n\nReturn indices of the two numbers such that they add up to target.\n\nYou may assume that each input would have exactly one solution, and you may not us... |
import heapq
def shortestPath(V, E, edges, S, D):
# Build adjacency list
adj = [[] for _ in range(V)]
for u, v, w in edges:
adj[u].append((v, w))
# Initialize distances
INF = float('inf')
dist = [INF] * V
dist[S] = 0
# Priority queue
heap = []
heapq.heappush(he... | simplelr_Taco | [
{
"content": "Question:\nGiven a directed graph with V vertices and E edges, where each edge has a weight associated with it. Find the shortest distance from the source vertex S to the destination vertex D. If there is no path between S and D, return -1.\n\nExample 1:\nInput:\nV = 6, E = 8\nEdges = [(0, 1, 2), ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2893,
"level": 1,
"question": "Given a directed graph with V vertices and E edges, where each edge has a weight associated with it. Find the shortest distance from the source vertex S to the destination vertex D. If there is no path between S and D, return -1.\n\nExample 1:\nInput:\... |
def select_words(s, n):
vowels = {'a', 'e', 'i', 'o', 'u'}
words = s.split()
result = []
for word in words:
consonant_count = 0
for char in word:
if char.lower() not in vowels:
consonant_count += 1
if consonant_count == n:
result.append(wor... | simplelr_Filter | [
{
"content": "Question:\nWrite a python function called `select_words` that takes a string and a positive integer `n` as arguments and returns a list of all words from the string that contain exactly `n` consonants. The string will consist of words separated by spaces and will not exceed 100 characters. The out... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2894,
"level": 1,
"question": "Write a python function called `select_words` that takes a string and a positive integer `n` as arguments and returns a list of all words from the string that contain exactly `n` consonants. The string will consist of words separated by spaces and will... |
import random
def coin_flip():
return random.choice(["Heads", "Tails"]) | simplelr_Filter | [
{
"content": "Question:\nHere is a Python function that uses the `random` module to simulate a coin flip:\n\n```python\nimport random\ndef coin_flip():\n if random.random() < 0.5:\n return \"Heads\"\n else:\n return \"Tails\"\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2895,
"level": 1,
"question": "Here is a Python function that uses the `random` module to simulate a coin flip:\n\n```python\nimport random\ndef coin_flip():\n if random.random() < 0.5:\n return \"Heads\"\n else:\n return \"Tails\"",
"split": "train"
} |
def sum_divisible_by_3_and_5(n):
if n < 15:
return 0
k = n // 15
return (15 * k * (k + 1)) // 2 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that sums up all numbers between 1 and n (where n is a positive integer) that are divisible by both 3 and 5.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2896,
"level": 1,
"question": "Create a function that sums up all numbers between 1 and n (where n is a positive integer) that are divisible by both 3 and 5.",
"split": "train"
} |
def contains_all_alphabet(s):
alphabet = set()
for c in s:
if c.isalpha():
lower_c = c.lower()
alphabet.add(lower_c)
return len(alphabet) == 26
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that receives a string and checks if it contains all letters of the alphabet at least once. The function should return a boolean value: `true` if the string contains all the letters from 'a' to 'z', and `false` otherwise. \n\nNote: The input string can include any chara... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2897,
"level": 1,
"question": "Write a function that receives a string and checks if it contains all letters of the alphabet at least once. The function should return a boolean value: `true` if the string contains all the letters from 'a' to 'z', and `false` otherwise. \n\nNote: The... |
import pandas as pd
import time
def sales_analysis(df):
start_time = time.time()
total = df['Sales'].sum()
average = df['Sales'].mean()
max_sale = df['Sales'].max()
max_index = df['Sales'].idxmax()
min_sale = df['Sales'].min()
min_index = df['Sales'].idxmin()
end_time = time.time()
... | simplelr_Package | [
{
"content": "Question:\nYou are given a DataFrame `df` that contains a column labeled 'Sales', which includes the sale amounts for various transactions in a store. Your task is to create a function called `sales_analysis(df)` that calculates and displays the following statistics:\n1. Total sales amount.\n2. Av... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2898,
"level": 1,
"question": "You are given a DataFrame `df` that contains a column labeled 'Sales', which includes the sale amounts for various transactions in a store. Your task is to create a function called `sales_analysis(df)` that calculates and displays the following statist... |
def count_subsequences(arr, target):
n = len(arr)
dp = [[0] * (target + 1) for _ in range(n + 1)]
dp[0][0] = 1 # Base case: one way to make sum 0 with 0 elements
for i in range(1, n + 1):
num = arr[i - 1]
for j in range(target + 1):
dp[i][j] = dp[i - 1][j]
i... | simplelr_Filter | [
{
"content": "Question:\ndef count_subsequences(arr, target):\n \"\"\"\n Counts the number of subsequences in 'arr' that sum up to 'target'.\n \n Parameters:\n arr (list): A list of integers.\n target (int): The target sum.\n \n Returns:\n int: The number of subsequences that sum up t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2899,
"level": 1,
"question": "def count_subsequences(arr, target):\n \"\"\"\n Counts the number of subsequences in 'arr' that sum up to 'target'.\n \n Parameters:\n arr (list): A list of integers.\n target (int): The target sum.\n \n Returns:\n int: The n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.