target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
def can_transform_by_reversing_substring(s, t):
if len(s) != len(t):
return False
if s == t:
return True
from collections import Counter
if Counter(s) != Counter(t):
return False
left = 0
while left < len(s) and s[left] == t[left]:
left += 1
right = len(s) - 1... | simplelr_Leetcode | [
{
"content": "Question:\nGiven two strings `s` and `t` consisting of only lowercase letters, you need to determine if you can convert `s` to `t` using the following operations exactly once:\n\n1. Choose a non-empty substring of `s` and reverse it.\n\nReturn `true` if it is possible to transform `s` into `t` usi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3200,
"level": 1,
"question": "Given two strings `s` and `t` consisting of only lowercase letters, you need to determine if you can convert `s` to `t` using the following operations exactly once:\n\n1. Choose a non-empty substring of `s` and reverse it.\n\nReturn `true` if it is pos... |
def validate_subsequence(arr, subseq):
i = j = 0
while i < len(arr) and j < len(subseq):
if arr[i] == subseq[j]:
j += 1
i += 1
return j == len(subseq)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `validate_subsequence(arr, subseq)` that takes in two arrays of integers. The function should return `true` if the provided subsequence is a valid subsequence of the main array, and `false` otherwise.\n\nA subsequence of an array is a set of numbers that aren’t necessar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3201,
"level": 1,
"question": "Write a function `validate_subsequence(arr, subseq)` that takes in two arrays of integers. The function should return `true` if the provided subsequence is a valid subsequence of the main array, and `false` otherwise.\n\nA subsequence of an array is a ... |
def contains_nearby_almost_duplicate(arr, x):
n = len(arr)
if n < 2 or x == 0:
return False
for i in range(n):
start = max(0, i - x)
end = min(n - 1, i + x)
for j in range(start, end + 1):
if j != i and abs(arr[i] - arr[j]) <= x:
return True
re... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `arr` and an integer `x`, determine if there exist two distinct indices `i` and `j` in the array such that `|arr[i] - arr[j]| <= x` and `|i - j| <= x`. Return `true` if such indices exist, and `false` otherwise.\nAnswer:\nLet's think step by step.\n",
"role": ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3202,
"level": 1,
"question": "Given an integer array `arr` and an integer `x`, determine if there exist two distinct indices `i` and `j` in the array such that `|arr[i] - arr[j]| <= x` and `|i - j| <= x`. Return `true` if such indices exist, and `false` otherwise.",
"split": "tra... |
import bisect
def minimum_moves_to_sort(heights):
tails = []
for x in heights:
idx = bisect.bisect_right(tails, x)
if idx == len(tails):
tails.append(x)
else:
tails[idx] = x
return len(heights) - len(tails) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `heights`, where `heights[i]` represents the height of the `i-th` student in a class. The students are initially arranged from left to right in random order. You need to arrange the students in non-decreasing order of their heights. Return the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3203,
"level": 1,
"question": "You are given a **0-indexed** integer array `heights`, where `heights[i]` represents the height of the `i-th` student in a class. The students are initially arranged from left to right in random order. You need to arrange the students in non-decreasing... |
def min_cost_path(grid):
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = grid[0][0]
# Fill the first row
for j in range(1, n):
dp[0][j] = dp[0][j-1] + grid[0][j]
# Fill the first column
for i in... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a 2-dimensional integer matrix where each element represents the cost of a cell in a grid, you are initially positioned at the top-left corner of the grid. You can only move right or down from a cell. Write a function to return the minimum cost path sum to reach the bottom-right c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3204,
"level": 1,
"question": "Given a 2-dimensional integer matrix where each element represents the cost of a cell in a grid, you are initially positioned at the top-left corner of the grid. You can only move right or down from a cell. Write a function to return the minimum cost p... |
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_Filter | [
{
"content": "Question:\nWrite me a Python function to calculate the nth Fibonacci number using recursion. Then, optimize this function using memoization to improve performance for large values of n. Explain the benefits of using memoization in this context.\nAnswer:\nLet's think step by step.\n",
"role": "... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3205,
"level": 1,
"question": "Write me a Python function to calculate the nth Fibonacci number using recursion. Then, optimize this function using memoization to improve performance for large values of n. Explain the benefits of using memoization in this context.",
"split": "trai... |
def word_break(s, words):
if not s:
return True
if not words:
return False
word_set = set(words)
word_lengths = set(len(word) for word in words)
max_len = max(word_lengths) if word_lengths else 0
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
for i in range(... | simplelr_Apps | [
{
"content": "Question:\nGiven a string `s` and a list of words `words`, determine if `s` can be segmented into a space-separated sequence of one or more dictionary words from the list `words`. Return `true` if it can be segmented, otherwise return `false`.\n\nExample:\n```text\ns = \"leetcode\"\nwords = [\"lee... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3206,
"level": 1,
"question": "Given a string `s` and a list of words `words`, determine if `s` can be segmented into a space-separated sequence of one or more dictionary words from the list `words`. Return `true` if it can be segmented, otherwise return `false`.\n\nExample:\n```tex... |
def maxNonOverlappingIntervals(intervals):
if not intervals:
return 0
intervals.sort(key=lambda x: x[1])
count = 1
last_end = intervals[0][1]
for i in range(1, len(intervals)):
if intervals[i][0] >= last_end:
count += 1
last_end = intervals[i][1]
return co... | simplelr_Leetcode | [
{
"content": "Question:\nA company is scheduling interviews for a list of applicants. Each applicant has a start time and an end time represented by a pair of integers `[start, end]`, where `start` is the time the interview starts and `end` is the time the interview ends. The goal is to determine the maximum nu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3207,
"level": 1,
"question": "A company is scheduling interviews for a list of applicants. Each applicant has a start time and an end time represented by a pair of integers `[start, end]`, where `start` is the time the interview starts and `end` is the time the interview ends. The ... |
def sum_of_odds_in_range(start: int, end: int) -> int:
total = 0
for num in range(start, end + 1):
if num % 2 == 1:
total += num
return total | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function called `sum_of_odds_in_range` that computes the sum of all odd integers within a specified range inclusive of the boundaries. This problem aids in familiarizing you with basic iteration and conditional checks in Python.\n\nHere’s the detailed descrip... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3208,
"level": 1,
"question": "You are required to write a function called `sum_of_odds_in_range` that computes the sum of all odd integers within a specified range inclusive of the boundaries. This problem aids in familiarizing you with basic iteration and conditional checks in Pyt... |
def to_binary(n):
if n == 0:
return "0"
is_negative = False
if n < 0:
is_negative = True
n = abs(n)
binary_digits = []
while n > 0:
remainder = n % 2
binary_digits.append(str(remainder))
n = n // 2
binary_str = ''.join(reversed(binary_digits))
... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that converts a given number to its corresponding binary representation in string format.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3209,
"level": 1,
"question": "Create a function that converts a given number to its corresponding binary representation in string format.",
"split": "train"
} |
def sum_even_numbers(lst):
if not lst:
return 0
else:
if lst[0] % 2 == 0:
return lst[0] + sum_even_numbers(lst[1:])
else:
return sum_even_numbers(lst[1:]) | simplelr_Filter | [
{
"content": "Question:\nBased on the following instruction, write a code snippet that implements a function to calculate the sum of all even numbers in a list using recursion.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3210,
"level": 1,
"question": "Based on the following instruction, write a code snippet that implements a function to calculate the sum of all even numbers in a list using recursion.",
"split": "train"
} |
def find_majority_element(arr):
if not arr:
return -1
# First pass to find the candidate for majority element
count = 0
candidate = None
for num in arr:
if count == 0:
candidate = num
count = 1
else:
if num == candidate:
... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that finds the majority element in an array. The majority element is the element that appears more than half the time within the array. If no majority element exists, return -1. The function should be efficient and consider both time and space complexity.\nAnswer:\nLet... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3211,
"level": 1,
"question": "Create a function that finds the majority element in an array. The majority element is the element that appears more than half the time within the array. If no majority element exists, return -1. The function should be efficient and consider both time ... |
def is_palindrome(s):
s_lower = s.lower()
return s_lower == s_lower[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if a given string is a palindrome. A palindrome is a string that reads the same backward as forward, e.g., \"radar\". The function should return `true` if the string is a palindrome and `false` otherwise. The function should be case-insensitive.\nAnswer:\nL... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3212,
"level": 1,
"question": "Create a function that checks if a given string is a palindrome. A palindrome is a string that reads the same backward as forward, e.g., \"radar\". The function should return `true` if the string is a palindrome and `false` otherwise. The function shou... |
def check_greater_than_ten(numbers):
for num in numbers:
if num > 10:
return num
return None | simplelr_Filter | [
{
"content": "Question:\nWrite a callback function to check if a list of numbers contain any number greater than 10 and return the first occurrence of such number. If no such number exists, then return None.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3213,
"level": 1,
"question": "Write a callback function to check if a list of numbers contain any number greater than 10 and return the first occurrence of such number. If no such number exists, then return None.",
"split": "train"
} |
def all_pairs(nums):
if len(nums) < 2:
return []
result = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
result.append((nums[i], nums[j]))
return result | simplelr_Filter | [
{
"content": "Question:\nGiven a list of numbers, write a function that returns all possible pairs of numbers in the list.\n\nFor example, given the input [1, 2, 3, 4], the function should return [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)].\n\nCan you write this function in Python?\nAnswer:\nLet's think st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3214,
"level": 1,
"question": "Given a list of numbers, write a function that returns all possible pairs of numbers in the list.\n\nFor example, given the input [1, 2, 3, 4], the function should return [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)].\n\nCan you write this function ... |
import os
def get_last_path_component(path):
if not path:
return ""
normalized = os.path.normpath(path)
return os.path.basename(normalized) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string representing a file path and returns the last component of the path, which is the file name or directory name. Additionally, the function should handle special cases such as trailing slashes and empty paths.\nAnswer:\nLet's think step by step.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3215,
"level": 1,
"question": "Write a Python function that takes a string representing a file path and returns the last component of the path, which is the file name or directory name. Additionally, the function should handle special cases such as trailing slashes and empty paths."... |
from datetime import datetime, timedelta
def longest_commit_streak(timestamps: list[str]) -> int:
# Convert the string timestamps to datetime objects for easier manipulation.
dates = [datetime.strptime(date, '%Y-%m-%d') for date in timestamps]
# Initialize variables for tracking the longest streak.
... | simplelr_Algorithm | [
{
"content": "Question:\n**Scenario**:\nA software development company uses a version control system where feature branches are created for new additions and bug fixes. Developers commit changes to these branches, which are recorded as timestamps sorted in ascending order. Your task is to identify the longest p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3216,
"level": 1,
"question": "**Scenario**:\nA software development company uses a version control system where feature branches are created for new additions and bug fixes. Developers commit changes to these branches, which are recorded as timestamps sorted in ascending order. You... |
def run_length_encode(s: str) -> str:
if not s:
return ""
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 ... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\nYou are required to implement a function that encodes a given string using Run-Length Encoding (RLE). Run-Length Encoding is a basic form of data compression in which consecutive occurrences of the same character are replaced with a single character followed by t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3217,
"level": 1,
"question": "### Problem Statement:\nYou are required to implement a function that encodes a given string using Run-Length Encoding (RLE). Run-Length Encoding is a basic form of data compression in which consecutive occurrences of the same character are replaced wi... |
import torch
def complex_tensor_operations(real_part: torch.Tensor, imag_part: torch.Tensor) -> dict:
# 1. Create the complex tensor
complex_tensor = torch.complex(real_part, imag_part)
# 2. Extract the real and imaginary parts
tensor_real = complex_tensor.real
tensor_imag = complex_tensor.ima... | simplelr_Docs | [
{
"content": "Question:\n### Complex Tensor Operations with PyTorch\n\n**Objective:**\nCreate a function that performs a series of operations on a complex tensor using PyTorch. The function should demonstrate your understanding of basic and advanced complex tensor operations, including creation, manipulation, a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3218,
"level": 1,
"question": "### Complex Tensor Operations with PyTorch\n\n**Objective:**\nCreate a function that performs a series of operations on a complex tensor using PyTorch. The function should demonstrate your understanding of basic and advanced complex tensor operations, ... |
def all_unique(lst):
return len(lst) == len(set(lst)) | simplelr_Filter | [
{
"content": "Question:\nCan you write a Python function that checks if all elements in a list are unique? The function should return `True` if all elements are unique and `False` if there are any duplicates. The list can contain numbers, strings, or a mix of both. The function should be efficient and work for ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3219,
"level": 1,
"question": "Can you write a Python function that checks if all elements in a list are unique? The function should return `True` if all elements are unique and `False` if there are any duplicates. The list can contain numbers, strings, or a mix of both. The functio... |
def k_most_frequent_elements(nums: list[int], k: int) -> list[int]:
if not nums:
raise ValueError("Invalid input: nums must not be empty")
n = len(nums)
if k < 1 or k > n:
raise ValueError("Invalid value for k")
freq = {}
first_occurrence = {}
for idx, num in enume... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n**K-Most Frequent Elements**\n\nGiven a list of integers, write a Python function to return the `k` most frequent elements. The function should return the elements in descending order of frequency. If two elements have the same frequency, order them by their first occurren... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3220,
"level": 1,
"question": "### Question\n**K-Most Frequent Elements**\n\nGiven a list of integers, write a Python function to return the `k` most frequent elements. The function should return the elements in descending order of frequency. If two elements have the same frequency,... |
def longest_increasing_subsequence(s: str) -> str:
if not s:
return ""
n = len(s)
dp = [(1, -1) for _ in range(n)] # (length, previous index)
for i in range(n):
for j in range(i):
if s[j] < s[i]:
if dp[j][0] + 1 > dp[i][0]:
dp[i]... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with implementing a function that determines the longest subsequence in a given string where each subsequent character is lexicographically greater than the previous one. The problem is similar to finding the longest increasing subsequence in numerical arrays but applies ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3221,
"level": 1,
"question": "You are tasked with implementing a function that determines the longest subsequence in a given string where each subsequent character is lexicographically greater than the previous one. The problem is similar to finding the longest increasing subsequen... |
def filter_common_elements(list1, list2):
set2 = set(list2)
result = []
seen = set()
for item in list1:
if item in set2 and item not in seen:
result.append(item)
seen.add(item)
return result | simplelr_Filter | [
{
"content": "Question:\nGiven two lists, `list1` and `list2`, write a Python code to filter elements in `list1` which are also present in `list2`. The resulting list should only contain the common elements found in both lists, but without duplicates and in the order they appear in `list1`.\nAnswer:\nLet's thin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3222,
"level": 1,
"question": "Given two lists, `list1` and `list2`, write a Python code to filter elements in `list1` which are also present in `list2`. The resulting list should only contain the common elements found in both lists, but without duplicates and in the order they appe... |
from collections import deque
from typing import List, Tuple
def is_path_exists(n: int, edges: List[Tuple[int, int]], source: int, target: int) -> bool:
if source == target:
return True
if source < 0 or source >= n or target < 0 or target >= n:
return False
adj = [[] for _ in rang... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Problem:\nYou are given a directed graph with `n` vertices labeled from `0` to `n-1`. Your task is to implement a function `is_path_exists(n, edges, source, target)` that determines if there is a path between the given source and target vertex.\n\n#### Function Signature:\n```pytho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3223,
"level": 1,
"question": "#### Problem:\nYou are given a directed graph with `n` vertices labeled from `0` to `n-1`. Your task is to implement a function `is_path_exists(n, edges, source, target)` that determines if there is a path between the given source and target vertex.\n\... |
def findPair(arr, target):
seen = {}
for i, num in enumerate(arr):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers and a target sum, determine if any two distinct integers in the array add up to the target sum. If such a pair exists, return the indices of the two numbers as a list of two integers. If no such pair exists, return an empty list.\n\nFunction Description \n\nC... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3224,
"level": 1,
"question": "Given an array of integers and a target sum, determine if any two distinct integers in the array add up to the target sum. If such a pair exists, return the indices of the two numbers as a list of two integers. If no such pair exists, return an empty l... |
def convert_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9 | simplelr_Filter | [
{
"content": "Question:\nThis code snippet defines a function called `convert_to_celsius` that takes one argument: a temperature in Fahrenheit. The function should return the temperature converted to Celsius.\n\n ```python\n def convert_to_celsius(fahrenheit):\n\n # Your code here\n ```\n\n Can you implement ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3225,
"level": 1,
"question": "This code snippet defines a function called `convert_to_celsius` that takes one argument: a temperature in Fahrenheit. The function should return the temperature converted to Celsius.\n\n ```python\n def convert_to_celsius(fahrenheit):\n\n # Your cod... |
def find_substring(main_string, sub_string):
return main_string.lower().find(sub_string.lower()) | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a specific programming problem I'm facing? I'm working on a project that requires me to create a function in Python that finds the first occurrence of a substring within a string, but with a twist. The function should be case-insensitive, and it should return the in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3226,
"level": 1,
"question": "Can you help me with a specific programming problem I'm facing? I'm working on a project that requires me to create a function in Python that finds the first occurrence of a substring within a string, but with a twist. The function should be case-insen... |
def num_decompositions(n: int) -> int:
if n == 0:
return 1
dp = [[0] * (n + 1) for _ in range(n + 1)]
for j in range(n + 1):
dp[0][j] = 1
for i in range(1, n + 1):
for j in range(1, n + 1):
if j > i:
dp[i][j] = dp[i][i]
else:
... | simplelr_Data_Structure | [
{
"content": "Question:\nImplement a function to determine the number of ways a given positive integer can be decomposed into a sum of non-negative integers. The function should be optimized for performance and use dynamic programming concepts.\n\n#### Function Signature:\n```python\ndef num_decompositions(n: i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3227,
"level": 1,
"question": "Implement a function to determine the number of ways a given positive integer can be decomposed into a sum of non-negative integers. The function should be optimized for performance and use dynamic programming concepts.\n\n#### Function Signature:\n```... |
def most_frequent_letter(s: str) -> str:
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
max_count = 0
max_char = ''
for char, count in freq.items():
if count > max_count:
max_count = count
ma... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are given a string containing only lowercase letters and you need to calculate the frequency of each letter in the string. Your task is to find the letter that occurs the most frequently. If there are multiple letters with the same highest frequency, return the lexicog... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3228,
"level": 1,
"question": "### Scenario\nYou are given a string containing only lowercase letters and you need to calculate the frequency of each letter in the string. Your task is to find the letter that occurs the most frequently. If there are multiple letters with the same hi... |
def longest_substring_with_k_distinct_chars(s: str, k: int) -> int:
max_length = 0
freq = {}
left = 0
for right in range(len(s)):
char = s[right]
if char in freq:
freq[char] += 1
else:
freq[char] = 1
# Ensure the number of distinct characters doe... | simplelr_Codeforces | [
{
"content": "Question:\nBob is organizing a string generator competition with his friends. The task is to generate strings that meet certain conditions. Each participant is given a string $$s$$ consisting solely of lowercase English letters. The goal is to find the length of the longest substring of $$s$$ such... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3229,
"level": 1,
"question": "Bob is organizing a string generator competition with his friends. The task is to generate strings that meet certain conditions. Each participant is given a string $$s$$ consisting solely of lowercase English letters. The goal is to find the length of ... |
def unique_paths_with_obstacles(obstacleGrid):
m = len(obstacleGrid)
if m == 0:
return 0
n = len(obstacleGrid[0])
dp = [[0] * n for _ in range(m)]
if obstacleGrid[0][0] == 1:
return 0
dp[0][0] = 1
for i in range(m):
for j in range(n):
if i == 0 a... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the total number of distinct paths from the top-left corner to the bottom-right corner of a grid, where you can only move down or right. The grid might contain obstacles that you cannot step on. How can you solve this problem using dynamic programming?\nAns... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3230,
"level": 1,
"question": "Write a function to calculate the total number of distinct paths from the top-left corner to the bottom-right corner of a grid, where you can only move down or right. The grid might contain obstacles that you cannot step on. How can you solve this prob... |
def convert_to_minutes(time):
period = time[-2:].upper()
time_part = time[:-2]
hour_str, minute_str = time_part.split(':')
hour = int(hour_str)
minute = int(minute_str)
if period == 'AM':
if hour == 12:
hour = 0
else:
if hour != 12:
hour += 12
... | simplelr_Apps | [
{
"content": "Question:\nA company is implementing a digital scheduling system where meetings are scheduled based on a 12-hour clock format. However, to avoid scheduling conflicts, the system needs to convert all times into minutes past midnight.\n\nPlease complete the function `convert_to_minutes(time)` that t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3231,
"level": 1,
"question": "A company is implementing a digital scheduling system where meetings are scheduled based on a 12-hour clock format. However, to avoid scheduling conflicts, the system needs to convert all times into minutes past midnight.\n\nPlease complete the functio... |
from collections import defaultdict
def count_unique_indexes(records):
category_indexes = defaultdict(set)
for category, index in records:
category_indexes[category].add(index)
return {cat: len(indexes) for cat, indexes in category_indexes.items()} | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nIn a database system, indexing plays a crucial role in efficiently retrieving data. One of the main tasks is determining the number of unique indexes for each category in a given dataset. This data is represented as a list of tuples, wher... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3232,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario\nIn a database system, indexing plays a crucial role in efficiently retrieving data. One of the main tasks is determining the number of unique indexes for each category in a given dataset. This data is re... |
def min_clear_out_days(D, deliveries, capacity):
if not deliveries:
return 0
current_sum = 0
groups = 1
for delivery in deliveries:
if current_sum + delivery > capacity:
groups += 1
current_sum = delivery
else:
current_sum += delivery
retur... | simplelr_Leetcode | [
{
"content": "Question:\nYou are tasked with managing a warehouse that operates over a span of `D` days. Each day, a certain number of products are expected to be delivered, and you have to ensure that you have enough storage capacity each day to handle these deliveries. You are given an integer `D` representin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3233,
"level": 1,
"question": "You are tasked with managing a warehouse that operates over a span of `D` days. Each day, a certain number of products are expected to be delivered, and you have to ensure that you have enough storage capacity each day to handle these deliveries. You a... |
def find_vowels(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
result = []
for char in s:
if char.lower() in vowels:
result.append(char)
return result if result else None | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to check if a given string contains any vowels or not. The function should return a list of vowels found in the string, or `None` if no vowels are present.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3234,
"level": 1,
"question": "Write a Python function to check if a given string contains any vowels or not. The function should return a list of vowels found in the string, or `None` if no vowels are present.",
"split": "train"
} |
def unscramble_sentence(s):
words = s.split()
result = []
for word in words:
pos = int(word[-1])
actual_word = word[:-1]
result.append((pos, actual_word))
result.sort(key=lambda x: x[0])
sorted_words = [word for (pos, word) in result]
return ' '.join(sorted_words) | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` which represents a scrambled sentence, return the sentence corrected by rearranging the words. Each word is appended with a single-digit number which indicates its position in the sentence (1-indexed). Remove the numbers and return the sentence in its correct order.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3235,
"level": 1,
"question": "Given a string `s` which represents a scrambled sentence, return the sentence corrected by rearranging the words. Each word is appended with a single-digit number which indicates its position in the sentence (1-indexed). Remove the numbers and return t... |
def merge_intervals(intervals):
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 interval
merged = [list(sorted_intervals[0])]
for i in range(1, len(sor... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of intervals where each interval is represented as a pair `[start, end]`, and each `start` and `end` are integers representing an inclusive range. Merge all overlapping intervals and return _an array of the non-overlapping intervals that cover all the intervals in t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3236,
"level": 1,
"question": "You are given a list of intervals where each interval is represented as a pair `[start, end]`, and each `start` and `end` are integers representing an inclusive range. Merge all overlapping intervals and return _an array of the non-overlapping interval... |
def reverse_words(text):
"""
This function reverses the order of words in a given string.
Args:
text: The string to reverse the words in.
Returns:
The string with the words reversed.
"""
words = text.split()
reversed_words = words[::-1]
return " ".join(reversed_words) | simplelr_Filter | [
{
"content": "Question:\nThis is the problem:\n\n**The Problem:**\n\nYou are given a string containing only lowercase English letters, digits and spaces. You need to write a Python function to reverse the words in the string while preserving the order of characters in each word.\n\n**Example:**\n\n```\nInput: \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3237,
"level": 1,
"question": "This is the problem:\n\n**The Problem:**\n\nYou are given a string containing only lowercase English letters, digits and spaces. You need to write a Python function to reverse the words in the string while preserving the order of characters in each wor... |
from itertools import permutations
def generate_unique_permutations(nums: list[int]) -> list[list[int]]:
# Generate all possible permutations
perms = permutations(nums)
# Convert to a set to remove duplicates, then back to a list of lists
unique_perms = {p for p in perms}
# Convert tuples to lists
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are tasked with implementing a function that can generate all unique permutations of a given list of integers. The function should handle lists that may contain duplicate elements and ensure that permutations are generated in a lexicographic order.\n\n### Re... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3238,
"level": 1,
"question": "### Problem Statement\n\nYou are tasked with implementing a function that can generate all unique permutations of a given list of integers. The function should handle lists that may contain duplicate elements and ensure that permutations are generated ... |
def longest_unique_substring(s):
char_index = {}
left = 0
max_length = 0
for right in range(len(s)):
char = s[right]
if char in char_index and char_index[char] >= left:
left = char_index[char] + 1
char_index[char] = right
current_length = right - left + 1
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the length of the longest substring of a given string without repeating characters without using any built-in functions or libraries other than the standard library in python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3239,
"level": 1,
"question": "Write a python function to find the length of the longest substring of a given string without repeating characters without using any built-in functions or libraries other than the standard library in python.",
"split": "train"
} |
def trap_water(arr):
n = len(arr)
if n < 3:
return 0
left_max = [0] * n
right_max = [0] * n
# Compute left_max: max height from left excluding current
for i in range(1, n):
left_max[i] = max(left_max[i-1], arr[i-1])
# Compute right_max: max height from right ex... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` where `arr[i]` represents the elevation of the `i`-th position along a hiking path. The rain water can be trapped between different elevations. Your task is to calculate the total unit of water that can be trapped after a rain. Return the total a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3240,
"level": 1,
"question": "You are given an array of integers `arr` where `arr[i]` represents the elevation of the `i`-th position along a hiking path. The rain water can be trapped between different elevations. Your task is to calculate the total unit of water that can be trapp... |
def sum_of_even_numbers(numbers):
return sum(num for num in numbers if num % 2 == 0) | simplelr_Filter | [
{
"content": "Question:\nThis is a question for the OpenAI's Codex.\n\nImagine you are a large language model, trained on a massive dataset of text and code.\n\nIf you were asked to write a Python function that takes a list of numbers as input and returns the sum of all the even numbers in the list,\n\nHow woul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3241,
"level": 1,
"question": "This is a question for the OpenAI's Codex.\n\nImagine you are a large language model, trained on a massive dataset of text and code.\n\nIf you were asked to write a Python function that takes a list of numbers as input and returns the sum of all the ev... |
from collections import Counter
def group_and_count(s):
counts = Counter(s)
return sorted(counts.items(), key=lambda x: (-x[1], x[0]))
| simplelr_Taco | [
{
"content": "Question:\nYou are given a string containing characters from A to Z. Your task is to write a function to group and count the characters and then output the counts as a list of tuples. Each tuple should contain a character and its count. The list should be sorted by the counts in descending order. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3242,
"level": 1,
"question": "You are given a string containing characters from A to Z. Your task is to write a function to group and count the characters and then output the counts as a list of tuples. Each tuple should contain a character and its count. The list should be sorted ... |
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to search a given number in a sorted array (in ascending order). The function should return the index of the number if it is present, else return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3243,
"level": 1,
"question": "Write a python function to search a given number in a sorted array (in ascending order). The function should return the index of the number if it is present, else return -1.",
"split": "train"
} |
def evaluate_expression(s):
# Tokenize the input string into numbers and operators
tokens = []
current_number = ''
for c in s:
if c in '+-*/':
if current_number:
tokens.append(current_number)
current_number = ''
tokens.append(c)
els... | simplelr_Taco | [
{
"content": "Question:\nCreate a function that takes a string containing a mathematical expression consisting of non-negative integers and the operators `+`, `-`, `*`, and `/`. The function should evaluate the expression and return the result as a float. Note that the input string is guaranteed to be valid and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3244,
"level": 1,
"question": "Create a function that takes a string containing a mathematical expression consisting of non-negative integers and the operators `+`, `-`, `*`, and `/`. The function should evaluate the expression and return the result as a float. Note that the input s... |
def top_n_students(students, N):
# Sort the list of students based on their scores in descending order
sorted_students = sorted(students, key=lambda x: x['score'], reverse=True)
# Initialize the list to store the top N students
top_students = []
for student in sorted_students:
if len(to... | simplelr_Evol | [
{
"content": "Question:\nGiven a list of students with their respective scores in a format of a list of dictionaries, write a function that returns a list of the top N students based on their scores. The function should handle edge cases such as multiple students having the same score and N being larger than th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3245,
"level": 1,
"question": "Given a list of students with their respective scores in a format of a list of dictionaries, write a function that returns a list of the top N students based on their scores. The function should handle edge cases such as multiple students having the sa... |
def merge_intervals(events):
if not events:
return []
# Sort the events based on the start time
sorted_events = sorted(events, key=lambda x: x[0])
merged = [list(sorted_events[0])]
for event in sorted_events[1:]:
last_start, last_end = merged[-1]
current_start, curr... | simplelr_Filter | [
{
"content": "Question:\nPlease write a Python function that takes a list of tuples as input, where each tuple contains two elements representing the start and end times of an event. The function should merge any overlapping events and return a list of tuples representing the merged events. The input list is no... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3246,
"level": 1,
"question": "Please write a Python function that takes a list of tuples as input, where each tuple contains two elements representing the start and end times of an event. The function should merge any overlapping events and return a list of tuples representing the ... |
def find_overlapping_ranges(set1, set2):
overlapping = []
for a in set1:
for b in set2:
a_start, a_end = a
b_start, b_end = b
overlap_start = max(a_start, b_start)
overlap_end = min(a_end, b_end)
if overlap_start <= overlap_end:
... | simplelr_Filter | [
{
"content": "Question:\nDevelop a Python function to identify overlapping ranges between two sets of ranges. Each set contains ranges represented as tuples of two integers, indicating the start and end of the range. The function should return a list of tuples representing the overlapping ranges.\nAnswer:\nLet'... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3247,
"level": 1,
"question": "Develop a Python function to identify overlapping ranges between two sets of ranges. Each set contains ranges represented as tuples of two integers, indicating the start and end of the range. The function should return a list of tuples representing the... |
def encode_morse(text):
morse_code = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...', 'T': '-', 'U... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n**Title**: Implement Morse Code Encoder\n\n**Context**:\nYou are working on a communication tool that can encode text messages into Morse code. Morse code is a method used in telecommunication to encode text characters as standardized sequences of two d... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3248,
"level": 1,
"question": "### Coding Assessment Question\n\n**Title**: Implement Morse Code Encoder\n\n**Context**:\nYou are working on a communication tool that can encode text messages into Morse code. Morse code is a method used in telecommunication to encode text characters... |
def largest_rectangle_area(heights):
stack = [-1] # Initialize stack with base index
max_area = 0
n = len(heights)
for i in range(n):
# Pop elements from the stack while the current height is smaller than the top of the stack
while stack[-1] != -1 and heights[i] < heights[stack[-1]... | simplelr_Filter | [
{
"content": "Question:\nYou are given an array of integers representing the heights of bars in a bar chart. The bars are arranged vertically, with the leftmost bar having index 0.\n\n```\nheights = [2, 1, 5, 6, 2, 3]\n```\n\n Objectives:\n\nFind the largest rectangular area that can be formed within the bar ch... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3249,
"level": 1,
"question": "You are given an array of integers representing the heights of bars in a bar chart. The bars are arranged vertically, with the leftmost bar having index 0.\n\n```\nheights = [2, 1, 5, 6, 2, 3]\n```\n\n Objectives:\n\nFind the largest rectangular area t... |
from collections import Counter
def can_form_palindrome(s):
count = Counter(s)
odd_counts = sum(1 for cnt in count.values() if cnt % 2 != 0)
n = len(s)
if n % 2 == 0:
return odd_counts == 0
else:
return odd_counts == 1
| simplelr_Taco | [
{
"content": "Question:\nGiven a string (str) containing only lowercase alphabetical characters, determine if it can be rearranged to form a palindrome. Return a boolean value indicating whether it is possible to rearrange the characters to form a palindrome. \n\nA palindrome reads the same backward as forward.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3250,
"level": 1,
"question": "Given a string (str) containing only lowercase alphabetical characters, determine if it can be rearranged to form a palindrome. Return a boolean value indicating whether it is possible to rearrange the characters to form a palindrome. \n\nA palindrome ... |
from typing import List, Union
def split_array_by_pattern(n: int, k: int, arr: List[int], pattern: List[int]) -> Union[List[int], int]:
m = len(pattern)
if m * k != n:
return -1
for i in range(k):
start = i * m
end = start + m
chunk = arr[start:end]
if chunk != patte... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given an array of n integers and a sequence consistency rule specified by a given pattern. The goal is to check if the array can be split into k contiguous subarrays such that each subarray matches the pattern exactly. The pattern is a shorter array of integers.\n\nWrite a funct... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3251,
"level": 1,
"question": "You are given an array of n integers and a sequence consistency rule specified by a given pattern. The goal is to check if the array can be split into k contiguous subarrays such that each subarray matches the pattern exactly. The pattern is a shorter ... |
import sys
import faulthandler
import signal
import ctypes
def setup_faulthandler(timeout=None, file=sys.stderr, signal_num=signal.SIGUSR1, chain=False, cancel_timeout=False):
"""
Set up the fault handler for debugging.
:param timeout: Optional timeout in seconds after which to dump tracebacks. If None, n... | simplelr_Docs | [
{
"content": "Question:\n**Objective**: Implement a function `setup_faulthandler()` that demonstrates the use of the `faulthandler` module to help debug segmentation faults or other catastrophic errors in a Python program.\n\n### Requirements:\n\n1. **Enable Fault Handlers**: The function should enable the faul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3252,
"level": 1,
"question": "**Objective**: Implement a function `setup_faulthandler()` that demonstrates the use of the `faulthandler` module to help debug segmentation faults or other catastrophic errors in a Python program.\n\n### Requirements:\n\n1. **Enable Fault Handlers**: ... |
def is_palindrome(s):
# Process the string: keep only alphanumeric characters and convert to lowercase
cleaned = []
for char in s:
if char.isalnum():
cleaned.append(char.lower())
cleaned_str = ''.join(cleaned)
# Check if the cleaned string is a palindrome
return cleaned_str =... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that accepts a string as input and checks if it's a palindrome. A palindrome is a string that reads the same backward as forward. The program should return True if the string is a palindrome and False otherwise. The program should be case-insensitive and should ig... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3253,
"level": 1,
"question": "Write a Python program that accepts a string as input and checks if it's a palindrome. A palindrome is a string that reads the same backward as forward. The program should return True if the string is a palindrome and False otherwise. The program shoul... |
import random
def roll_dice(sides=6):
"""Simulates rolling a dice with a specified number of sides.
Args:
sides: The number of sides on the dice (default is 6).
Returns:
A random integer between 1 and the number of sides, inclusive.
"""
return random.randint(1, sides) | simplelr_Filter | [
{
"content": "Question:\nThis is the first part of the project:\n1. Create a Python program to simulate the dice rolling process.\n\n```python\nimport random\n\ndef roll_dice(sides=6):\n \"\"\"Simulates rolling a dice with a specified number of sides.\n\n Args:\n sides: The number of sides on the dice (def... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3254,
"level": 1,
"question": "This is the first part of the project:\n1. Create a Python program to simulate the dice rolling process.\n\n```python\nimport random\n\ndef roll_dice(sides=6):\n \"\"\"Simulates rolling a dice with a specified number of sides.\n\n Args:\n sides: T... |
def parse_config_file(file_path: str) -> dict:
config = {}
with open(file_path, 'r') as file:
for line in file:
stripped_line = line.strip()
if not stripped_line:
continue
if stripped_line[0] == '#':
continue
if '=' not in s... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\nImplement a function that parses a configuration file and extracts key-value pairs. The configuration file contains settings where each line signifies a key-value pair, separated by an equal sign (`=`). Your task is to read the file, parse each line to obtain the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3255,
"level": 1,
"question": "### Problem Statement:\nImplement a function that parses a configuration file and extracts key-value pairs. The configuration file contains settings where each line signifies a key-value pair, separated by an equal sign (`=`). Your task is to read the ... |
def min_add_to_make_valid(s):
res = 0
balance = 0
for c in s:
if c == '(':
balance += 1
else:
balance -= 1
if balance < 0:
res += 1
balance = 0
res += balance
return res | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` representing a valid Parentheses sequence. The string consists of only `'('` and `')'`. Return _the **minimum** number of parentheses to be added to make the string valid_. A valid Parentheses sequence is one where each opening parenthesis `'('` has a correspo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3256,
"level": 1,
"question": "You are given a string `s` representing a valid Parentheses sequence. The string consists of only `'('` and `')'`. Return _the **minimum** number of parentheses to be added to make the string valid_. A valid Parentheses sequence is one where each openi... |
def unique_paths(m: int, n: int) -> int:
a = m + n - 2
b = min(m - 1, n - 1)
result = 1
for i in range(1, b + 1):
result = result * (a - b + i) // i
return result
| simplelr_Taco | [
{
"content": "Question:\nIn a game, a character can move on a grid. The grid is an `m x n` matrix and the character is initially positioned at the top-left corner (0,0). The character can only move either down or right at any point in time. Write a function to find the number of unique paths that the character ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3257,
"level": 1,
"question": "In a game, a character can move on a grid. The grid is an `m x n` matrix and the character is initially positioned at the top-left corner (0,0). The character can only move either down or right at any point in time. Write a function to find the number ... |
import math
def find_roots(a, b, c):
discriminant = b ** 2 - 4 * a * c
if discriminant < 0:
return None
elif discriminant == 0:
root = (-b) / (2 * a)
return (root, root)
else:
sqrt_discriminant = math.sqrt(discriminant)
root1 = (-b + sqrt_discriminant) / (2 * a)
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the roots of a quadratic equation ax^2 + bx + c = 0. The function should take the coefficients a, b, and c as input and return the roots as a tuple. If the equation has no real roots, the function should return None. If the equation has one real root, the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3258,
"level": 1,
"question": "Write a Python function to find the roots of a quadratic equation ax^2 + bx + c = 0. The function should take the coefficients a, b, and c as input and return the roots as a tuple. If the equation has no real roots, the function should return None. If ... |
import math
def generate_prime_numbers(n):
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0], sieve[1] = False, False
for p in range(2, int(math.sqrt(n)) + 1):
if sieve[p]:
for multiple in range(p * p, n + 1, p):
sieve[multiple] = False
primes = [i fo... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to generate prime numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3259,
"level": 1,
"question": "Write a python function to generate prime numbers.",
"split": "train"
} |
def filter_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0] | simplelr_Filter | [
{
"content": "Question:\nExercise: Write a Python script that takes a list of integers as input and returns a new list containing only the even numbers from the original list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3260,
"level": 1,
"question": "Exercise: Write a Python script that takes a list of integers as input and returns a new list containing only the even numbers from the original list.",
"split": "train"
} |
def is_at_origin(movements: str) -> bool:
count_L = movements.count('L')
count_R = movements.count('R')
count_U = movements.count('U')
count_D = movements.count('D')
net_x = count_R - count_L
net_y = count_U - count_D
return net_x == 0 and net_y == 0 | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\nYou are given a string representing the movement of a robot in a 2D grid. The string consists of the characters 'L' (left), 'R' (right), 'U' (up), and 'D' (down). Your task is to determine if the robot returns to the origin (0, 0) after executing all the movement... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3261,
"level": 1,
"question": "### Problem Statement:\nYou are given a string representing the movement of a robot in a 2D grid. The string consists of the characters 'L' (left), 'R' (right), 'U' (up), and 'D' (down). Your task is to determine if the robot returns to the origin (0, ... |
def merge_dictionaries(dict1, dict2, keys):
result = {}
for key in keys:
if key in dict2:
result[key] = dict2[key]
elif key in dict1:
result[key] = dict1[key]
return result | simplelr_Package | [
{
"content": "Question:\nYou are required to write a Python function `merge_dictionaries(dict1, dict2, keys)`, which takes in three parameters:\n\n1. `dict1` (a dictionary): This is the first dictionary to be merged.\n2. `dict2` (a dictionary): This is the second dictionary to be merged.\n3. `keys` (a list of s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3262,
"level": 1,
"question": "You are required to write a Python function `merge_dictionaries(dict1, dict2, keys)`, which takes in three parameters:\n\n1. `dict1` (a dictionary): This is the first dictionary to be merged.\n2. `dict2` (a dictionary): This is the second dictionary to... |
def can_plant_flowers(garden, num_flowers):
if num_flowers == 0:
return True
current = 0
for spot in garden:
if spot == 0:
current += 1
else:
if current >= num_flowers:
return True
current = 0
if current >= num_flowers... | simplelr_Taco | [
{
"content": "Question:\nYou've just moved into a new house with a beautiful garden! However, the garden is filled with rocks and you want to replace some of them with flowers. You have a bag of flower seeds and you know exactly how many flowers you'd like to plant. Unfortunately, you can only plant flowers in ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3263,
"level": 1,
"question": "You've just moved into a new house with a beautiful garden! However, the garden is filled with rocks and you want to replace some of them with flowers. You have a bag of flower seeds and you know exactly how many flowers you'd like to plant. Unfortunat... |
from collections import defaultdict
def detect_ddos(k, n, packets):
# Group packets by source IP
source_packets = defaultdict(list)
for packet in packets:
timestamp, src, dst = packet
source_packets[src].append((timestamp, dst))
attackers = set()
for src, src_pkts in sourc... | simplelr_Codeforces | [
{
"content": "Question:\nA cybersecurity company is developing a system to monitor incoming packets in a computer network. Each incoming packet has a timestamp, source IP address, and destination IP address. The goal is to identify potential Distributed Denial of Service (DDoS) attacks. \n\nA DDoS attack is sus... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3264,
"level": 1,
"question": "A cybersecurity company is developing a system to monitor incoming packets in a computer network. Each incoming packet has a timestamp, source IP address, and destination IP address. The goal is to identify potential Distributed Denial of Service (DDoS... |
def rob(nums):
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 `nums` representing the amounts of money of `n` houses lined up in a row. Each house can be robbed, but robbing two adjacent houses will trigger the security system. Your goal is to maximize the amount of money you can rob tonight without al... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3265,
"level": 1,
"question": "You are given a list of non-negative integers `nums` representing the amounts of money of `n` houses lined up in a row. Each house can be robbed, but robbing two adjacent houses will trigger the security system. Your goal is to maximize the amount of m... |
def extended_gcd(num1: int, num2: int) -> (int, int, int):
old_r, r = num1, num2
s_old, s = 1, 0
t_old, t = 0, 1
while r != 0:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
s_old, s = s, s_old - quotient * s
t_old, t = t, t_old - quotient * t
return (s_ol... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given two integers, num1 and num2. You need to implement a function called `extended_gcd` which finds three integers \\( s \\), \\( t \\), and \\( g \\) such that:\n\n\\[ \\text{num1} \\times s + \\text{num2} \\times t = g \\]\n\nwhere \\( g \\) is the greatest common divisor (G... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3266,
"level": 1,
"question": "You are given two integers, num1 and num2. You need to implement a function called `extended_gcd` which finds three integers \\( s \\), \\( t \\), and \\( g \\) such that:\n\n\\[ \\text{num1} \\times s + \\text{num2} \\times t = g \\]\n\nwhere \\( g \\... |
from typing import List
from collections import Counter
def unique_words(sentence: str) -> List[str]:
words = sentence.split()
counts = Counter(words)
added = set()
result = []
for word in words:
if counts[word] == 1 and word not in added:
result.append(word)
added.a... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` representing a sentence containing words separated by spaces. Some words are repeated multiple times. Your task is to return a list of words that appear only once in the sentence. The words should be returned in the order of their appearance in the sentence.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3267,
"level": 1,
"question": "You are given a string `s` representing a sentence containing words separated by spaces. Some words are repeated multiple times. Your task is to return a list of words that appear only once in the sentence. The words should be returned in the order of ... |
def invert_dictionary(d):
inverted_dict = {}
for key, value in d.items():
inverted_dict[value] = key
return inverted_dict | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a Python dictionary and returns a new dictionary where the keys are the original values and the values are the keys. Essentially, it inverts the key-value relationship in the dictionary.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3268,
"level": 1,
"question": "Create a function that takes a Python dictionary and returns a new dictionary where the keys are the original values and the values are the keys. Essentially, it inverts the key-value relationship in the dictionary.",
"split": "train"
} |
def reverse_words_in_sentence(s):
words = s.split()
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` representing a sentence where words are separated by single spaces. Each word in `s` consists of only alphabetical characters. Your task is to reverse each word in the sentence while maintaining the initial word order and spaces. Return the resulting sentence ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3269,
"level": 1,
"question": "You are given a string `s` representing a sentence where words are separated by single spaces. Each word in `s` consists of only alphabetical characters. Your task is to reverse each word in the sentence while maintaining the initial word order and spa... |
import pandas as pd
def calculate_average_score_by_country():
df = pd.read_csv('data.csv')
average_scores = df.groupby('Country')['Score'].mean()
return average_scores.to_dict() | simplelr_Package | [
{
"content": "Question:\nIn this problem, you will be working with the `pandas` library to analyze a dataset and perform data manipulation. The dataset is assumed to be in a CSV file named `data.csv` with the following columns: `ID`, `Name`, `Age`, `Country`, and `Score`.\n\nYou are required to define a functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3270,
"level": 1,
"question": "In this problem, you will be working with the `pandas` library to analyze a dataset and perform data manipulation. The dataset is assumed to be in a CSV file named `data.csv` with the following columns: `ID`, `Name`, `Age`, `Country`, and `Score`.\n\nY... |
def count_anagrams(words, targetWord):
target_sorted = ''.join(sorted(targetWord))
unique_words = set(words)
count = 0
for word in unique_words:
if len(word) != len(targetWord):
continue
if ''.join(sorted(word)) == target_sorted:
count += 1
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of strings `words` and a string `targetWord`. Your goal is to find the number of unique words in the list that can be transformed into `targetWord` by rearranging its letters. In other words, count the anagrams of `targetWord` that exist in the `words` list. Return ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3271,
"level": 1,
"question": "You are given a list of strings `words` and a string `targetWord`. Your goal is to find the number of unique words in the list that can be transformed into `targetWord` by rearranging its letters. In other words, count the anagrams of `targetWord` that... |
def is_valid_integer(s):
s = s.strip()
if not s:
return False
i = 0
# Check for optional sign
if s[0] in '+-':
i += 1
if i == len(s):
return False
# Check each character after the sign for being a digit
for c in s[i:]:
if c not in '0123456789':
... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and verifies whether it is a valid integer. The function should return `True` if the string represents a valid integer, including handling negative integers and ignoring leading/trailing whitespaces. However, the function should not convert... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3272,
"level": 1,
"question": "Create a function that takes a string as input and verifies whether it is a valid integer. The function should return `True` if the string represents a valid integer, including handling negative integers and ignoring leading/trailing whitespaces. Howev... |
def frequency_sort(s):
freq = {}
first_occurrence = {}
for index, char in enumerate(s):
if char not in freq:
freq[char] = 1
first_occurrence[char] = index
else:
freq[char] += 1
chars = list(freq.keys())
sorted_chars = sorted(chars, key=lambda c: (-... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns a string where the characters are rearranged in descending order based on their frequency. If two characters have the same frequency, they should be ordered by their original position in the string.\nAnswer:\nLet's think s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3273,
"level": 1,
"question": "Write a Python function that takes a string as input and returns a string where the characters are rearranged in descending order based on their frequency. If two characters have the same frequency, they should be ordered by their original position in ... |
def max_area(heights):
max_area = 0
i = 0
j = len(heights) - 1
while i < j:
# Calculate the current area
current_height = min(heights[i], heights[j])
current_width = j - i
current_area = current_height * current_width
# Update the maximum area if nee... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `heights` representing the heights of buildings, each building being 1 unit wide. The goal is to find the **maximum area of water** that can be contained between the buildings when it rains. The amount of water that can be contained between two buildin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3274,
"level": 1,
"question": "You are given an array of integers `heights` representing the heights of buildings, each building being 1 unit wide. The goal is to find the **maximum area of water** that can be contained between the buildings when it rains. The amount of water that c... |
def formatWithCommas(s: str) -> str:
if len(s) <= 3:
return s
reversed_s = s[::-1]
chunks = [reversed_s[i:i+3] for i in range(0, len(reversed_s), 3)]
reversed_chunks = [chunk[::-1] for chunk in chunks]
reversed_chunks.reverse()
return ','.join(reversed_chunks)
| simplelr_Taco | [
{
"content": "Question:\nGiven a string representing a large integer, the task is to format it with commas to separate every three digits from the right.\n\nWrite a function `formatWithCommas(s: str) -> str` that takes a string `s` representing a non-negative integer and returns the formatted string with commas... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3275,
"level": 1,
"question": "Given a string representing a large integer, the task is to format it with commas to separate every three digits from the right.\n\nWrite a function `formatWithCommas(s: str) -> str` that takes a string `s` representing a non-negative integer and retur... |
def get_indices_of_X(s):
return [index for index, char in enumerate(s) if char == 'X'] | simplelr_Filter | [
{
"content": "Question:\nI have a string of 'X's and 'O's. I want to get all the indices of the 'X' character in the string. \n\nFor example: \nIf my string is 'XOOXXXO', my output should be [0, 3, 4, 5]. \n\nHow can I do it in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3276,
"level": 1,
"question": "I have a string of 'X's and 'O's. I want to get all the indices of the 'X' character in the string. \n\nFor example: \nIf my string is 'XOOXXXO', my output should be [0, 3, 4, 5]. \n\nHow can I do it in Python?",
"split": "train"
} |
def first_non_repeating_character(string):
from collections import Counter
counts = Counter(string)
for char in string:
if counts[char] == 1:
return char
return None | simplelr_Filter | [
{
"content": "Question:\nThis is a task:\n\n> Given a string, return the first non-repeating character in it. If there is no non-repeating character, return None. \n\nLet's call this function `first_non_repeating_character`\n\nHere are some examples:\n\n* `first_non_repeating_character(\"abcabcbb\")` returns `'... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3277,
"level": 1,
"question": "This is a task:\n\n> Given a string, return the first non-repeating character in it. If there is no non-repeating character, return None. \n\nLet's call this function `first_non_repeating_character`\n\nHere are some examples:\n\n* `first_non_repeating_... |
def max_subarray_sum(nums):
max_current = max_global = nums[0]
for num in nums[1:]:
max_current = max(max_current + num, num)
if max_current > max_global:
max_global = max_current
return max_global
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, you need to find the largest sum of any continuous subarray. The subarray must contain at least one number.\n\nExample 1:\nInput: nums = [-2,1,-3,4,-1,2,1,-5,4]\nOutput: 6\nExplanation: The contiguous subarray [4,-1,2,1] has the largest sum = 6.\n\nConstraints:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3278,
"level": 1,
"question": "Given a list of integers, you need to find the largest sum of any continuous subarray. The subarray must contain at least one number.\n\nExample 1:\nInput: nums = [-2,1,-3,4,-1,2,1,-5,4]\nOutput: 6\nExplanation: The contiguous subarray [4,-1,2,1] has t... |
def sum_even_fibonacci(n):
a, b = 0, 1
total = 0
while a <= n:
if a % 2 == 0:
total += a
a, b = b, a + b
return total | simplelr_Apps | [
{
"content": "Question:\n## Task\n\nWrite a function that, given a positive integer `n`, returns the sum of all even Fibonacci numbers that are less than or equal to `n`.\n\nThe Fibonacci sequence is a series of numbers starting with 0 and 1 where each number is the sum of the two preceding ones.\n\n### Example... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3279,
"level": 1,
"question": "## Task\n\nWrite a function that, given a positive integer `n`, returns the sum of all even Fibonacci numbers that are less than or equal to `n`.\n\nThe Fibonacci sequence is a series of numbers starting with 0 and 1 where each number is the sum of the... |
def three_sum_closest(nums, target):
nums.sort()
n = len(nums)
min_diff = float('inf')
closest_sum = 0
for i in range(n - 2):
left = i + 1
right = n - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
current_diff = abs(current_sum... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums` and an integer `target`. Your task is to find a unique triplet in the array, such that the sum of the triplet is closest to the target. Return _the sum of the triplet_ that is closest to the target. If there are multiple triplets that have the s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3280,
"level": 1,
"question": "You are given an array of integers `nums` and an integer `target`. Your task is to find a unique triplet in the array, such that the sum of the triplet is closest to the target. Return _the sum of the triplet_ that is closest to the target. If there ar... |
def reverse_words(sentence):
return ' '.join(sentence.split()[::-1]) | simplelr_Filter | [
{
"content": "Question:\nImplement the following function in Python: `def reverse_words(sentence)`. This function should take a string `sentence` as input and return a new string where the order of the words in the sentence is reversed. The words in the returned string should be separated by a single space. Ass... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3281,
"level": 1,
"question": "Implement the following function in Python: `def reverse_words(sentence)`. This function should take a string `sentence` as input and return a new string where the order of the words in the sentence is reversed. The words in the returned string should ... |
def two_sum(numbers, target):
num_set = set()
for num in numbers:
if target - num in num_set:
return [target - num, num]
num_set.add(num)
return [] | simplelr_Filter | [
{
"content": "Question:\ndef two_sum(numbers, target):\n num_set = set()\n for num in numbers:\n if target - num in num_set:\n return [target - num, num]\n num_set.add(num)\n return []\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3282,
"level": 1,
"question": "def two_sum(numbers, target):\n num_set = set()\n for num in numbers:\n if target - num in num_set:\n return [target - num, num]\n num_set.add(num)\n return []",
"split": "train"
} |
def binary_search(sorted_list, target):
low = 0
high = len(sorted_list) - 1
while low <= high:
mid = (low + high) // 2
if sorted_list[mid] == target:
return mid
elif sorted_list[mid] > target:
high = mid - 1
else:
low = mid + 1
ret... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function that implements the binary search algorithm and returns the index of the target element in a sorted list? If the target is not found, the function should return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3283,
"level": 1,
"question": "Can you provide a Python function that implements the binary search algorithm and returns the index of the target element in a sorted list? If the target is not found, the function should return -1.",
"split": "train"
} |
def double_sum(numbers):
return sum(2 * x for x in numbers) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum of a list of integers, but the function should double the value of each integer before summing them up.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3284,
"level": 1,
"question": "Write a function to calculate the sum of a list of integers, but the function should double the value of each integer before summing them up.",
"split": "train"
} |
def extract_integers(lst):
integers = []
for item in lst:
if type(item) is int:
integers.append(item)
return integers | simplelr_Filter | [
{
"content": "Question:\ngiven a python list that contains both numeric and string type data, write a function to pick out all the integer values from the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3285,
"level": 1,
"question": "given a python list that contains both numeric and string type data, write a function to pick out all the integer values from the list.",
"split": "train"
} |
import zipfile
import os
def process_zipfile(file_dict, zip_filename, extract_dir):
# Step 1: Create the ZIP file and write the files using ZIP_DEFLATED compression
with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
for filename, content in file_dict.items():
zipf.writes... | simplelr_Docs | [
{
"content": "Question:\n**Objective**: Assess your understanding and ability to work with the `zipfile` module in Python.\n\n### Problem Statement\n\nYou are tasked with creating a utility function that processes a ZIP file. This function should accomplish the following tasks:\n\n1. **Write and Compress Files*... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3286,
"level": 1,
"question": "**Objective**: Assess your understanding and ability to work with the `zipfile` module in Python.\n\n### Problem Statement\n\nYou are tasked with creating a utility function that processes a ZIP file. This function should accomplish the following tasks... |
import string
from collections import Counter
def word_count(text):
# Convert the text to lowercase to ensure case insensitivity
text_lower = text.lower()
# Split the text into words based on whitespace
words = text_lower.split()
# Remove any leading or trailing punctuation from each word
words... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function that can count the frequency of words in a given text?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3287,
"level": 1,
"question": "Can you provide a Python function that can count the frequency of words in a given text?",
"split": "train"
} |
def maximum(a, b):
return (a + b + abs(a - b)) / 2 | simplelr_Filter | [
{
"content": "Question:\nIn Python, define a function that takes two arguments and returns the maximum of the two. However, you are not allowed to use the built-in max() function or any other sorting functions. Additionally, you cannot use any conditional statements like if-else or ternary operators.\nAnswer:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3288,
"level": 1,
"question": "In Python, define a function that takes two arguments and returns the maximum of the two. However, you are not allowed to use the built-in max() function or any other sorting functions. Additionally, you cannot use any conditional statements like if-el... |
def remove_duplicates(array: list) -> list:
seen = set()
result = []
for element in array:
if element not in seen:
seen.add(element)
result.append(element)
return result | simplelr_Data_Structure | [
{
"content": "Question:\nGiven an array, write a Python function that removes all duplicates from the array and returns a new array containing only unique elements. The order of the elements in the new array should be the same as their first occurrence in the original array.\n\n### Input Format\n- A list `array... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3289,
"level": 1,
"question": "Given an array, write a Python function that removes all duplicates from the array and returns a new array containing only unique elements. The order of the elements in the new array should be the same as their first occurrence in the original array.\n... |
def bubble_sort(arr, simulation=False):
working_arr = arr[:] # Create a copy of the input array
n = len(working_arr)
if n <= 1:
return working_arr # Return immediately for empty or single-element arrays
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Bubble Sort Augmentation and Optimization\n\nBubble sort is a fundamental sorting algorithm that can be suboptimal for performance-intensive tasks due to its O(N^2) time complexity. However, it serves as an excellent example for learning basic sorting concepts. In this task, you are... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3290,
"level": 1,
"question": "### Bubble Sort Augmentation and Optimization\n\nBubble sort is a fundamental sorting algorithm that can be suboptimal for performance-intensive tasks due to its O(N^2) time complexity. However, it serves as an excellent example for learning basic sort... |
def create_diagonal_matrix(n):
matrix = [[0] * n for _ in range(n)]
for i in range(n):
matrix[i][i] = 1
matrix[i][n - i - 1] = 1
return matrix | simplelr_Filter | [
{
"content": "Question:\nGiven an integer n, generate an array of size n x n with all elements initialized to 0, and then change all the elements in the primary diagonal and anti-diagonal to 1.\n\nHere's an example:\nInput: n = 5\nOutput: \n[[0, 0, 0, 0, 1],\n [0, 0, 0, 1, 0],\n [0, 0, 1, 0, 0],\n [0, 1, 0, 0, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3291,
"level": 1,
"question": "Given an integer n, generate an array of size n x n with all elements initialized to 0, and then change all the elements in the primary diagonal and anti-diagonal to 1.\n\nHere's an example:\nInput: n = 5\nOutput: \n[[0, 0, 0, 0, 1],\n [0, 0, 0, 1, 0],... |
import re
def is_palindrome(s: str) -> bool:
# Remove all non-alphanumeric characters from the string
cleaned = re.sub(r'[^a-zA-Z0-9]', '', s)
# Convert to lowercase to ignore case
cleaned = cleaned.lower()
# Check if the cleaned string is a palindrome
return cleaned == cleaned[::-1] | simplelr_Filter | [
{
"content": "Question:\nHow to solve this problem:\n\n\"Given string s, determine if it is a palindrome considering only alphanumeric characters. ignore cases.\n\nFor example:\nInput: s = \"A man, a plan, a canal: Panama\"\nOutput: true\n\nInput: s = \"race a car\"\nOutput: false\"\n\nLet me know the code solu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3292,
"level": 1,
"question": "How to solve this problem:\n\n\"Given string s, determine if it is a palindrome considering only alphanumeric characters. ignore cases.\n\nFor example:\nInput: s = \"A man, a plan, a canal: Panama\"\nOutput: true\n\nInput: s = \"race a car\"\nOutput: f... |
def longest_unique_substring(s: str) -> str:
char_index = {}
left = 0
max_length = 0
start = 0
for right in range(len(s)):
current_char = s[right]
# Update left pointer if the current character is within the current window
if current_char in char_index and char_index[cur... | simplelr_Evol | [
{
"content": "Question:\nDesign a function in Python that takes a string as input and returns the longest substring without repeating characters. Your solution should be efficient, working within linear time complexity. Ensure to handle edge cases such as an empty string and strings with all identical character... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3293,
"level": 1,
"question": "Design a function in Python that takes a string as input and returns the longest substring without repeating characters. Your solution should be efficient, working within linear time complexity. Ensure to handle edge cases such as an empty string and s... |
def longest_consecutive_segment(s: str) -> int:
if not s:
return 0 # Though the problem states s is non-empty, this handles edge cases.
max_length = 1
current_length = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
current_length += 1
else:
if current_le... | simplelr_Algorithm | [
{
"content": "Question:\n### Consecutive Character Checker\n\nA consecutive character segment in a string is a substring made of identical characters. For example, in \"aaabbccc\", \"aaa\" and \"bbb\" and \"ccc\" are consecutive character segments.\n\n#### Task\nWrite a function `longest_consecutive_segment(s: ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3294,
"level": 1,
"question": "### Consecutive Character Checker\n\nA consecutive character segment in a string is a substring made of identical characters. For example, in \"aaabbccc\", \"aaa\" and \"bbb\" and \"ccc\" are consecutive character segments.\n\n#### Task\nWrite a functi... |
from typing import List
def trapWater(height: List[int]) -> int:
if not height:
return 0
n = len(height)
if n < 3:
return 0
# Compute left_max array
left_max = [0] * n
for i in range(1, n):
left_max[i] = max(left_max[i-1], height[i-1])
# Compute right_max a... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of non-negative integers representing the amount of rainfall each bucket has collected, where each integer represents one bucket. Your task is to calculate the total amount of water that could be trapped between the buckets after the rainfall. \n\nWrite a function `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3295,
"level": 1,
"question": "You are given a list of non-negative integers representing the amount of rainfall each bucket has collected, where each integer represents one bucket. Your task is to calculate the total amount of water that could be trapped between the buckets after t... |
def factorial(n):
"""
Calculate the factorial of a number.
Parameters:
n (int): A non-negative integer whose factorial is to be computed.
Returns:
int: Factorial of the number n.
Raises:
ValueError: If n is not a non-negative integer.
"""
if type(n) is not int or n < 0:
... | simplelr_Taco | [
{
"content": "Question:\nWrite a Python function to calculate the factorial of a given number 'n'. Ensure your function handles edge cases and performs error checking for invalid inputs. The function should be efficient and use recursion where appropriate. Define the function as follows:\n\n```python\ndef facto... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3296,
"level": 1,
"question": "Write a Python function to calculate the factorial of a given number 'n'. Ensure your function handles edge cases and performs error checking for invalid inputs. The function should be efficient and use recursion where appropriate. Define the function ... |
def sieve_of_eratosthenes(n):
if n < 2:
return []
is_prime = [True] * (n + 1)
is_prime[0], is_prime[1] = False, False
p = 2
while p * p <= n:
if is_prime[p]:
for i in range(p * p, n + 1, p):
is_prime[i] = False
p += 1
return [num... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Analyze and Optimize the Prime Number Generation\n\n#### Context:\nYou are working on an application that requires generating a list of prime numbers up to a given limit `n`. The current implementation uses a basic method that is inefficient for larger values of `n`. There... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3297,
"level": 1,
"question": "### Question: Analyze and Optimize the Prime Number Generation\n\n#### Context:\nYou are working on an application that requires generating a list of prime numbers up to a given limit `n`. The current implementation uses a basic method that is ineffici... |
import re
def word_occurrence(paragraph, word):
# Escape special characters in the target word
escaped_word = re.escape(word)
# Create the regex pattern to match whole words, case-insensitively
pattern = r'\b{}\b'.format(escaped_word)
# Find all occurrences
matches = re.findall(pattern, paragra... | simplelr_Filter | [
{
"content": "Question:\nPlease generate Python code to find the occurrence of a specific word in a given paragraph. The code should be case-insensitive and should only consider whole words.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3298,
"level": 1,
"question": "Please generate Python code to find the occurrence of a specific word in a given paragraph. The code should be case-insensitive and should only consider whole words.",
"split": "train"
} |
def count_words(text, delimiter=None):
"""Counts the number of words in a given text using a custom delimiter."""
words = text.split(delimiter)
return len(words) | simplelr_Filter | [
{
"content": "Question:\nWhile working on a coding project, I get stuck. Let's say I'm trying to\n\n```python\ndef count_words(text):\n \"\"\"Counts the number of words in a given text.\"\"\"\n words = text.split()\n return len(words)\n```\n\nThis function seems to be working fine, but I want to make it more... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3299,
"level": 1,
"question": "While working on a coding project, I get stuck. Let's say I'm trying to\n\n```python\ndef count_words(text):\n \"\"\"Counts the number of words in a given text.\"\"\"\n words = text.split()\n return len(words)\n```\n\nThis function seems to be worki... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.