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 rearrange_cars(parking_lot):
count = 0
new_cars = []
for num in parking_lot:
if num == -1:
count += 1
else:
new_cars.append(num)
return [-1] * count + new_cars | simplelr_Apps | [
{
"content": "Question:\nWrite a function `rearrange_cars` that takes in a parking lot represented by a list of integers, where each integer represents a car with a unique identifier (any positive integer) or `-1` representing an empty parking spot. The function should rearrange the parking lot such that all em... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9100,
"level": 1,
"question": "Write a function `rearrange_cars` that takes in a parking lot represented by a list of integers, where each integer represents a car with a unique identifier (any positive integer) or `-1` representing an empty parking spot. The function should rearran... |
def find_second_largest(lst):
for num in lst:
if not isinstance(num, (int, float)):
raise ValueError("List must contain only numbers.")
max_val = max(lst)
filtered = [x for x in lst if x < max_val]
return max(filtered) | simplelr_Apps | [
{
"content": "Question:\nCreate a function `find_second_largest` that accepts a list of numbers and returns the second largest number in the list. Consider that the list will have at least two unique numbers. If the list contains any non-numeric values, the function should raise a `ValueError` with the message ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9101,
"level": 1,
"question": "Create a function `find_second_largest` that accepts a list of numbers and returns the second largest number in the list. Consider that the list will have at least two unique numbers. If the list contains any non-numeric values, the function should rai... |
def strong_password(n, password):
count = 0
# Check for digit
if not any(c.isdigit() for c in password):
count += 1
# Check for lowercase
if not any(c.islower() for c in password):
count += 1
# Check for uppercase
if not any(c.isupper() for c in password):
count += 1
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Password Strengthening Challenge\n\nLouise is trying to create a password for her new account, but she's unsure if it meets the necessary strength criteria. A password is considered strong if it satisfies all the following conditions:\n\n1. It is at least 6 characters long.\n2. It c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9102,
"level": 1,
"question": "### Password Strengthening Challenge\n\nLouise is trying to create a password for her new account, but she's unsure if it meets the necessary strength criteria. A password is considered strong if it satisfies all the following conditions:\n\n1. It is a... |
from typing import List, Tuple
def remove_duplicates(transactions: List[Tuple[int, float]]) -> List[Tuple[int, float]]:
max_amounts = {}
for tid, amount in transactions:
if tid in max_amounts:
if amount > max_amounts[tid]:
max_amounts[tid] = amount
else:
... | simplelr_Algorithm | [
{
"content": "Question:\n## Question \n\n### Context:\nGiven a set of transactions recorded throughout the day, each transaction is represented as a tuple containing the transaction ID and the transaction amount. Transactions with the same ID are considered duplicates, and only the transaction with the highest ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9103,
"level": 1,
"question": "## Question \n\n### Context:\nGiven a set of transactions recorded throughout the day, each transaction is represented as a tuple containing the transaction ID and the transaction amount. Transactions with the same ID are considered duplicates, and onl... |
from typing import List
def sort_movies_by_word_count(movies: List[str]) -> List[str]:
return sorted(movies, key=lambda x: (len(x.split()), x)) | simplelr_Evol | [
{
"content": "Question:\nYou are given the following list of movie titles, where each movie title is a string:\n\n```python\nmovies = [\n \"The Matrix\",\n \"Inception\",\n \"Interstellar\",\n \"The Prestige\",\n \"The Dark Knight\",\n \"Memento\",\n \"Insomnia\",\n \"Dunkirk\",\n \"T... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9104,
"level": 1,
"question": "You are given the following list of movie titles, where each movie title is a string:\n\n```python\nmovies = [\n \"The Matrix\",\n \"Inception\",\n \"Interstellar\",\n \"The Prestige\",\n \"The Dark Knight\",\n \"Memento\",\n \"Ins... |
def fibonacci(n):
"""Calculate the nth term of the Fibonacci sequence using recursion."""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
# Example usage to print the first n terms of the Fibonacci sequence
n = 10 # Change this to the desi... | simplelr_Filter | [
{
"content": "Question:\nDesign a problem and solution using recursion to calculate the Fibonacci sequence up to the nth term in Python. Explain why recursion is an appropriate choice for this problem and discuss the limitations of this approach.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9105,
"level": 1,
"question": "Design a problem and solution using recursion to calculate the Fibonacci sequence up to the nth term in Python. Explain why recursion is an appropriate choice for this problem and discuss the limitations of this approach.",
"split": "train"
} |
def stutter_stack(stack: list) -> list:
result = []
for num in stack:
result.append(num)
result.append(num)
return result | simplelr_Data_Structure | [
{
"content": "Question:\nIn this task, you are to design a function based on the given `Stutter` algorithm. Specifically, you will implement a function `stutter_stack` that takes a stack as an input and replaces every value in the stack with two occurrences of that value.\n\nYour solution will require you to de... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9106,
"level": 1,
"question": "In this task, you are to design a function based on the given `Stutter` algorithm. Specifically, you will implement a function `stutter_stack` that takes a stack as an input and replaces every value in the stack with two occurrences of that value.\n\nY... |
def is_palindrome(s: str) -> bool:
# Preprocess the string: keep only alphanumeric characters and convert to lowercase
filtered = [c.lower() for c in s if c.isalnum()]
# Join the list into a string
filtered_str = ''.join(filtered)
# Initialize two pointers, one at start and one at end
left ... | simplelr_Filter | [
{
"content": "Question:\nIn the provided code snippet, I'm trying to implement a method to check if a given string is a palindrome. A palindrome is a string that reads the same backward as forward. How can I modify the `is_palindrome` function to handle cases where the input string might contain non-alphanumeri... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9107,
"level": 1,
"question": "In the provided code snippet, I'm trying to implement a method to check if a given string is a palindrome. A palindrome is a string that reads the same backward as forward. How can I modify the `is_palindrome` function to handle cases where the input s... |
from typing import List, Set, Tuple
def generate_subsets(nums: List[int]) -> Set[Tuple[int]]:
n = len(nums)
if n == 0:
return {()}
result = set()
for i in range(2 ** n):
subset = []
for j in range(n):
if (i >> j) & 1:
subset.append(nums[j])
re... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Context:\nYou are tasked with developing a system that provides users various combinations of features they can select. As part of the feature selection module, you need to implement a function that provides all possible subsets of a given set of features.\n\n#### Problem Statement... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9108,
"level": 1,
"question": "#### Context:\nYou are tasked with developing a system that provides users various combinations of features they can select. As part of the feature selection module, you need to implement a function that provides all possible subsets of a given set of ... |
def min_swaps_to_sort(height):
n = len(height)
if n == 0:
return 0
sorted_height = sorted(height)
# Create a dictionary to store the positions for each height in the sorted array
pos = {}
for i, num in enumerate(sorted_height):
if num not in pos:
pos[num] = ... | simplelr_Leetcode | [
{
"content": "Question:\nIn a warehouse, there are multiple shelves stacked with different boxes. Each shelf `i` has `height[i]` representing the height of the tallest box on that shelf. You must rearrange these shelves to make the warehouse more organized. The task is to sort the shelves in non-decreasing orde... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9109,
"level": 1,
"question": "In a warehouse, there are multiple shelves stacked with different boxes. Each shelf `i` has `height[i]` representing the height of the tallest box on that shelf. You must rearrange these shelves to make the warehouse more organized. The task is to sort... |
def largestRectangleArea(heights):
stack = [-1] # Initialize stack with base index
max_area = 0
n = len(heights)
for i in range(n):
while stack[-1] != -1 and heights[i] < heights[stack[-1]]:
# Pop the top element
h = heights[stack.pop()]
# Calculate the ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of non-negative integers representing the heights of pillars where the width of each pillar is 1. These pillars form a histogram. Compute the area of the largest rectangle that can be formed within the bounds of the histogram. The rectangle must be aligned with the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9110,
"level": 1,
"question": "You are given a list of non-negative integers representing the heights of pillars where the width of each pillar is 1. These pillars form a histogram. Compute the area of the largest rectangle that can be formed within the bounds of the histogram. The ... |
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr[1:] if x > pivot]
return quicksort(left) + middle + quicksort(right) | simplelr_Filter | [
{
"content": "Question:\nIn Python, create a function that takes a list of integers as input and returns a sorted list of those integers using the quicksort algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9111,
"level": 1,
"question": "In Python, create a function that takes a list of integers as input and returns a sorted list of those integers using the quicksort algorithm.",
"split": "train"
} |
def two_sum(nums, target):
num_indices = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_indices:
return [num_indices[complement], i]
num_indices[num] = i
return [] | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers `nums` and an integer `target`, return the indices of the two numbers whose sum equals the `target`. You may assume that each input would have exactly one solution, and you may not use the same element twice. \n\nYou can return the answer in any order.\n\nExam... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9112,
"level": 1,
"question": "Given an array of integers `nums` and an integer `target`, return the indices of the two numbers whose sum equals the `target`. You may assume that each input would have exactly one solution, and you may not use the same element twice. \n\nYou can retu... |
from typing import List
def last_occurrence(array: List[int], target: int) -> int:
low = 0
high = len(array) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if array[mid] == target:
result = mid
low = mid + 1
elif array[mid] < target:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Binary Search Problem: Last Occurrence in Sorted Array\n\nYou are given a sorted array of integers in increasing order and a target value. Your task is to implement a function that finds the last occurrence of the target value in the array using binary search. If the target value is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9113,
"level": 1,
"question": "### Binary Search Problem: Last Occurrence in Sorted Array\n\nYou are given a sorted array of integers in increasing order and a target value. Your task is to implement a function that finds the last occurrence of the target value in the array using bi... |
def my_function(input_string):
"""
This function takes a string input and returns the first 3 characters of the string.
Args:
input_string (str): The input string.
Returns:
str: The first 3 characters of the input string.
"""
return input_string[0:3] | simplelr_Filter | [
{
"content": "Question:\nHere is the code:\n\n```python\ndef my_function(input_string):\n \"\"\"\n This function takes a string input and returns the first 3 characters of the string.\n\n Args:\n input_string (str): The input string.\n\n Returns:\n str: The first 3 characters of the in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9114,
"level": 1,
"question": "Here is the code:\n\n```python\ndef my_function(input_string):\n \"\"\"\n This function takes a string input and returns the first 3 characters of the string.\n\n Args:\n input_string (str): The input string.\n\n Returns:\n st... |
def countDivisibles(A, N, L, R, D):
count = 0
start = L - 1 # Convert to 0-based index
end = R - 1
for i in range(start, end + 1):
if A[i] % D == 0:
count += 1
return count
| simplelr_Taco | [
{
"content": "Question:\nGiven an array A[] of N integers and a range [L, R], you need to count the number of elements within this range (inclusive) that are divisible by a given integer D.\n\nExample 1:\nInput:\nN = 6\nA[] = {1, 2, 3, 4, 5, 6}\nL = 2\nR = 5\nD = 2\nOutput: 2\nExplanation: Elements within the r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9115,
"level": 1,
"question": "Given an array A[] of N integers and a range [L, R], you need to count the number of elements within this range (inclusive) that are divisible by a given integer D.\n\nExample 1:\nInput:\nN = 6\nA[] = {1, 2, 3, 4, 5, 6}\nL = 2\nR = 5\nD = 2\nOutput: 2\... |
def sumFib(N):
a, b = 0, 1
for _ in range(N + 1):
a, b = b, a + b
return a - 1 | simplelr_Apps | [
{
"content": "Question:\n# Fibonacci Sum\n\n*In the Fibonacci sequence, each number is the sum of the two preceding ones*, **_starting from 0 and 1_**, usually denoted as *F(n)* to represent *the nth Fibonacci number*. Given a number N, **_calculate the sum_** of the first N Fibonacci numbers, starting from F(0... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9116,
"level": 1,
"question": "# Fibonacci Sum\n\n*In the Fibonacci sequence, each number is the sum of the two preceding ones*, **_starting from 0 and 1_**, usually denoted as *F(n)* to represent *the nth Fibonacci number*. Given a number N, **_calculate the sum_** of the first N F... |
def print_string_length(s):
if len(s) == 0:
print("The provided string is empty.")
else:
print(f"The string '{s}' has a length of: {len(s)}") | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a string as an argument and prints the length of the string along with the string itself in the format: \"The string 'input_string' has a length of: input_length\". Make sure to handle empty strings by printing \"The provided string is empty.\"\nAnswe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9117,
"level": 1,
"question": "Create a Python function that takes a string as an argument and prints the length of the string along with the string itself in the format: \"The string 'input_string' has a length of: input_length\". Make sure to handle empty strings by printing \"The... |
from typing import List
def find_median_age(ages: List[int]) -> float:
if not ages:
return None
sorted_ages = sorted(ages)
n = len(sorted_ages)
if n % 2 == 0:
mid1 = sorted_ages[(n // 2) - 1]
mid2 = sorted_ages[n // 2]
median = (mid1 + mid2) / 2
else:
median ... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a Python function called `find_median_age` that calculates the median age from a list of ages provided as a parameter. The function should:\n\n1. Accept a list of ages as input.\n2. Sort the list of ages.\n3. Calculate the median value:\n - If the length of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9118,
"level": 1,
"question": "You are required to write a Python function called `find_median_age` that calculates the median age from a list of ages provided as a parameter. The function should:\n\n1. Accept a list of ages as input.\n2. Sort the list of ages.\n3. Calculate the med... |
def count_substring(main: str, search: str) -> int:
"""
This function calculates the frequency of a search string within a main string,
considering both overlapping and non-overlapping occurrences.
Args:
main (str): The main string to search in.
search (str): The substring to search for.
... | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function that accepts two strings as input - a main string and a search string - and returns the frequency of the search string appearing inside the main string, considering both overlapping and non-overlapping occurrences. Also, provide a piece of erroneous code that fa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9119,
"level": 1,
"question": "Design a Python function that accepts two strings as input - a main string and a search string - and returns the frequency of the search string appearing inside the main string, considering both overlapping and non-overlapping occurrences. Also, provid... |
from collections import deque
def bfs_traversal(graph: dict[int, list[int]], start_node: int) -> list[int]:
if start_node not in graph:
return []
visited = set()
queue = deque()
queue.append(start_node)
visited.add(start_node)
result = []
while queue:
current_node ... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function that generates a graph data structure and performs a Breadth-First Search (BFS) on it. The graph will be represented using an adjacency list. Your function should be able to traverse the graph starting from a given node and return the list of node... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9120,
"level": 1,
"question": "You are tasked with creating a function that generates a graph data structure and performs a Breadth-First Search (BFS) on it. The graph will be represented using an adjacency list. Your function should be able to traverse the graph starting from a giv... |
def roman_to_int(roman):
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
values = [roman_dict[c] for c in roman]
total = 0
prev = 0
for current in reversed(values):
if current < prev:
total -= current
else:
total += current
... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that converts a given Roman numeral string to its corresponding integer value.\n\n##### Inputs:\nA single string `roman` that represents a valid Roman numeral. The characters in the string are limited to 'I', 'V', 'X', 'L', 'C', 'D', and 'M' which represent the values 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9121,
"level": 1,
"question": "Write a function that converts a given Roman numeral string to its corresponding integer value.\n\n##### Inputs:\nA single string `roman` that represents a valid Roman numeral. The characters in the string are limited to 'I', 'V', 'X', 'L', 'C', 'D', a... |
def extract_number(s):
result = ''
for char in s:
if char.isdigit():
result += char
return int(result) if result else 0
# Test cases
print(extract_number("abc123def456")) # Output: 123456
print(extract_number("")) # Output: 0
print(extract_number("abcd")) # Output... | simplelr_Filter | [
{
"content": "Question:\nI have a string that I want to convert into a number, but the string contains some invalid characters. I want to extract the number part from the string and ignore the invalid characters.\n\nFor example, input string \"abc123def456\" should output 123456. \n\nI want to write a function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9122,
"level": 1,
"question": "I have a string that I want to convert into a number, but the string contains some invalid characters. I want to extract the number part from the string and ignore the invalid characters.\n\nFor example, input string \"abc123def456\" should output 1234... |
def fahrenheit_to_celsius(F):
return (F - 32) * 5/9 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that converts a given temperature in Fahrenheit to Celsius using the formula `C = (F - 32) * 5/9`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9123,
"level": 1,
"question": "Create a function that converts a given temperature in Fahrenheit to Celsius using the formula `C = (F - 32) * 5/9`.",
"split": "train"
} |
import torch
import numpy as np
def low_pass_filter(image: np.ndarray, radius: float) -> np.ndarray:
# Convert the image to a PyTorch tensor
image_tensor = torch.from_numpy(image).float()
# Get the dimensions of the image
H, W = image_tensor.shape
# Compute the 2D Fourier Transform
F ... | simplelr_Docs | [
{
"content": "Question:\n### PyTorch FFT Coding Assessment Question\n\n#### Problem Statement\n\nYou are given a grayscale image represented as a 2D NumPy array. Your task is to implement a function in PyTorch that performs the following operations:\n\n1. **Compute the 2D Fourier Transform** of the image.\n2. *... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9124,
"level": 1,
"question": "### PyTorch FFT Coding Assessment Question\n\n#### Problem Statement\n\nYou are given a grayscale image represented as a 2D NumPy array. Your task is to implement a function in PyTorch that performs the following operations:\n\n1. **Compute the 2D Four... |
def calculate_total_cost(prices, quantities):
total = 0
for item in quantities:
total += prices[item] * quantities[item]
return total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the total cost (in dollars) of a shopping cart based on the prices of the items and their quantities. The prices are provided in a dictionary where the keys are the item names and the values are the prices per unit. The quantities of the items in the sh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9125,
"level": 1,
"question": "Create a function that calculates the total cost (in dollars) of a shopping cart based on the prices of the items and their quantities. The prices are provided in a dictionary where the keys are the item names and the values are the prices per unit. Th... |
def top_three_keys(d):
items = list(d.items())
sorted_items = sorted(items, key=lambda x: x[1], reverse=True)
return sorted_items[:3] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a dictionary as input and returns the top three keys with the highest values. If there are less than three keys, return all keys with their values sorted in descending order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9126,
"level": 1,
"question": "Create a function that takes a dictionary as input and returns the top three keys with the highest values. If there are less than three keys, return all keys with their values sorted in descending order.",
"split": "train"
} |
def extract_elements(data):
names = [product['name'] for product in data if product['price'] >= 100]
names.sort()
return names | simplelr_Package | [
{
"content": "Question:\nIn this problem, you will be writing a function that manipulates and extracts information from a list of dictionaries. Your task is to create a function named `extract_elements` which takes a single parameter `data`. This parameter is a list of dictionaries, where each dictionary contai... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9127,
"level": 1,
"question": "In this problem, you will be writing a function that manipulates and extracts information from a list of dictionaries. Your task is to create a function named `extract_elements` which takes a single parameter `data`. This parameter is a list of diction... |
def most_frequent_integer(lst):
if not lst:
return None
frequency = {}
for num in lst:
if num in frequency:
frequency[num] += 1
else:
frequency[num] = 1
max_freq = max(frequency.values())
candidates = [num for num, count in frequency.items() ... | simplelr_Evol | [
{
"content": "Question:\nCreate a function that receives a list of integers and returns the most frequently occurring integer in the list. If there are multiple integers with the same highest frequency, return the smallest one. Provide a full implementation, including considerations for edge cases such as an em... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9128,
"level": 1,
"question": "Create a function that receives a list of integers and returns the most frequently occurring integer in the list. If there are multiple integers with the same highest frequency, return the smallest one. Provide a full implementation, including consider... |
def compress_string(s):
if len(s) == 0:
return s
current_char = s[0]
count = 1
compressed = []
for char in s[1:]:
if char == current_char:
count += 1
else:
compressed.append(current_char + str(count))
current_char = char
count... | simplelr_Taco | [
{
"content": "Question:\nYour task is to implement a function to compress a string such that 'aaabbbccc' becomes 'a3b3c3'. Only compress the string if it saves space, so a string like 'abcd' stays 'abcd' since it doesn't shorten the string.\n\nWrite a function \n\n```python\ndef compress_string(s):\n```\n\nIt t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9129,
"level": 1,
"question": "Your task is to implement a function to compress a string such that 'aaabbbccc' becomes 'a3b3c3'. Only compress the string if it saves space, so a string like 'abcd' stays 'abcd' since it doesn't shorten the string.\n\nWrite a function \n\n```python\nd... |
def reverse_string(s):
return s[::-1]
# Example usage:
print(reverse_string("Hello, World!")) # Outputs: "!dlroW ,olleH" | simplelr_Filter | [
{
"content": "Question:\nCan you provide an example of a function in Python that reverses a string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9130,
"level": 1,
"question": "Can you provide an example of a function in Python that reverses a string?",
"split": "train"
} |
from typing import List
def canCompleteCircuit(gas: List[int], cost: List[int]) -> int:
total_gas = sum(gas)
total_cost = sum(cost)
if total_gas < total_cost:
return -1
current = 0
start = 0
n = len(gas)
for i in range(n):
current += gas[i] - cost[i]
if current < 0:
... | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function called `canCompleteCircuit` that takes two lists of integers, `gas` and `cost`, as input. The `gas` list represents the amount of gas available at each gas station, and the `cost` list represents the amount of gas required to travel to the next gas station. Your task is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9131,
"level": 1,
"question": "Write a function called `canCompleteCircuit` that takes two lists of integers, `gas` and `cost`, as input. The `gas` list represents the amount of gas available at each gas station, and the `cost` list represents the amount of gas required to travel to... |
def reverse_string(s):
return s[::-1]
# Example usage:
original_string = "Hello, World!"
reversed_string = reverse_string(original_string)
print(reversed_string) # Output: "!dlroW ,olleH" | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python code snippet to reverse a string? I want to understand how it works too.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9132,
"level": 1,
"question": "Can you help me with a Python code snippet to reverse a string? I want to understand how it works too.",
"split": "train"
} |
def find_first_peak_element_2d(matrix):
if not matrix or len(matrix) == 0:
return (-1, -1)
rows = len(matrix)
cols = len(matrix[0]) if rows > 0 else 0
for i in range(rows):
for j in range(cols):
current = matrix[i][j]
neighbors = []
# Collect all valid... | simplelr_Filter | [
{
"content": "Question:\nHere is a problem:\n\nYou are given a list of numbers, and you need to find the index of the first element that is greater than its neighbors. \n\nExample:\n\nInput: [1, 2, 3, 2, 5, 6, 7, 6, 5, 4]\nOutput: 2\n\nIn this case, the element at index 2 (which is 3) is greater than its neighb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9133,
"level": 1,
"question": "Here is a problem:\n\nYou are given a list of numbers, and you need to find the index of the first element that is greater than its neighbors. \n\nExample:\n\nInput: [1, 2, 3, 2, 5, 6, 7, 6, 5, 4]\nOutput: 2\n\nIn this case, the element at index 2 (whi... |
def count_frequencies(lst):
freq_dict = {}
for num in lst:
if num in freq_dict:
freq_dict[num] += 1
else:
freq_dict[num] = 1
return freq_dict | simplelr_Package | [
{
"content": "Question:\nIn this problem, you are required to write a function that takes a list of integers and returns a dictionary. The dictionary should have the unique integers from the list as keys, and the values should be the frequency of each integer in the list. \n\n### Here are the detailed requireme... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9134,
"level": 1,
"question": "In this problem, you are required to write a function that takes a list of integers and returns a dictionary. The dictionary should have the unique integers from the list as keys, and the values should be the frequency of each integer in the list. \n\n... |
from typing import List
def optimized_bubble_sort(arr: List[int]) -> List[int]:
if not arr:
return []
arr_copy = arr.copy()
n = len(arr_copy)
for i in range(n - 1):
swapped = False
for j in range(n - i - 1):
if arr_copy[j] > arr_copy[j + 1]:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Bubble Sort Optimization and Application Question\n\n**Scenario**: You are working as a software engineer for a company that deals with e-commerce data. One of your tasks includes sorting the total sales data for different products to display them in the monthly report. However, the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9135,
"level": 1,
"question": "### Bubble Sort Optimization and Application Question\n\n**Scenario**: You are working as a software engineer for a company that deals with e-commerce data. One of your tasks includes sorting the total sales data for different products to display them ... |
import bisect
from typing import List
def find_longest_increasing_subsequence(sequence: List[int]) -> int:
if not sequence:
return 0
tails = []
for num in sequence:
index = bisect.bisect_left(tails, num)
if index == len(tails):
tails.append(num)
else:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Longest Increasing Subsequence Challenge\n\nGiven an unsorted array of integers, your task is to determine the length of the longest increasing subsequence (LIS). Your solution should demonstrate the use of dynamic programming with an advanced data structure to optimize performance ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9136,
"level": 1,
"question": "### Longest Increasing Subsequence Challenge\n\nGiven an unsorted array of integers, your task is to determine the length of the longest increasing subsequence (LIS). Your solution should demonstrate the use of dynamic programming with an advanced data... |
def evaluate_expression(s: str) -> int:
tokens = []
current_number = ''
for char in s:
if char in '+-':
tokens.append(int(current_number))
tokens.append(char)
current_number = ''
else:
current_number += char
tokens.append(int(current_number... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` representing a mathematical expression containing digits `0-9`, the plus `+` sign, and the minus `-` sign. There are no parentheses and the input string will always be valid. Implement a function to evaluate the expression and return the result. The input expr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9137,
"level": 1,
"question": "You are given a string `s` representing a mathematical expression containing digits `0-9`, the plus `+` sign, and the minus `-` sign. There are no parentheses and the input string will always be valid. Implement a function to evaluate the expression an... |
def diagonalSums(matrix):
n = len(matrix)
primary = 0
secondary = 0
for i in range(n):
primary += matrix[i][i]
secondary += matrix[i][n - 1 - i]
return (primary, secondary)
| simplelr_Taco | [
{
"content": "Question:\nYou are given a square matrix of integers. The task is to find the sum of the elements on its primary diagonal and the sum of the elements on its secondary diagonal. \n\nThe primary diagonal of a square matrix runs from the top left to the bottom right, and the secondary diagonal runs f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9138,
"level": 1,
"question": "You are given a square matrix of integers. The task is to find the sum of the elements on its primary diagonal and the sum of the elements on its secondary diagonal. \n\nThe primary diagonal of a square matrix runs from the top left to the bottom right... |
def mergeAlternatingCharacters(A, B):
result = []
max_len = max(len(A), len(B))
for i in range(max_len):
if i < len(A):
result.append(A[i])
if i < len(B):
result.append(B[i])
return ''.join(result)
| simplelr_Taco | [
{
"content": "Question:\nGiven two strings A and B, the task is to merge them into a new string C using the following rules:\n1. Start with A and B as input.\n2. Pick characters in alternating order from A and B starting with the first character of A.\n3. If one string is exhausted before the other, append the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9139,
"level": 1,
"question": "Given two strings A and B, the task is to merge them into a new string C using the following rules:\n1. Start with A and B as input.\n2. Pick characters in alternating order from A and B starting with the first character of A.\n3. If one string is exha... |
def is_adidas_product(name):
return name == "ULTRA BOOST 21 MAIN" | simplelr_Filter | [
{
"content": "Question:\nWrite a Python 3 code to identify the the ADIDAS product from the given name list. If the given name is \"ULTRA BOOST 21 MAIN\" return True.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9140,
"level": 1,
"question": "Write a Python 3 code to identify the the ADIDAS product from the given name list. If the given name is \"ULTRA BOOST 21 MAIN\" return True.",
"split": "train"
} |
from typing import List, Tuple
def find_max_subarray_sum(array: List[int]) -> Tuple[int, Tuple[int, int]]:
if not array:
return (0, (0, 0)) # Handle empty array case, though constraints say n >=1
n = len(array)
max_current = array[0]
max_sum = array[0]
current_start = 0
current_en... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question:\n\nYou are provided with an array of integers. Write a function `find_max_subarray_sum(array: List[int]) -> Tuple[int, Tuple[int, int]]` that implements Kadane's Algorithm to find the maximum sum of a contiguous subarray.\n\nAdditionally, the function should return the sta... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9141,
"level": 1,
"question": "### Question:\n\nYou are provided with an array of integers. Write a function `find_max_subarray_sum(array: List[int]) -> Tuple[int, Tuple[int, int]]` that implements Kadane's Algorithm to find the maximum sum of a contiguous subarray.\n\nAdditionally,... |
def replace_words_with_lengths(s):
return ' '.join(str(len(word)) for word in s.split())
# Example usage:
print(replace_words_with_lengths("Hello World")) # Output: "5 5" | simplelr_Filter | [
{
"content": "Question:\nHow can I replace all the words in a string with their lengths in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9142,
"level": 1,
"question": "How can I replace all the words in a string with their lengths in Python?",
"split": "train"
} |
import string
def word_frequency(input_string):
# Create a translation table to remove punctuation
translation_table = str.maketrans('', '', string.punctuation)
# Convert to lowercase and remove punctuation
cleaned_string = input_string.lower().translate(translation_table)
# Split into words
wo... | simplelr_Package | [
{
"content": "Question:\n### Task:\nYou need to write a function that takes a string of words separated by spaces, and returns a dictionary with each word as the key and the frequency of that word as the value. If a word appears more than once, it should return the frequency of how many times it appears within ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9143,
"level": 1,
"question": "### Task:\nYou need to write a function that takes a string of words separated by spaces, and returns a dictionary with each word as the key and the frequency of that word as the value. If a word appears more than once, it should return the frequency o... |
def max_visitors(entries: list[int], exits: list[int]) -> int:
events = []
for e in entries:
events.append((e, 1))
for x in exits:
events.append((x, -1))
# Sort by time, and for same time, exit events come before enter events
events.sort(key=lambda x: (x[0], x[1]))
curr... | simplelr_Algorithm | [
{
"content": "Question:\n## Problem Statement\n\nYou are helping a museum to track visitor statistics. The museum records the entry and exit times of each visitor through a turnstile. Your task is to write a Python function that calculates the maximum number of visitors present in the museum at any given time b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9144,
"level": 1,
"question": "## Problem Statement\n\nYou are helping a museum to track visitor statistics. The museum records the entry and exit times of each visitor through a turnstile. Your task is to write a Python function that calculates the maximum number of visitors presen... |
def reorder_list(items, operations):
reordered = items.copy()
for i, j in operations:
reordered[i], reordered[j] = reordered[j], reordered[i]
return reordered | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reorder a list of items based on a given list of operations. Each operation is a tuple consisting of two integers representing the indices of the two elements to be swapped. The function should handle an arbitrary number of operations.\nAnswer:\nLet's think st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9145,
"level": 1,
"question": "Write a python function to reorder a list of items based on a given list of operations. Each operation is a tuple consisting of two integers representing the indices of the two elements to be swapped. The function should handle an arbitrary number of o... |
def count_lines_in_file(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
return len(lines) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the number of lines in a text file. The function should take the file path as an argument and return the number of lines.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9146,
"level": 1,
"question": "Write a python function to find the number of lines in a text file. The function should take the file path as an argument and return the number of lines.",
"split": "train"
} |
def is_strictly_increasing(lst):
for i in range(1, len(lst)):
if lst[i] <= lst[i-1]:
return False
return True | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that checks if a given list of integers is strictly increasing. A list is considered strictly increasing if each element is greater than the preceding one. The function should return `True` if the list is strictly increasing, otherwise `False`.\nAnswer:\nLet's th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9147,
"level": 1,
"question": "Write a Python function that checks if a given list of integers is strictly increasing. A list is considered strictly increasing if each element is greater than the preceding one. The function should return `True` if the list is strictly increasing, ot... |
import math
def is_perfect_square(n):
if n < 0:
return False
if n == 0:
return True
s = math.isqrt(n)
return s * s == n | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as input and returns a boolean value that corresponds to whether or not that integer is a perfect square.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9148,
"level": 1,
"question": "Create a function that takes an integer as input and returns a boolean value that corresponds to whether or not that integer is a perfect square.",
"split": "train"
} |
def merge_sorted_arrays(arr1, arr2):
i = j = 0
result = []
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
result.append(arr1[i])
i += 1
else:
result.append(arr2[j])
j += 1
if i < len(arr1):
result += arr1[i:]
if j... | simplelr_Taco | [
{
"content": "Question:\nWrite a function `merge_sorted_arrays(arr1, arr2)` that merges two sorted lists into a single sorted list. The function should be as efficient as possible. \n\nThe input will be two non-empty lists of integers, which are already sorted in non-decreasing order.\n\nHere are some sample ca... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9149,
"level": 1,
"question": "Write a function `merge_sorted_arrays(arr1, arr2)` that merges two sorted lists into a single sorted list. The function should be as efficient as possible. \n\nThe input will be two non-empty lists of integers, which are already sorted in non-decreasin... |
def reorganize_string(s: str) -> str:
from collections import defaultdict
count = defaultdict(int)
for c in s:
count[c] += 1
n = len(s)
max_count = (n + 1) // 2
# Check if any character's count exceeds the maximum allowed
for c in count:
if count[c] > max_count:
... | simplelr_Taco | [
{
"content": "Question:\nGiven a string $s$ consisting of lowercase Latin letters, we want to reorganize the string such that any two adjacent characters are not the same. If it is not possible to reorganize the string in this way, return an empty string.\n\nFor example, the string \"aab\" can be reorganized as... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9150,
"level": 1,
"question": "Given a string $s$ consisting of lowercase Latin letters, we want to reorganize the string such that any two adjacent characters are not the same. If it is not possible to reorganize the string in this way, return an empty string.\n\nFor example, the s... |
from collections import deque
from typing import List
def find_course_order(num_courses: int, prerequisites: List[tuple[int, int]]) -> List[int]:
# Build the adjacency list and in-degree array
adj = [[] for _ in range(num_courses)]
in_degree = [0] * num_courses
for a, b in prerequisites:
a... | simplelr_Algorithm | [
{
"content": "Question:\n### **Coding Assessment Question**\n\n**Objective**:\nYou are tasked with implementing a functionality to determine the order of courses one has to take given a list of course prerequisites. Your implementation should handle cyclical dependencies and provide an error message if a cycle ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9151,
"level": 1,
"question": "### **Coding Assessment Question**\n\n**Objective**:\nYou are tasked with implementing a functionality to determine the order of courses one has to take given a list of course prerequisites. Your implementation should handle cyclical dependencies and p... |
def task_func(input_list):
even_numbers = [num for num in input_list if num % 2 == 0]
odd_numbers = [num for num in input_list if num % 2 != 0]
return (even_numbers, odd_numbers) | simplelr_Package | [
{
"content": "Question:\nGenerate a list of integers, and create two functions: one for filtering even numbers and another for filtering odd numbers. Ensure you use list comprehension in both functions. The function should output the filtered lists for both even and odd numbers.\nThe function inputs should incl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9152,
"level": 1,
"question": "Generate a list of integers, and create two functions: one for filtering even numbers and another for filtering odd numbers. Ensure you use list comprehension in both functions. The function should output the filtered lists for both even and odd number... |
import random
def dice_game(player1: str, player2: str) -> str:
"""Simulate rolling two six-sided dice for each player and determine the winner.
Randomly roll two dice for each player, sum their values, and compare.
Args:
player1 (str): The name of the first player.
player2 (str): The name of the... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that simulates a dice game between two players. The function should:\n1. Simulate the rolling of two six-sided dice for each player.\n2. Calculate the sum of the values from the two dice.\n3. Compare the sum for each player to determine the winner.\n4. Handle ties appro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9153,
"level": 1,
"question": "Write a function that simulates a dice game between two players. The function should:\n1. Simulate the rolling of two six-sided dice for each player.\n2. Calculate the sum of the values from the two dice.\n3. Compare the sum for each player to determin... |
def separate_even_odd(numbers):
even_numbers = []
odd_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
else:
odd_numbers.append(num)
return even_numbers, odd_numbers | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function to return the list of values in two separate lists for even and odd numbers in a given list, without using built-in functions like filter, map or list comprehensions. Additionally, ensure that function performance is optimized for large input lists.\nAnswer:\nLe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9154,
"level": 1,
"question": "Design a Python function to return the list of values in two separate lists for even and odd numbers in a given list, without using built-in functions like filter, map or list comprehensions. Additionally, ensure that function performance is optimized ... |
def multiply_by_two(nums):
return [num * 2 for num in nums] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that accepts a list of integers and returns a new list where each element of the original list is multiplied by 2.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9155,
"level": 1,
"question": "Write a Python function that accepts a list of integers and returns a new list where each element of the original list is multiplied by 2.",
"split": "train"
} |
import os
def process_file_paths(paths: list) -> dict:
files = []
directories = []
links = []
non_existing = []
for path in paths:
# Expand environment variables and user references, then make absolute
expanded_vars = os.path.expandvars(path)
expanded_user = os.path.exp... | simplelr_Docs | [
{
"content": "Question:\n### Python Coding Assessment Question: Complex Path Manipulation and Validation\n\n#### Objective:\nCreate a Python function that processes a list of file paths. The function will normalize each path, check the existence of each path, and return a dictionary categorizing the paths based... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9156,
"level": 1,
"question": "### Python Coding Assessment Question: Complex Path Manipulation and Validation\n\n#### Objective:\nCreate a Python function that processes a list of file paths. The function will normalize each path, check the existence of each path, and return a dict... |
def merge_intervals(intervals, new_interval):
# Create a copy to avoid modifying the original list
intervals = list(intervals)
intervals.append(new_interval)
# Sort the intervals based on the start time
sorted_intervals = sorted(intervals, key=lambda x: x[0])
if not sorted_intervals:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `n` intervals, where each interval is represented as a tuple `(start, end)`. An interval `(start, end)` represents a continuous range of integers from `start` to `end` (both inclusive). Your goal is to insert a new interval `(new_start, new_end)` into the list of... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9157,
"level": 1,
"question": "You are given a list of `n` intervals, where each interval is represented as a tuple `(start, end)`. An interval `(start, end)` represents a continuous range of integers from `start` to `end` (both inclusive). Your goal is to insert a new interval `(ne... |
def second_smallest(numbers):
unique_sorted = sorted(set(numbers))
if len(unique_sorted) >= 2:
return unique_sorted[1]
else:
return None | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the second smallest number in a list of integers. Your function 'second_smallest' should accept a single list of integers as its input and return the second smallest element in the list. If the list does not contain enough unique elements to determine a s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9158,
"level": 1,
"question": "Write a python function to find the second smallest number in a list of integers. Your function 'second_smallest' should accept a single list of integers as its input and return the second smallest element in the list. If the list does not contain enou... |
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
a, b = 0, 1
for i in range(2, n + 1):
c = a + b
a = b
b = c
return b | simplelr_Filter | [
{
"content": "Question:\nThis code defines a function named `fibonacci` that takes one argument, `n`, which represents the position of the desired Fibonacci number in the sequence.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9159,
"level": 1,
"question": "This code defines a function named `fibonacci` that takes one argument, `n`, which represents the position of the desired Fibonacci number in the sequence.",
"split": "train"
} |
import re
from collections import Counter
def word_frequencies(k, paragraph):
# Extract all words as sequences of alphabetic characters
words = re.findall(r'[A-Za-z]+', paragraph)
# Convert all words to lowercase
words_lower = [word.lower() for word in words]
# Count the frequency of each word
... | simplelr_Taco | [
{
"content": "Question:\nWrite a program that reads a paragraph of text and performs the following operations:\n 1. Counts the frequency of each word in the paragraph.\n 2. Reports the k highest-frequency words in descending order of frequency.\n 3. If two words have the same frequency, they should be sorted... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9160,
"level": 1,
"question": "Write a program that reads a paragraph of text and performs the following operations:\n 1. Counts the frequency of each word in the paragraph.\n 2. Reports the k highest-frequency words in descending order of frequency.\n 3. If two words have the sa... |
import math
def is_perfect_square(n):
if n < 0:
print(f"{n} is not a perfect square.")
return False
s = math.isqrt(n)
if s * s == n:
print(f"The square root of {n} is {s}.")
return True
else:
print(f"{n} is not a perfect square.")
return False | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that checks if a given number is a perfect square and returns a boolean value? If the number is a perfect square, the function should also print the square root. If not, it should print a message stating that the number is not a perfect square.\nAnswer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9161,
"level": 1,
"question": "How can I create a Python function that checks if a given number is a perfect square and returns a boolean value? If the number is a perfect square, the function should also print the square root. If not, it should print a message stating that the numb... |
def twoSum(nums, target):
left = 0
right = len(nums) - 1
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == target:
return [left + 1, right + 1]
elif current_sum < target:
left += 1
else:
right -= 1
return [-1,... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to solve the following problem: Given a sorted array of integers `nums` and an integer `target`, write a function `twoSum` that returns the indices of the two numbers such that they add up to the target. The indices are 1-based, not 0-based. If no such two number... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9162,
"level": 1,
"question": "Write a python function to solve the following problem: Given a sorted array of integers `nums` and an integer `target`, write a function `twoSum` that returns the indices of the two numbers such that they add up to the target. The indices are 1-based,... |
def number_to_column(n):
result = ""
while n > 0:
n -= 1
rem = n % 26
result = chr(65 + rem) + result
n = n // 26
return result
| simplelr_Taco | [
{
"content": "Question:\nGiven an integer, return its corresponding column title as it appears in an Excel sheet.\n\nFor example:\n\n\n 1 -> A\n 2 -> B\n 3 -> C\n ...\n 26 -> Z\n 27 -> AA\n 28 -> AB \n ...\n\n\nExample 1:\n\n\nInput: 1\nOutput: \"A\"\n\n\nExample 2:\n\n\nInput: 28\nOutpu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9163,
"level": 1,
"question": "Given an integer, return its corresponding column title as it appears in an Excel sheet.\n\nFor example:\n\n\n 1 -> A\n 2 -> B\n 3 -> C\n ...\n 26 -> Z\n 27 -> AA\n 28 -> AB \n ...\n\n\nExample 1:\n\n\nInput: 1\nOutput: \"A\"\n\... |
def power(base, exponent):
if exponent == 0:
return 1.0
elif exponent > 0:
return base * power(base, exponent - 1)
else:
return 1.0 / power(base, -exponent) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the power of a number using recursion. The function should handle both positive and negative exponents, and return the result as a floating-point number.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9164,
"level": 1,
"question": "Write a function to calculate the power of a number using recursion. The function should handle both positive and negative exponents, and return the result as a floating-point number.",
"split": "train"
} |
def digit_Reorder(n):
if n == 0:
return 0
sign = 1
if n < 0:
sign = -1
digits = str(abs(n))
sorted_digits = sorted(digits, reverse=True)
number_str = ''.join(sorted_digits)
result = int(number_str)
return sign * result | simplelr_Apps | [
{
"content": "Question:\nCreate a function that receives an integer `n` and returns the integer with all its digits rearranged in non-ascending order. If the number is negative, the function should rearrange the digits of the absolute value in non-ascending order and return the negative of the resulting number.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9165,
"level": 1,
"question": "Create a function that receives an integer `n` and returns the integer with all its digits rearranged in non-ascending order. If the number is negative, the function should rearrange the digits of the absolute value in non-ascending order and return th... |
def square_even_numbers(numbers):
return [num ** 2 for num in numbers if num % 2 == 0] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that takes a list of integers and returns a new list with the squares of the original numbers, but only for those numbers that are even.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9166,
"level": 1,
"question": "Write a Python program that takes a list of integers and returns a new list with the squares of the original numbers, but only for those numbers that are even.",
"split": "train"
} |
def factorial(number):
result = 1
for i in range(1, number + 1):
result *= i
return result
# Example usage
number = 5
print(f"The factorial of {number} is {factorial(number)}") | simplelr_Filter | [
{
"content": "Question:\nI am a computer science student and I need to write a program that calculates the factorial of a given number. Can you help me understand the concept of factorial and provide a simple code example in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9167,
"level": 1,
"question": "I am a computer science student and I need to write a program that calculates the factorial of a given number. Can you help me understand the concept of factorial and provide a simple code example in Python?",
"split": "train"
} |
def sum_of_args(*args):
return sum(args) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts a variable number of arguments. The function should return their sum.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9168,
"level": 1,
"question": "Create a function that accepts a variable number of arguments. The function should return their sum.",
"split": "train"
} |
def find_triangular_number(n: int) -> int:
# Check if the input is an integer
if type(n) is not int:
raise TypeError(f"Input value of [number={n}] must be an integer")
# Check if the input is a positive integer
if n < 1:
raise ValueError("Input must be a positive integer")
# Calculat... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Nth Triangular Number Finder\n\nYou are given a positive integer `n` representing the position of a triangular number in the sequence. Your task is to implement a function `find_triangular_number(n: int) -> int` which calculates the nth triangular number using the formula ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9169,
"level": 1,
"question": "### Question: Nth Triangular Number Finder\n\nYou are given a positive integer `n` representing the position of a triangular number in the sequence. Your task is to implement a function `find_triangular_number(n: int) -> int` which calculates the nth t... |
import re
def is_palindrome(s):
cleaned = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
return cleaned == cleaned[::-1] | simplelr_Filter | [
{
"content": "Question:\nA palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). The term \"level\" is an example of a palindrome since \"level\" spelled backwards is \"level\". Write a function that det... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9170,
"level": 1,
"question": "A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). The term \"level\" is an example of a palindrome since \"level\" spelled backwards is \... |
from collections import defaultdict
def find_anagrams(words_list: list) -> dict:
anagrams = defaultdict(list)
for word in words_list:
key = ''.join(sorted(word))
anagrams[key].append(word)
return dict(anagrams) | simplelr_Algorithm | [
{
"content": "Question:\n### Anagram Finder\n\n**Context**:\nYou are tasked with developing a function for a text analysis software to identify anagrams from a list of words. An anagram is a word formed by rearranging the letters of a different word, typically using all the original letters exactly once.\n\n**T... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9171,
"level": 1,
"question": "### Anagram Finder\n\n**Context**:\nYou are tasked with developing a function for a text analysis software to identify anagrams from a list of words. An anagram is a word formed by rearranging the letters of a different word, typically using all the or... |
def find_unique_pairs_with_difference_one(vector):
unique = set(vector)
sorted_unique = sorted(unique)
result = []
for x in sorted_unique:
if (x + 1) in unique:
result.append((x, x + 1))
return result | simplelr_Filter | [
{
"content": "Question:\nI have a vector of integers. Some of these integers are repeated more than once. I want to find all the unique pairs of integers in the vector that have a difference of exactly 1.\n\nFor example: \nInput vector: [1, 2, 3, 2, 1]\nOutput: [(1, 2), (2, 3)]\n\nNote that (2, 1) and (3, 2) ar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9172,
"level": 1,
"question": "I have a vector of integers. Some of these integers are repeated more than once. I want to find all the unique pairs of integers in the vector that have a difference of exactly 1.\n\nFor example: \nInput vector: [1, 2, 3, 2, 1]\nOutput: [(1, 2), (2, 3)... |
def binary_search(tree, target):
low = 0
high = len(tree) - 1
while low <= high:
mid = (low + high) // 2
if tree[mid] == target:
return mid
elif tree[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1 # Return -1 if target is... | simplelr_Filter | [
{
"content": "Question:\nHere is a Python function implementing binary search:\n```python\ndef binary_search(tree, target):\n low = 0\n high = len(tree) - 1\n\n while low <= high:\n mid = (low + high) // 2\n if tree[mid] == target:\n return mid\n elif tree[mid] < target:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9173,
"level": 1,
"question": "Here is a Python function implementing binary search:\n```python\ndef binary_search(tree, target):\n low = 0\n high = len(tree) - 1\n\n while low <= high:\n mid = (low + high) // 2\n if tree[mid] == target:\n return mi... |
def add_strings(num1, num2):
sum_value = int(num1) + int(num2)
return str(sum_value) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to add two numbers in Python, but the numbers are stored as strings. The function should return the result as a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9174,
"level": 1,
"question": "Write a function to add two numbers in Python, but the numbers are stored as strings. The function should return the result as a string.",
"split": "train"
} |
def extract_first_letters(s):
return ''.join(word[0] for word in s.split())
# Example usage:
print(extract_first_letters("Hello World Python")) # Outputs: "HWP"
print(extract_first_letters("Python is awesome")) # Outputs: "PIA" | simplelr_Filter | [
{
"content": "Question:\nHow can I extract the first letter of each word in a string using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9175,
"level": 1,
"question": "How can I extract the first letter of each word in a string using Python?",
"split": "train"
} |
def find_majority_element(elements: list[int]) -> int | None:
if not elements:
return None
# Find the candidate for majority element using Boyer-Moore algorithm
count = 0
candidate = None
for num in elements:
if count == 0:
candidate = num
count = 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario:\nYou need to develop an algorithm that finds the majority element in a list of integers. A majority element is an element that appears more than half the time in the list. If no such element exists, the algorithm should return `None`.\n\n### Requirements:\n1. Implement a f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9176,
"level": 1,
"question": "### Scenario:\nYou need to develop an algorithm that finds the majority element in a list of integers. A majority element is an element that appears more than half the time in the list. If no such element exists, the algorithm should return `None`.\n\n... |
def are_values_within_range(dictionary, lower_bound, upper_bound):
if not dictionary:
return True
for value in dictionary.values():
if value < lower_bound or value > upper_bound:
return False
return True | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to determine if all the values in one dictionary are within a specified range. The function should take three parameters: `dictionary` (the dictionary to check), `lower_bound` (the minimum allowed value), and `upper_bound` (the maximum allowed value). The function shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9177,
"level": 1,
"question": "Write a function to determine if all the values in one dictionary are within a specified range. The function should take three parameters: `dictionary` (the dictionary to check), `lower_bound` (the minimum allowed value), and `upper_bound` (the maximum... |
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:\nReverse the following string without using any built-in reverse functions and without using any data structures (like arrays or lists). Your solution should have a time complexity of O(n), where n is the length of the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9178,
"level": 1,
"question": "Reverse the following string without using any built-in reverse functions and without using any data structures (like arrays or lists). Your solution should have a time complexity of O(n), where n is the length of the string.",
"split": "train"
} |
def merge_sorted_lists(list1, list2):
merged = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
merged.append(list1[i])
i += 1
else:
merged.append(list2[j])
j += 1
# Add remaining elements from list1
merged... | simplelr_Filter | [
{
"content": "Question:\nPlease write a Python code snippet to merge two sorted lists into a single sorted list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9179,
"level": 1,
"question": "Please write a Python code snippet to merge two sorted lists into a single sorted list.",
"split": "train"
} |
def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings `str1` and `str2`, each consisting of lowercase English letters. Determine whether the two strings are **anagrams** of each other. Two strings are considered anagrams if they contain the same characters, with the same frequencies. Return `true` _if `str1` and ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9180,
"level": 1,
"question": "You are given two strings `str1` and `str2`, each consisting of lowercase English letters. Determine whether the two strings are **anagrams** of each other. Two strings are considered anagrams if they contain the same characters, with the same frequenc... |
def canCompleteMarathon(N, tokens):
for token in tokens:
if token == 0:
return False
return True
| simplelr_Taco | [
{
"content": "Question:\nYou are organizing a marathon where participants need to collect tokens at various checkpoints throughout the course. Each participant starts with zero tokens and can collect a variable number of tokens at each checkpoint. However, there's a rule: if a participant fails to collect any t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9181,
"level": 1,
"question": "You are organizing a marathon where participants need to collect tokens at various checkpoints throughout the course. Each participant starts with zero tokens and can collect a variable number of tokens at each checkpoint. However, there's a rule: if a... |
def max_apples(grid):
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
prev_row = [0] * n
prev_row[0] = grid[0][0]
for j in range(1, n):
prev_row[j] = prev_row[j-1] + grid[0][j]
for i in range(1, m):
current_row = [0] * n
curr... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a `m x n` grid representing a farm where each cell in the grid has a non-negative integer representing the number of apples in that cell, determine the maximum number of apples you can collect by starting at the top-left corner of the grid and moving to the bottom-right corner. Yo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9182,
"level": 1,
"question": "Given a `m x n` grid representing a farm where each cell in the grid has a non-negative integer representing the number of apples in that cell, determine the maximum number of apples you can collect by starting at the top-left corner of the grid and mo... |
import csv
def read_csv_to_dict_list(filename):
with open(filename, 'r') as csvfile:
csvreader = csv.DictReader(csvfile)
list_of_dicts = [row for row in csvreader]
return list_of_dicts
# Example usage:
# data = read_csv_to_list_of_dicts('yourfile.csv') | simplelr_Filter | [
{
"content": "Question:\nIn Python, how do I read a CSV file and store the data in a list of dictionaries?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9183,
"level": 1,
"question": "In Python, how do I read a CSV file and store the data in a list of dictionaries?",
"split": "train"
} |
def max_heights_visible(heights, w):
n = len(heights)
if n == 0:
return []
# Precompute the sparse table
max_level = 0
while (1 << max_level) <= n:
max_level += 1
max_level -= 1
st = [[0] * n for _ in range(max_level + 1)]
for i in range(n):
st[0][i] = h... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `heights` representing the heights of buildings on an infinitely long street. The array `heights` is guaranteed to have a length greater than or equal to 1. You are also given an integer `w` and you have an endoscope with a maximum distance view of `2w` un... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9184,
"level": 1,
"question": "You are given an integer array `heights` representing the heights of buildings on an infinitely long street. The array `heights` is guaranteed to have a length greater than or equal to 1. You are also given an integer `w` and you have an endoscope with... |
from collections import defaultdict, deque
def is_graph_acyclic_bipartite(u, v):
if not u and not v:
return True # Empty graph is trivially acyclic and bipartite
# Build directed adjacency list and in-degree dictionary
directed_adj = defaultdict(list)
in_degree = defaultdict(int)
nodes = ... | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function to check if the elements of two 1D arrays, representing a directed graph's edges, can form a graph that is both acyclic and bipartite. The function should return `True` if such a graph can be formed, and `False` otherwise. Validate this function with provided te... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9185,
"level": 1,
"question": "Design a Python function to check if the elements of two 1D arrays, representing a directed graph's edges, can form a graph that is both acyclic and bipartite. The function should return `True` if such a graph can be formed, and `False` otherwise. Vali... |
def longest_subarray_with_sum(nums, S):
sum_map = {0: -1}
current_sum = 0
max_length = 0
for i, num in enumerate(nums):
current_sum += num
target = current_sum - S
if target in sum_map:
length = i - sum_map[target]
if length > max_length:
m... | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers and an integer `S`, return the length of the longest contiguous subarray that sums up to exactly `S`. If there is no such subarray, return 0.\n\nExample 1:\nInput: nums = [1, -1, 5, -2, 3], S = 3\nOutput: 4\nExplanation: The subarray [1, -1, 5, -2] sums to 3 a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9186,
"level": 1,
"question": "Given an array of integers and an integer `S`, return the length of the longest contiguous subarray that sums up to exactly `S`. If there is no such subarray, return 0.\n\nExample 1:\nInput: nums = [1, -1, 5, -2, 3], S = 3\nOutput: 4\nExplanation: The ... |
def sort_list(nums):
return sorted(nums) | simplelr_Filter | [
{
"content": "Question:\n### Make a function that takes a list of integers and returns a new list with the integers in non-decreasing order. \n\n```python\ndef sort_list(nums):\n # Create a copy of the input list to avoid modifying the original list\n nums_copy = nums.copy()\n\n # Iterate over the list... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9187,
"level": 1,
"question": "### Make a function that takes a list of integers and returns a new list with the integers in non-decreasing order. \n\n```python\ndef sort_list(nums):\n # Create a copy of the input list to avoid modifying the original list\n nums_copy = nums.co... |
def sort_colors(nums: list[int]) -> None:
low = 0
mid = 0
high = len(nums) - 1
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else:
nums... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Sort Colors Challenge\n\n**Objective**:\n\nYou are given an array containing integers `0`, `1`, and `2` representing the colors red, white, and blue respectively. Write a function to sort the array so that all instances of `0` come before `1`s and all `1`s come before `2`s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9188,
"level": 1,
"question": "### Question: Sort Colors Challenge\n\n**Objective**:\n\nYou are given an array containing integers `0`, `1`, and `2` representing the colors red, white, and blue respectively. Write a function to sort the array so that all instances of `0` come before... |
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1) | simplelr_Filter | [
{
"content": "Question:\nDefine a function in Python that calculates the factorial of a given positive integer. The factorial of a positive integer \\( n \\) is the product of all positive integers less than or equal to \\( n \\). For example, the factorial of 5 is \\( 5 \\times 4 \\times 3 \\times 2 \\times 1 ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9189,
"level": 1,
"question": "Define a function in Python that calculates the factorial of a given positive integer. The factorial of a positive integer \\( n \\) is the product of all positive integers less than or equal to \\( n \\). For example, the factorial of 5 is \\( 5 \\tim... |
from typing import List, Tuple
def max_non_overlapping_intervals(intervals: List[Tuple[int, int]]) -> int:
# Sort intervals based on their end times
sorted_intervals = sorted(intervals, key=lambda x: x[1])
count = 0
last_end = -1 # Initializing to -1 to handle the first interval correctly
... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are working for a company that develops container orchestration systems. Part of your job involves ensuring efficient resource allocation within a distributed network. You've been tasked with implementing an algorithm that calculates the maximum number of non-overlappi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9190,
"level": 1,
"question": "### Scenario\nYou are working for a company that develops container orchestration systems. Part of your job involves ensuring efficient resource allocation within a distributed network. You've been tasked with implementing an algorithm that calculates ... |
def find_maximum(lst):
if not lst:
return None
return max(lst) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the maximum element in a given list of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9191,
"level": 1,
"question": "Write a Python function to find the maximum element in a given list of integers.",
"split": "train"
} |
from typing import List
def is_sorted(stack: List[int]) -> bool:
for i in range(len(stack) - 1):
if stack[i] > stack[i+1]:
return False
return True | simplelr_Data_Structure | [
{
"content": "Question:\n**Problem Statement**:\n\nYou are given a stack implemented as a list. Your task is to implement the function `is_sorted`, which takes this stack as input and returns `True` if the elements in the stack are in ascending order from bottom to top, and `False` otherwise. The function must ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9192,
"level": 1,
"question": "**Problem Statement**:\n\nYou are given a stack implemented as a list. Your task is to implement the function `is_sorted`, which takes this stack as input and returns `True` if the elements in the stack are in ascending order from bottom to top, and `F... |
def find_common_elements(list1, list2):
set1 = set(list1)
set2 = set(list2)
common = set1 & set2
return list(common) | simplelr_Filter | [
{
"content": "Question:\nWrite a function `find_common_elements` that takes in two lists of integers and returns a list containing the common elements between the two lists. The returned list should not contain any duplicates.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9193,
"level": 1,
"question": "Write a function `find_common_elements` that takes in two lists of integers and returns a list containing the common elements between the two lists. The returned list should not contain any duplicates.",
"split": "train"
} |
def merge(intervals):
if not intervals:
return []
# Sort the intervals by start time
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
last = merged[-1]
if current[0] <= last[1]:
# Merge the intervals
merged[-1] =... | simplelr_Filter | [
{
"content": "Question:\nHere's the problem: Given an array of intervals where each interval is a pair (start, end), merge all overlapping intervals into one, and return the merged intervals.\n\nExample: Input intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]]\n\nMy solution:\n```python\nde... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9194,
"level": 1,
"question": "Here's the problem: Given an array of intervals where each interval is a pair (start, end), merge all overlapping intervals into one, and return the merged intervals.\n\nExample: Input intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,... |
def max_coins(grid):
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
prev_row = [0] * n
prev_row[0] = grid[0][0]
for j in range(1, n):
prev_row[j] = prev_row[j-1] + grid[0][j]
for i in range(1, m):
current_row = [0] * n
current_ro... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a grid represented by a 2D integer array `grid` of size `m x n`. Each cell in the grid contains a non-negative integer which represents the number of coins in that cell. You start at the top-left cell `(0, 0)` and you need to reach the bottom-right cell `(m-1, n-1)`. From ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9195,
"level": 1,
"question": "You are given a grid represented by a 2D integer array `grid` of size `m x n`. Each cell in the grid contains a non-negative integer which represents the number of coins in that cell. You start at the top-left cell `(0, 0)` and you need to reach the bo... |
def checkSubarraySum(nums, k):
n = len(nums)
if n < 2:
return False
prefix = [0] * (n + 1)
for i in range(n):
prefix[i+1] = prefix[i] + nums[i]
if k == 0:
sum_map = {prefix[0]: 0}
for j in range(1, n+1):
current_sum = prefix[j]
if current_sum... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` and an integer `k`. Your task is to determine whether there is a continuous subarray of size at least 2 that sums up to a multiple of `k`. In other words, should exist integers `i`, `j` with `j > i` such that `(sum(nums[i] ... nums[j])) % k == 0`. I... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9196,
"level": 1,
"question": "You are given an integer array `nums` and an integer `k`. Your task is to determine whether there is a continuous subarray of size at least 2 that sums up to a multiple of `k`. In other words, should exist integers `i`, `j` with `j > i` such that `(sum... |
def print_pattern(n):
for i in range(1, n + 1):
for j in range(n - i + 1, 0, -1):
print("*", end=" ")
print() | simplelr_Filter | [
{
"content": "Question:\nThis is my code:\n\n```python\ndef print_pattern(n):\n for i in range(1, n + 1):\n for j in range((n - i), 0, -1):\n print(\"*\", end=\" \")\n print()\n\nprint_pattern(5)\n```\n\nThis creates the following output:\n\n```\n* * * * * \n* * * * \n* * * \n* * \n*\n```\n\nI would... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9197,
"level": 1,
"question": "This is my code:\n\n```python\ndef print_pattern(n):\n for i in range(1, n + 1):\n for j in range((n - i), 0, -1):\n print(\"*\", end=\" \")\n print()\n\nprint_pattern(5)\n```\n\nThis creates the following output:\n\n```\n* * * * * \n* * * ... |
def four_sum(arr, target):
arr.sort()
result = []
n = len(arr)
if n < 4:
return result
for i in range(n - 3):
if i > 0 and arr[i] == arr[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and arr[j] == arr[j - 1]:
continue... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes an array of integers and a target integer as input. The function should return a list of all unique quadruplets [a, b, c, d] from the given array such that a + b + c + d equals the target value. You should ensure that the returned quadruplets are sorted in no... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9198,
"level": 1,
"question": "Write a function that takes an array of integers and a target integer as input. The function should return a list of all unique quadruplets [a, b, c, d] from the given array such that a + b + c + d equals the target value. You should ensure that the re... |
def can_attend_meetings(intervals):
if not intervals:
return True # Though the problem states no empty input, this handles edge cases
# Sort intervals based on the start time
sorted_intervals = sorted(intervals, key=lambda x: x[0])
# Check each interval against the previous one for an... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of intervals, representing start and end times of meetings. Your task is to determine if a person can attend all the meetings without any overlap in schedule.\n\n### Input:\n\n* A list of tuples where each tuple contains two integers `(start, end)` representing the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9199,
"level": 1,
"question": "You are given a list of intervals, representing start and end times of meetings. Your task is to determine if a person can attend all the meetings without any overlap in schedule.\n\n### Input:\n\n* A list of tuples where each tuple contains two intege... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.