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 reverse_array(arr):
left = 0
right = len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse the elements of an array in-place. The function should have a time complexity of O(n), where n is the number of elements in the array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6900,
"level": 1,
"question": "Write a function to reverse the elements of an array in-place. The function should have a time complexity of O(n), where n is the number of elements in the array.",
"split": "train"
} |
def remove_numbers_containing_seven(numbers):
removed_count = 0
remaining_numbers = []
for num in numbers:
if '7' in str(num):
removed_count += 1
else:
remaining_numbers.append(num)
return remaining_numbers, removed_count | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove all numbers containing the digit 7 and count how many numbers are removed. Provide a breakdown of the code.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6901,
"level": 1,
"question": "Write a python function to remove all numbers containing the digit 7 and count how many numbers are removed. Provide a breakdown of the code.",
"split": "train"
} |
import numpy as np
from sklearn.model_selection import validation_curve, learning_curve
import matplotlib.pyplot as plt
def plot_model_evaluation_curves(model, X, y, param_name, param_range, train_sizes, cv=5):
"""
Plots the validation curve and learning curve for the given model and dataset.
Paramete... | simplelr_Docs | [
{
"content": "Question:\n### Question\n\nGiven the concepts of validation curves and learning curves explained in the documentation, your task is to implement a function that:\n1. Generates and plots a validation curve for a specified model, dataset, and hyperparameter range.\n2. Generates and plots a learning ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6902,
"level": 1,
"question": "### Question\n\nGiven the concepts of validation curves and learning curves explained in the documentation, your task is to implement a function that:\n1. Generates and plots a validation curve for a specified model, dataset, and hyperparameter range.\... |
def is_valid_parentheses_sequence(s: str) -> bool:
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code to determine if a given string is a valid parentheses sequence? A valid parentheses sequence is one where each opening parenthesis '(' has a corresponding closing parenthesis ')' and they are correctly nested.\nAnswer:\nLet's think step by step.\n",
"ro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6903,
"level": 1,
"question": "Can you provide a Python code to determine if a given string is a valid parentheses sequence? A valid parentheses sequence is one where each opening parenthesis '(' has a corresponding closing parenthesis ')' and they are correctly nested.",
"split":... |
def list_to_string(numbers):
return ','.join(str(num) for num in numbers) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert a list of numbers into a single string, separated by commas.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6904,
"level": 1,
"question": "Write a python function to convert a list of numbers into a single string, separated by commas.",
"split": "train"
} |
def swap_numbers(a, b):
a = a ^ b
b = a ^ b
a = a ^ b
return a, b | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to swap two numbers without using a temporary variable. However, you can use any arithmetic or logical operations. How would you implement it?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6905,
"level": 1,
"question": "Write a function to swap two numbers without using a temporary variable. However, you can use any arithmetic or logical operations. How would you implement it?",
"split": "train"
} |
def calculate_statistics(employees):
if not employees:
return {'average_salary': 0, 'highest_salary_employee': None}
sum_sal = sum(e['salary'] for e in employees)
avg = sum_sal / len(employees)
avg_rounded = round(avg, 2)
max_sal = max(e['salary'] for e in employees)
highest_na... | simplelr_Package | [
{
"content": "Question:\nYou are provided with a skeleton of a program that helps manage employee records in a company. Each employee has a unique ID, name, and salary. The goal is to add functionality to calculate the average salary of all employees and to identify the employee with the highest salary.\n\nYour... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6906,
"level": 1,
"question": "You are provided with a skeleton of a program that helps manage employee records in a company. Each employee has a unique ID, name, and salary. The goal is to add functionality to calculate the average salary of all employees and to identify the employ... |
def string_to_integer(s):
result = 0
for char in s:
digit = int(char)
result = result * 10 + digit
return result | simplelr_Filter | [
{
"content": "Question:\nGiven a string, write a Python function that converts the string to an integer number. For simplicity, you can assume that the string only contains digits and that it represents a valid non-negative integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6907,
"level": 1,
"question": "Given a string, write a Python function that converts the string to an integer number. For simplicity, you can assume that the string only contains digits and that it represents a valid non-negative integer.",
"split": "train"
} |
def remove_first_occurrence(lst, num):
try:
lst.remove(num)
except ValueError:
pass
return lst
# Example usage:
numbers = [5, 3, 6, 3, 7]
print(remove_first_occurrence(numbers, 3)) # Output: [5, 6, 3, 7] | simplelr_Filter | [
{
"content": "Question:\nI have a list of numbers in Python, and I want to remove the first occurrence of a specific number from the list. How can I do that?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6908,
"level": 1,
"question": "I have a list of numbers in Python, and I want to remove the first occurrence of a specific number from the list. How can I do that?",
"split": "train"
} |
def sum_up_to(n):
if n < 1:
return 0
return n * (n + 1) // 2 | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the sum of all positive integers up to and including n.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6909,
"level": 1,
"question": "Write a function to find the sum of all positive integers up to and including n.",
"split": "train"
} |
from itertools import accumulate
def cumulative_sum(nums):
return list(accumulate(nums)) | simplelr_Filter | [
{
"content": "Question:\nGiven a sequence of numbers, you need to write a Python function that calculates the cumulative sum of the sequence and returns a new list where each element is the cumulative sum up to that point. For example, given the list [1, 2, 3, 4], the function should return [1, 3, 6, 10]. Ensur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6910,
"level": 1,
"question": "Given a sequence of numbers, you need to write a Python function that calculates the cumulative sum of the sequence and returns a new list where each element is the cumulative sum up to that point. For example, given the list [1, 2, 3, 4], the function... |
import os
def organize_paths(base_path: str, file_paths: list[str]) -> dict[str, list[str]]:
result = {
"files": [],
"directories": [],
"non_existent": []
}
for path in file_paths:
# Determine the absolute path for the current path
if os.path.isabs(path):
... | simplelr_Docs | [
{
"content": "Question:\n### Advanced Path Manipulation Utility\n\n**Objective:** \nWrite a function `organize_paths(base_path: str, file_paths: list[str]) -> dict[str, list[str]]` that organizes given file paths into a dictionary based on their existence status and type (file or directory). This utility functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6911,
"level": 1,
"question": "### Advanced Path Manipulation Utility\n\n**Objective:** \nWrite a function `organize_paths(base_path: str, file_paths: list[str]) -> dict[str, list[str]]` that organizes given file paths into a dictionary based on their existence status and type (file... |
def filter_alphabetic_characters(input_string):
"""
This function filters out non-alphabetic characters from a given string.
Parameters:
input_string (str): The input string to be filtered.
Returns:
str: A new string containing only alphabetic characters from the input string.
"""
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to filter out non alphabetic characters from a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6912,
"level": 1,
"question": "Write a python function to filter out non alphabetic characters from a string.",
"split": "train"
} |
def double_characters(s):
return ''.join([c * 2 for c in s]) | simplelr_Apps | [
{
"content": "Question:\nGiven a string, return a new string where each character in the original string is repeated twice.\n\nFor example:\n\n`\"hello\"` should return `\"hheelllloo\"`.\n\n`\"1234!\"` should return `\"11223344!!\"`.\n\nThe input string will consist of printable ASCII characters only.\nAnswer:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6913,
"level": 1,
"question": "Given a string, return a new string where each character in the original string is repeated twice.\n\nFor example:\n\n`\"hello\"` should return `\"hheelllloo\"`.\n\n`\"1234!\"` should return `\"11223344!!\"`.\n\nThe input string will consist of printab... |
from collections import deque
from typing import List
def max_sliding_window(nums: List[int], k: int) -> List[int]:
q = deque()
result = []
for i in range(len(nums)):
# Remove elements from the end which are smaller than current element
while q and nums[i] >= nums[q[-1]]:
q.pop(... | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem: Maximum Sliding Window\n\nGiven an array `nums` and a number `k`, there is a sliding window of size `k` that moves along the array from the very left to the very right. You are required to implement a function that finds the maximum value in each sliding window.\n\n#### Fun... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6914,
"level": 1,
"question": "### Problem: Maximum Sliding Window\n\nGiven an array `nums` and a number `k`, there is a sliding window of size `k` that moves along the array from the very left to the very right. You are required to implement a function that finds the maximum value ... |
def reverse_string(str):
return str[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string `str` and returns a new string with all the characters in reverse order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6915,
"level": 1,
"question": "Create a function that takes a string `str` and returns a new string with all the characters in reverse order.",
"split": "train"
} |
def count_ones_in_binary(n):
binary = bin(abs(n))[2:]
return binary.count('1') | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to convert a decimal number to its binary representation, then count the number of 1s in that binary representation. The function should return the count of 1s as an integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6916,
"level": 1,
"question": "Write a Python function to convert a decimal number to its binary representation, then count the number of 1s in that binary representation. The function should return the count of 1s as an integer.",
"split": "train"
} |
def first_non_repeating_char(s):
char_info = {}
for i, char in enumerate(s):
if char not in char_info:
char_info[char] = {'first_index': i, 'count': 1}
else:
char_info[char]['count'] += 1
min_index = -1
result_char = None
for char, info in char_info.items... | simplelr_Filter | [
{
"content": "Question:\n### Algorithm to find the first non-repeating character in a stream of characters\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6917,
"level": 1,
"question": "### Algorithm to find the first non-repeating character in a stream of characters",
"split": "train"
} |
def is_sum_of_digits_even(n):
n = abs(n)
sum_digits = 0
while n > 0:
sum_digits += n % 10
n = n // 10
return sum_digits % 2 == 0 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if the sum of the digits of a given number is even. If it is, return true; otherwise, return false.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6918,
"level": 1,
"question": "Create a function that checks if the sum of the digits of a given number is even. If it is, return true; otherwise, return false.",
"split": "train"
} |
def factorial(n):
if n < 0:
raise ValueError("Input must be a non-negative integer.")
elif n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120 | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to calculate the factorial of a given number using recursion. The function should be named `factorial` and it should take a single integer argument. If the input is negative, the function should raise a `ValueError` with the message \"Input must be a non-negative... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6919,
"level": 1,
"question": "Write a Python function to calculate the factorial of a given number using recursion. The function should be named `factorial` and it should take a single integer argument. If the input is negative, the function should raise a `ValueError` with the mes... |
def rotate(matrix):
transposed = zip(*matrix)
rotated = [list(row[::-1]) for row in transposed]
return rotated | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to rotate a given 2D array (matrix) by 90 degrees clockwise.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6920,
"level": 1,
"question": "Write a function to rotate a given 2D array (matrix) by 90 degrees clockwise.",
"split": "train"
} |
from typing import List, Tuple
def optimized_bubble_sort(arr: List[int], simulation: bool = False) -> Tuple[List[int], int]:
arr_copy = arr.copy()
n = len(arr_copy)
operations = 0
for i in range(n - 1):
swapped = False
for j in range(n - i - 1):
operations += 1 # Count the ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Bubble Sort Extension with an Early Termination Condition\n\n#### Problem Statement\nYou are required to extend the current implementation of the bubble sort algorithm to improve its efficiency. Specifically, implement an additional feature that stops sorting when the array is ident... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6921,
"level": 1,
"question": "### Bubble Sort Extension with an Early Termination Condition\n\n#### Problem Statement\nYou are required to extend the current implementation of the bubble sort algorithm to improve its efficiency. Specifically, implement an additional feature that st... |
def smallestStudentSet(students):
# Precompute the set of clubs for each student and collect all unique clubs
students_clubs = {}
all_clubs = set()
for name, clubs in students.items():
students_clubs[name] = set(clubs)
all_clubs.update(clubs)
covered = set()
result = []
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of students who belong to different clubs in school. Each student is represented by a string and the clubs they belong to are represented by a list of strings. You need to find the smallest set of students such that the union of their clubs covers all the unique clu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6922,
"level": 1,
"question": "You are given a list of students who belong to different clubs in school. Each student is represented by a string and the clubs they belong to are represented by a list of strings. You need to find the smallest set of students such that the union of th... |
def longest_common_subsequence(str1: str, str2: str) -> int:
m = len(str1)
n = len(str2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i - 1] == str2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question - Dynamic Programming on Strings\n\n**Context**:\nYou are given two strings, `str1` and `str2`. Your task is to determine the length of the longest subsequence common to both strings. A subsequence is a sequence derived by deleting some or no characters from the orig... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6923,
"level": 1,
"question": "### Coding Question - Dynamic Programming on Strings\n\n**Context**:\nYou are given two strings, `str1` and `str2`. Your task is to determine the length of the longest subsequence common to both strings. A subsequence is a sequence derived by deleting ... |
def rob(nums):
if not nums:
return 0
n = len(nums)
if n == 1:
return nums[0]
a, b = 0, nums[0]
for i in range(1, n):
new_b = max(b, a + nums[i])
a, b = b, new_b
return b | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **non-empty** array `nums` of positive integers representing the amount of money of each house. You are a burglar trying to rob these houses, but you cannot rob two adjacent houses because the alarms will go off. Write a function to return _the maximum amount of money yo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6924,
"level": 1,
"question": "You are given a **non-empty** array `nums` of positive integers representing the amount of money of each house. You are a burglar trying to rob these houses, but you cannot rob two adjacent houses because the alarms will go off. Write a function to ret... |
def print_string_n_times(string, n):
if n <= 0:
return
print(string)
print_string_n_times(string, n - 1) | simplelr_Filter | [
{
"content": "Question:\nDevelop a recursive function in Python to print a user-specified string n times.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6925,
"level": 1,
"question": "Develop a recursive function in Python to print a user-specified string n times.",
"split": "train"
} |
def sieve_of_eratosthenes(n):
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0], sieve[1] = False, False
for p in range(2, int(n ** 0.5) + 1):
if sieve[p]:
for multiple in range(p * p, n + 1, p):
sieve[multiple] = False
primes = [i for i, is_prime in e... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to generate a list of prime numbers up to a given number `n` using the Sieve of Eratosthenes algorithm. The function should take one parameter: `n`, which is the upper limit for finding prime numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6926,
"level": 1,
"question": "Write a function to generate a list of prime numbers up to a given number `n` using the Sieve of Eratosthenes algorithm. The function should take one parameter: `n`, which is the upper limit for finding prime numbers.",
"split": "train"
} |
def find_max_integer(lst):
return max(lst) if lst else None | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns the maximum integer in the list. If the list is empty, the function should return `None`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6927,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns the maximum integer in the list. If the list is empty, the function should return `None`.",
"split": "train"
} |
def validate_string(s):
has_upper = False
has_lower = False
has_digit = False
for char in s:
if char.isupper():
has_upper = True
elif char.islower():
has_lower = True
elif char.isdigit():
has_digit = True
return has_upper and has_lower and ... | simplelr_Filter | [
{
"content": "Question:\nYou've been tasked with writing a function `validate_string` that checks if a given string contains at least one uppercase letter, one lowercase letter, and one digit. The function should return `True` if the string is valid and `False` otherwise.\nAnswer:\nLet's think step by step.\n",... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6928,
"level": 1,
"question": "You've been tasked with writing a function `validate_string` that checks if a given string contains at least one uppercase letter, one lowercase letter, and one digit. The function should return `True` if the string is valid and `False` otherwise.",
... |
def trailing_zeroes(n: int) -> int:
count = 0
while n >= 5:
n = n // 5
count += n
return count | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer `n`, return the number of trailing zeroes in `n!` (n factorial). Note that `n!` means `n × (n - 1) × ... × 2 × 1`. For example, `5! = 120` has one trailing zero. You are required to implement an efficient algorithm to solve this problem.\nAnswer:\nLet's think step by st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6929,
"level": 1,
"question": "Given an integer `n`, return the number of trailing zeroes in `n!` (n factorial). Note that `n!` means `n × (n - 1) × ... × 2 × 1`. For example, `5! = 120` has one trailing zero. You are required to implement an efficient algorithm to solve this proble... |
def common_elements(list1, list2):
seen = {}
for element in list1:
seen[element] = True
added = {}
result = []
for element in list2:
if element in seen and element not in added:
result.append(element)
added[element] = True
return result | simplelr_Filter | [
{
"content": "Question:\nCreate a code in Python that takes two lists and returns a new list which contains only the common elements from both lists. The code should have a time complexity of O(n), where n is the length of the longer list. Additionally, the code should not use any built-in Python functions such... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6930,
"level": 1,
"question": "Create a code in Python that takes two lists and returns a new list which contains only the common elements from both lists. The code should have a time complexity of O(n), where n is the length of the longer list. Additionally, the code should not use... |
def is_narcissistic(n):
s = str(n)
k = len(s)
total = 0
for char in s:
digit = int(char)
total += digit ** k
return total == n | simplelr_Apps | [
{
"content": "Question:\nYou are given an integer `n`. Write a function that determines whether `n` is a Narcissistic number. A Narcissistic number (also known as a pluperfect number) for a given number of digits is a number that is the sum of its own digits each raised to the power of the number of digits.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6931,
"level": 1,
"question": "You are given an integer `n`. Write a function that determines whether `n` is a Narcissistic number. A Narcissistic number (also known as a pluperfect number) for a given number of digits is a number that is the sum of its own digits each raised to the... |
def split_sentence(s, k):
words = s.split()
if not words:
return []
for word in words:
if len(word) > k:
return []
lines = []
current_line = []
current_length = 0
for word in words:
if current_line:
possible = current_length + 1 ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` and an integer `k`. The string `s` is a sentence containing words separated by spaces. Each word contains only lowercase English letters. We want to split the sentence into multiple lines such that each line contains at most `k` characters, and no word is spli... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6932,
"level": 1,
"question": "You are given a string `s` and an integer `k`. The string `s` is a sentence containing words separated by spaces. Each word contains only lowercase English letters. We want to split the sentence into multiple lines such that each line contains at most ... |
def maxConsecutiveOnes(nums, k):
left = 0
zero_count = 0
max_length = 0
for right in range(len(nums)):
if nums[right] == 0:
zero_count += 1
# If zero_count exceeds k, move left pointer
while zero_count > k:
if nums[left] == 0:
zero_count -=... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums` and an integer `k`, return the maximum number of consecutive 1s in the array if you can flip at most `k` 0s. A flip operation includes changing a 0 in the array to a 1. The array contains only 0s and 1s. Note: Your solution should have a time complexity... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6933,
"level": 1,
"question": "Given an array of integers `nums` and an integer `k`, return the maximum number of consecutive 1s in the array if you can flip at most `k` 0s. A flip operation includes changing a 0 in the array to a 1. The array contains only 0s and 1s. Note: Your sol... |
def unique_elements(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
result.append(item)
seen.add(item)
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to create a list with unique elements from the provided list while maintaining the original order. How can I achieve this in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6934,
"level": 1,
"question": "Write a python function to create a list with unique elements from the provided list while maintaining the original order. How can I achieve this in Python?",
"split": "train"
} |
def rearrange(s):
letters = []
digits = []
for char in s:
if char.isalpha():
letters.append(char)
else:
digits.append(char)
return ''.join(letters + digits)
| simplelr_Taco | [
{
"content": "Question:\nGiven a string containing digits and lowercase letters, rearrange the characters such that all lowercase letters come before any digits. The relative order of the characters within the letters and digits should be preserved.\nExample 1:\nInput:\nS = \"a1b2c3\"\nOutput: \"abc123\"\nExpla... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6935,
"level": 1,
"question": "Given a string containing digits and lowercase letters, rearrange the characters such that all lowercase letters come before any digits. The relative order of the characters within the letters and digits should be preserved.\nExample 1:\nInput:\nS = \"... |
def find_dict_with_key_value(dict_list, key, value):
for d in dict_list:
if key in d and d[key] == value:
return d
return None | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of dictionaries and returns the first dictionary that contains the specified key and value. If no such dictionary is found, return `None`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6936,
"level": 1,
"question": "Create a function that takes a list of dictionaries and returns the first dictionary that contains the specified key and value. If no such dictionary is found, return `None`.",
"split": "train"
} |
def sum_all_elements(input_list):
return [sum(input_list)] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list and returns a new list containing the sum of all the elements in the original list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6937,
"level": 1,
"question": "Create a function that takes in a list and returns a new list containing the sum of all the elements in the original list.",
"split": "train"
} |
from typing import List
def get_primes(n: int) -> List[int]:
"""
Computes a list of all primes less than the given integer n using an optimized
Sieve of Eratosthenes which does not consider even numbers.
Args:
n (int): The upper limit (exclusive) for which to find all prime numbers.
Retur... | simplelr_Data_Structure | [
{
"content": "Question:\nYou need to implement an optimized version of the Sieve of Eratosthenes which excludes even numbers. The function should provide a list of all prime numbers less than a given integer `n`.\n\n### Function Signature\n```python\ndef get_primes(n: int) -> List[int]:\n \"\"\"\n Compute... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6938,
"level": 1,
"question": "You need to implement an optimized version of the Sieve of Eratosthenes which excludes even numbers. The function should provide a list of all prime numbers less than a given integer `n`.\n\n### Function Signature\n```python\ndef get_primes(n: int) -> ... |
def binary_xor(s1, s2):
a = int(s1, 2)
b = int(s2, 2)
return bin(a ^ b)[2:] | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings `s1` and `s2` which represent two different binary numbers. Your task is to perform the **XOR** operation on these two binary numbers and return the result as a binary string. The XOR operation, also known as exclusive or, is a bitwise operation that returns `1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6939,
"level": 1,
"question": "You are given two strings `s1` and `s2` which represent two different binary numbers. Your task is to perform the **XOR** operation on these two binary numbers and return the result as a binary string. The XOR operation, also known as exclusive or, is ... |
def three_sum(nums, target):
nums.sort()
n = len(nums)
for i in range(n - 2):
j = i + 1
k = n - 1
while j < k:
current_sum = nums[i] + nums[j] + nums[k]
if current_sum == target:
return True
elif current_sum < target:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a **0-indexed** integer array `nums` and an integer `target`, determine if there are **three** distinct elements in the array that add up to the `target`. Return `true` _if such a combination exists, and_ `false` _otherwise._\nAnswer:\nLet's think step by step.\n",
"role": "us... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6940,
"level": 1,
"question": "Given a **0-indexed** integer array `nums` and an integer `target`, determine if there are **three** distinct elements in the array that add up to the `target`. Return `true` _if such a combination exists, and_ `false` _otherwise._",
"split": "train"... |
import random
import math
def estimate_pi(num_trials):
count = 0
for _ in range(num_trials):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
if x**2 + y**2 <= 1:
count += 1
return 4 * (count / num_trials)
num_trials = 1000000
pi_estimate = estimate_pi(num_trials)
pri... | simplelr_Filter | [
{
"content": "Question:\nI would like to create a simple Python script that runs a Monte Carlo simulation to estimate the value of π (pi) using the random number generation library. Could you provide a Python script that demonstrates this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6941,
"level": 1,
"question": "I would like to create a simple Python script that runs a Monte Carlo simulation to estimate the value of π (pi) using the random number generation library. Could you provide a Python script that demonstrates this?",
"split": "train"
} |
import pandas as pd
def analyze_data() -> str:
try:
# Read the CSV file into a DataFrame
df = pd.read_csv('data.csv')
# Filter out rows where the score is below 50
df_filtered = df[df['score'] >= 50]
# Check if the filtered DataFrame is empty
if df_... | simplelr_Algorithm | [
{
"content": "Question:\n### File Data Analysis with Pandas\n\nGiven the following requirements:\n\n1. A CSV file named `data.csv` that contains columns `id`, `name`, `score`, `date` representing an ID number, a student's name, their score, and the date the score was recorded, respectively.\n2. You are required... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6942,
"level": 1,
"question": "### File Data Analysis with Pandas\n\nGiven the following requirements:\n\n1. A CSV file named `data.csv` that contains columns `id`, `name`, `score`, `date` representing an ID number, a student's name, their score, and the date the score was recorded,... |
def isMatch(text: str, pattern: str) -> bool:
# Initialize the DP table
dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)]
dp[0][0] = True # Empty text matches empty pattern
for i in range(len(text) + 1):
for j in range(len(pattern) + 1):
if i == 0 and j == 0:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\nYou need to implement a function that determines whether a given string pattern matches a given text entirely, using regular expression matching with support for two special characters:\n1. `.` (dot) which matches any single character.\n2. `*` (asterisk) which ma... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6943,
"level": 1,
"question": "### Problem Statement:\nYou need to implement a function that determines whether a given string pattern matches a given text entirely, using regular expression matching with support for two special characters:\n1. `.` (dot) which matches any single cha... |
def sum_integers_in_range(a, b):
if a == b:
return a
start = min(a, b)
end = max(a, b)
number_of_terms = end - start + 1
total = (number_of_terms * (start + end)) // 2
return total
| simplelr_Taco | [
{
"content": "Question:\nWrite a Python function that computes the sum of the integers between two given integers (inclusive). However, if the two integers are equal, the function should return that integer directly. Ensure your function handles both negative and positive integers, and that the order of the giv... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6944,
"level": 1,
"question": "Write a Python function that computes the sum of the integers between two given integers (inclusive). However, if the two integers are equal, the function should return that integer directly. Ensure your function handles both negative and positive inte... |
from collections import deque
def is_water_flow_possible(pipeline: str) -> bool:
n = len(pipeline)
pipeline = list(pipeline)
for i in range(n):
if pipeline[i] == 'A':
visited = set()
queue = deque()
queue.append(i)
visited.add(i)
while que... | simplelr_Taco | [
{
"content": "Question:\nGiven a string representing a pipeline of water systems, each water system can be in one of the following states:\n\n- `A`: Active Water source\n- `B`: Broken Water source\n- `T`: Terminal point (water collection point)\n- `.`, `|`, `-`: Empty pipe sections which connect the whole water... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6945,
"level": 1,
"question": "Given a string representing a pipeline of water systems, each water system can be in one of the following states:\n\n- `A`: Active Water source\n- `B`: Broken Water source\n- `T`: Terminal point (water collection point)\n- `.`, `|`, `-`: Empty pipe sec... |
import heapq
from math import inf
from typing import List
def dijkstra_shortest_paths(graph: List[List[int]], src: int) -> List[int]:
n = len(graph)
if n == 0:
return []
distances = [inf] * n
distances[src] = 0
heap = []
heapq.heappush(heap, (0, src))
while heap:
curren... | simplelr_Data_Structure | [
{
"content": "Question:\n### Dijkstra's Navigation Route\n\nYou are given the task of developing a navigation system for a city represented by a weighted graph. Each edge in the graph represents a road between two intersections (vertices), with the edge weight corresponding to the time taken to travel that road... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6946,
"level": 1,
"question": "### Dijkstra's Navigation Route\n\nYou are given the task of developing a navigation system for a city represented by a weighted graph. Each edge in the graph represents a road between two intersections (vertices), with the edge weight corresponding to... |
def count_letter_occurrences(words, char):
result = {}
for word in words:
count = 0
for c in word:
if c == char:
count += 1
result[word] = count
return result | simplelr_Evol | [
{
"content": "Question:\nImplement a function `count_letter_occurrences` that takes two arguments: a list of words and a single character (a letter). The function should return a dictionary where each key is a word from the list and the corresponding value is the number of times the given character appears in t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6947,
"level": 1,
"question": "Implement a function `count_letter_occurrences` that takes two arguments: a list of words and a single character (a letter). The function should return a dictionary where each key is a word from the list and the corresponding value is the number of tim... |
import heapq
def dijkstra_shortest_path(graph, start, end):
if start not in graph or end not in graph:
return []
if start == end:
return [start]
distances = {node: float('infinity') for node in graph}
distances[start] = 0
previous = {node: None for node in graph}
prior... | simplelr_Data_Structure | [
{
"content": "Question:\n### Path Finding in Directed Graphs\n\n#### Objective\nImplement a function to find the shortest path between two nodes in a weighted, directed graph using Dijkstra's algorithm.\n\n#### Description\nIn the provided weighted, directed graph, you need to find the shortest path from a star... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6948,
"level": 1,
"question": "### Path Finding in Directed Graphs\n\n#### Objective\nImplement a function to find the shortest path between two nodes in a weighted, directed graph using Dijkstra's algorithm.\n\n#### Description\nIn the provided weighted, directed graph, you need to... |
def calculate_total_cost(number_of_boxes, cost_per_box, shipping_fee):
return number_of_boxes * cost_per_box + shipping_fee | simplelr_Apps | [
{
"content": "Question:\nSarah is organizing a holiday campaign and wants to calculate the total cost of gift wrapping boxes she needs to buy. She knows the number of boxes, the cost per box, and a fixed shipping fee for the entire order. Write a function to help Sarah calculate the total cost.\n\n```if:shell\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6949,
"level": 1,
"question": "Sarah is organizing a holiday campaign and wants to calculate the total cost of gift wrapping boxes she needs to buy. She knows the number of boxes, the cost per box, and a fixed shipping fee for the entire order. Write a function to help Sarah calcula... |
import re
def extract_numbers(s):
numbers = re.findall(r'\d', s)
return ''.join(numbers)
# Example usage:
print(extract_numbers("abc123def456")) # Outputs: "123456" | simplelr_Filter | [
{
"content": "Question:\nCan you please help me with the script to extract only numbers from a string in Python? For example, from the string \"abc123def456\", I want to extract \"123456\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6950,
"level": 1,
"question": "Can you please help me with the script to extract only numbers from a string in Python? For example, from the string \"abc123def456\", I want to extract \"123456\".",
"split": "train"
} |
def min_abs_diff(arr, x):
possible_sums = {0}
best_diff = float('inf')
for num in arr:
temp = set()
for s in possible_sums:
new_sum = s + num
if new_sum > x + best_diff:
continue
diff = abs(new_sum - x)
if diff < best_diff:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a sorted integer array `arr` and an integer `x`. Your task is to find the minimum absolute difference between the sum of any subset of `arr` and `x`. You may assume the array contains only positive integers and at least one element. Return the minimum absolute difference.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6951,
"level": 1,
"question": "You are given a sorted integer array `arr` and an integer `x`. Your task is to find the minimum absolute difference between the sum of any subset of `arr` and `x`. You may assume the array contains only positive integers and at least one element. Retu... |
from collections import deque
def bfs_shortest_path(graph: dict, start: str, end: str) -> list:
# Check if start or end nodes are not in the graph
if start not in graph or end not in graph:
return []
# If start and end are the same, return the single node path
if start == end:
return [s... | simplelr_Algorithm | [
{
"content": "Question:\n### Context:\nIn graph theory, a graph traversal technique often used is the Breadth-First Search (BFS). BFS is used to explore the nodes of a graph or tree level by level, starting from a specified starting node. This can be particularly useful for finding the shortest path from one no... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6952,
"level": 1,
"question": "### Context:\nIn graph theory, a graph traversal technique often used is the Breadth-First Search (BFS). BFS is used to explore the nodes of a graph or tree level by level, starting from a specified starting node. This can be particularly useful for fi... |
def h_index(citations):
citations.sort(reverse=True)
h = 0
for i in range(len(citations)):
if citations[i] >= i + 1:
h = i + 1
else:
break
return h | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `citations` where `citations[i]` is the number of times a researcher's `i-th` paper has been cited, return the researcher's h-index. According to the definition of h-index: a researcher has an index `h` if `h` of their `n` papers have at least `h` citations ea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6953,
"level": 1,
"question": "Given an array of integers `citations` where `citations[i]` is the number of times a researcher's `i-th` paper has been cited, return the researcher's h-index. According to the definition of h-index: a researcher has an index `h` if `h` of their `n` pa... |
from collections import Counter
def count_balloon_instances(s: str) -> int:
counts = Counter(s)
required = {'b': 1, 'a': 1, 'l': 2, 'o': 2, 'n': 1}
min_count = float('inf')
for char in required:
cnt = counts.get(char, 0)
possible = cnt // required[char]
if possible < min_count:
... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a string $$$s$$$ consisting of lowercase English letters, and you need to check how many times you can spell the word \"balloon\" using the letters from the string. Each letter in the input string can only be used once in each instance of spelling \"balloon\".\n\nFor examp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6954,
"level": 1,
"question": "You are given a string $$$s$$$ consisting of lowercase English letters, and you need to check how many times you can spell the word \"balloon\" using the letters from the string. Each letter in the input string can only be used once in each instance of... |
def generate_personalized_greeting(name: str, age: int, city: str) -> str:
"""
Parameters:
1. name (str): The name of the recipient.
2. age (int): The age of the recipient (must be positive).
3. city (str): The city of residence of the recipient.
Returns:
str: A personalized greeting me... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are developing a software program that outputs a personalized greeting message based on the recipient's name, age, and city of residence. The message should adjust appropriately to different inputs, producing a friendly and readable string.\n\n### Problem Statement\nWr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6955,
"level": 1,
"question": "### Scenario\nYou are developing a software program that outputs a personalized greeting message based on the recipient's name, age, and city of residence. The message should adjust appropriately to different inputs, producing a friendly and readable s... |
def index_of_largest_number(lst):
if not lst:
return -1
max_val = max(lst)
for index, value in enumerate(lst):
if value == max_val:
return index | simplelr_Filter | [
{
"content": "Question:\nGiven a list of integers, write a Python function that returns the index of the first occurrence of the largest number in the list. If the list is empty, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6956,
"level": 1,
"question": "Given a list of integers, write a Python function that returns the index of the first occurrence of the largest number in the list. If the list is empty, return -1.",
"split": "train"
} |
from collections import Counter
def can_form_palindrome(s):
counts = Counter(s)
num_odds = 0
for count in counts.values():
if count % 2 != 0:
num_odds += 1
if len(s) % 2 == 0:
return "YES" if num_odds == 0 else "NO"
else:
return "YES" if num_odds == 1 else "NO" | simplelr_Apps | [
{
"content": "Question:\nFor this problem, you will be given a string as input. The string consists of uppercase English letters only. Write a function that checks if the input string can be rearranged to form a palindrome. \n\nA palindrome is a word, phrase, or sequence that reads the same backward as forward ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6957,
"level": 1,
"question": "For this problem, you will be given a string as input. The string consists of uppercase English letters only. Write a function that checks if the input string can be rearranged to form a palindrome. \n\nA palindrome is a word, phrase, or sequence that ... |
def check_multiples(lst):
for num in lst:
if num % 3 != 0 and num % 5 != 0:
return "NO"
return "YES" | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes one parameter, which is a list of integers. The function should check if every integer in the list is either a multiple of 3 or a multiple of 5. If all integers meet this criterion, the function should return \"YES\". If there is at least one integer that is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6958,
"level": 1,
"question": "Create a function that takes one parameter, which is a list of integers. The function should check if every integer in the list is either a multiple of 3 or a multiple of 5. If all integers meet this criterion, the function should return \"YES\". If th... |
def numIdenticalPairs(nums):
from collections import defaultdict
freq = defaultdict(int)
for num in nums:
freq[num] += 1
count = 0
for k in freq.values():
if k >= 2:
count += k * (k - 1) // 2
return count | simplelr_Filter | [
{
"content": "Question:\n### Programming Challenges\n#### 1. Number of Good Pairs\nGiven an array of integers `nums`, return the number of \"good pairs\".\nA \"good pair\" is a pair `(i, j)` where `i < j` and `nums[i] == nums[j]`.\n\nExample 1:\nInput: nums = [1,2,2,3]\nOutput: 1\nExplanation: There is one good... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6959,
"level": 1,
"question": "### Programming Challenges\n#### 1. Number of Good Pairs\nGiven an array of integers `nums`, return the number of \"good pairs\".\nA \"good pair\" is a pair `(i, j)` where `i < j` and `nums[i] == nums[j]`.\n\nExample 1:\nInput: nums = [1,2,2,3]\nOutput... |
def reverse_words(s):
words = []
current_word = ''
for char in s:
if char == ' ':
if current_word:
words.append(current_word)
current_word = ''
else:
current_word += char
if current_word:
words.append(current_word)
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse the words in a given string without using any in-built function.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6960,
"level": 1,
"question": "Write a python function to reverse the words in a given string without using any in-built function.",
"split": "train"
} |
def is_palindrome(s: str) -> bool:
# Filter the string to include only alphanumeric characters and convert to lowercase
filtered = [c.lower() for c in s if c.isalnum()]
filtered_str = ''.join(filtered)
# Check if the filtered string is a palindrome
return filtered_str == filtered_str[::-1] | simplelr_Apps | [
{
"content": "Question:\nPalindrome Checker\n\nWrite a function `is_palindrome(s: str) -> bool` that checks whether a given string `s` is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring case, spaces, and punctuation).\n\n##... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6961,
"level": 1,
"question": "Palindrome Checker\n\nWrite a function `is_palindrome(s: str) -> bool` that checks whether a given string `s` is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring ca... |
def can_split_into_equal_sum_subarrays(nums):
total = sum(nums)
if total % 2 != 0:
return False
target = total // 2
current_sum = 0
for i in range(len(nums)):
current_sum += nums[i]
if current_sum == target and i < len(nums) - 1:
return True
return False | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums` containing `n` elements. Your task is to split the array into two contiguous subarrays such that the sum of elements in both subarrays is equal. Return `true` if such a split is possible, otherwise return `false`. \n\n**Note** that each subarray... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6962,
"level": 1,
"question": "You are given an array of integers `nums` containing `n` elements. Your task is to split the array into two contiguous subarrays such that the sum of elements in both subarrays is equal. Return `true` if such a split is possible, otherwise return `fals... |
def leftmost_min_index(lst):
if not lst:
return -1
min_index = 0
min_value = lst[0]
for i in range(1, len(lst)):
if lst[i] < min_value:
min_value = lst[i]
min_index = i
return min_index | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the index of the leftmost minimum in a list. If multiple instances of the minimum value exist, return the index of the first occurrence. If the list is empty, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6963,
"level": 1,
"question": "Write a function to find the index of the leftmost minimum in a list. If multiple instances of the minimum value exist, return the index of the first occurrence. If the list is empty, return -1.",
"split": "train"
} |
def product_except_self(arr):
n = len(arr)
if n == 0:
return []
prefix = [1] * n
current_product = 1
for i in range(n):
prefix[i] = current_product
current_product *= arr[i]
suffix = [1] * n
current_product = 1
for i in range(n-1, -1, -1):
suffix... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `arr`, return _an array_ `result` _such that_ `result[i]` _is equal to the product of all the elements of_ `arr` _except_ `arr[i]`. You must do this without using division and in linear time.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6964,
"level": 1,
"question": "Given an integer array `arr`, return _an array_ `result` _such that_ `result[i]` _is equal to the product of all the elements of_ `arr` _except_ `arr[i]`. You must do this without using division and in linear time.",
"split": "train"
} |
def sum_of_positive_numbers(numbers):
return sum(num for num in numbers if num > 0) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum of all numbers in a list, but only if they are positive.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6965,
"level": 1,
"question": "Write a function to calculate the sum of all numbers in a list, but only if they are positive.",
"split": "train"
} |
def remove_duplicates(input_list):
seen = set()
result = []
for num in input_list:
if num not in seen:
seen.add(num)
result.append(num)
return result
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns a new list with all duplicate values removed, while preserving the original order of elements.\n\nExample:\n\n```\n[1, 2, 3, 2, 4, 5, 1] --> [1, 2, 3, 4, 5]\n[7, 7, 8, 9, 8, 10] --> [7, 8, 9, 10]\n```\nAnswer:\nLet's think ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6966,
"level": 1,
"question": "Write a function that takes a list of integers and returns a new list with all duplicate values removed, while preserving the original order of elements.\n\nExample:\n\n```\n[1, 2, 3, 2, 4, 5, 1] --> [1, 2, 3, 4, 5]\n[7, 7, 8, 9, 8, 10] --> [7, 8, 9,... |
def remove_duplicates(sorted_list):
if not sorted_list:
return []
unique_list = [sorted_list[0]]
for num in sorted_list[1:]:
if num != unique_list[-1]:
unique_list.append(num)
return unique_list | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that removes duplicates from a sorted list. The function should accept a sorted list of integers and return a new list with all duplicates removed. Advanced users should consider optimizing the function for performance.\nAnswer:\nLet's think step by step.\n",
"role... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6967,
"level": 1,
"question": "Create a function that removes duplicates from a sorted list. The function should accept a sorted list of integers and return a new list with all duplicates removed. Advanced users should consider optimizing the function for performance.",
"split": "... |
def count_characters(s):
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
return counts | simplelr_Filter | [
{
"content": "Question:\nYou are given a string of characters. Write a Python function to count the occurrences of each character in the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6968,
"level": 1,
"question": "You are given a string of characters. Write a Python function to count the occurrences of each character in the string.",
"split": "train"
} |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def create_custom_flower_plot(df: pd.DataFrame) -> None:
# Set the style to whitegrid for white background and grid lines
sns.set_style("whitegrid")
# Scaling factor for the figure size
scale = 0.7
# Calculate the scaled... | simplelr_Docs | [
{
"content": "Question:\n**Objective:** This question aims to assess your understanding of seaborn's theme configuration and display settings using the `seaborn.objects` module. You will write a function to generate a specific plot using customized theme and display settings.\n\n**Problem Statement:**\n\nYou ar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6969,
"level": 1,
"question": "**Objective:** This question aims to assess your understanding of seaborn's theme configuration and display settings using the `seaborn.objects` module. You will write a function to generate a specific plot using customized theme and display settings.\... |
def minMeetingRooms(startTime, endTime):
events = []
for s in startTime:
events.append((s, 1)) # 1 represents a start event
for e in endTime:
events.append((e, 0)) # 0 represents an end event
events.sort() # Sorts by time, then by type (end events before start events at the same time)... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two integer arrays `startTime` and `endTime`, each of length `n`, representing the start and end times of `n` meetings. A meeting `i` starts at `startTime[i]` and ends at `endTime[i]`. You need to find the minimum number of meeting rooms required to host all the meetings. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6970,
"level": 1,
"question": "You are given two integer arrays `startTime` and `endTime`, each of length `n`, representing the start and end times of `n` meetings. A meeting `i` starts at `startTime[i]` and ends at `endTime[i]`. You need to find the minimum number of meeting rooms ... |
def is_reservation_possible(existing_reservations, new_reservation):
new_start, new_end = new_reservation
for res in existing_reservations:
existing_start, existing_end, _ = res
if new_start < existing_end and new_end > existing_start:
return False
return True | simplelr_Apps | [
{
"content": "Question:\nYou are developing a reservation system for a small hotel. Each reservation consists of a check-in date, a check-out date, and a guest name. To determine if a new reservation can be accommodated, you must check if the new reservation dates overlap with any existing reservations.\n\nWrit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6971,
"level": 1,
"question": "You are developing a reservation system for a small hotel. Each reservation consists of a check-in date, a check-out date, and a guest name. To determine if a new reservation can be accommodated, you must check if the new reservation dates overlap with... |
def sumDigits(s):
return sum(int(c) for c in s)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `sumDigits` that takes a single string parameter representing a positive integer, and returns the sum of its digits. \n\nFor example:\n\n```python\nsumDigits(\"1234\")\n```\n\nshould return `10` because 1 + 2 + 3 + 4 = 10.\n\n### Constraints:\n- The input string will al... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6972,
"level": 1,
"question": "Write a function `sumDigits` that takes a single string parameter representing a positive integer, and returns the sum of its digits. \n\nFor example:\n\n```python\nsumDigits(\"1234\")\n```\n\nshould return `10` because 1 + 2 + 3 + 4 = 10.\n\n### Const... |
import secrets
def generate_random_number(start, end):
"""Generates a cryptographically strong random number within a specified range.
Args:
start: The starting value of the range (inclusive).
end: The ending value of the range (inclusive).
Returns:
A cryptographically strong rand... | simplelr_Filter | [
{
"content": "Question:\nThis is the second time I've asked this question. I'm hoping someone can help me.\n\nI'm trying to create a program that generates random numbers within a specific range. I'm using Python and I'm stuck on how to ensure the generated numbers are truly random and not predictable.\n\n```py... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6973,
"level": 1,
"question": "This is the second time I've asked this question. I'm hoping someone can help me.\n\nI'm trying to create a program that generates random numbers within a specific range. I'm using Python and I'm stuck on how to ensure the generated numbers are truly r... |
def kth_smallest_pair_distance(arr, k):
arr.sort()
n = len(arr)
low = 0
high = arr[-1] - arr[0] if n > 0 else 0
while low < high:
mid = (low + high) // 2
count = 0
j = 0
for i in range(n):
while j < n and arr[j] - arr[i] <= mid:
j += 1
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of distinct integers `arr` and an integer `k`, return the `kth` smallest pair distance in the array. The distance of a pair (`arr[i]`, `arr[j]`) is defined as the absolute difference between `arr[i]` and `arr[j]`.\nAnswer:\nLet's think step by step.\n",
"role": "user"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6974,
"level": 1,
"question": "Given an array of distinct integers `arr` and an integer `k`, return the `kth` smallest pair distance in the array. The distance of a pair (`arr[i]`, `arr[j]`) is defined as the absolute difference between `arr[i]` and `arr[j]`.",
"split": "train"
} |
def find_duplicates(original_list):
counts = {}
for num in original_list:
counts[num] = counts.get(num, 0) + 1
duplicates = []
seen = set()
for num in original_list:
if counts[num] > 1 and num not in seen:
duplicates.append(num)
seen.add(num)
return duplic... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns a new list containing only the elements that appear more than once in the original list. Also, include a segment of erroneous code as an additional challenge for the candidate. Refactor the code to ensure it correctly ide... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6975,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns a new list containing only the elements that appear more than once in the original list. Also, include a segment of erroneous code as an additional challenge for the candidate. Refactor ... |
def sum_even_numbers(nums):
total = 0
for num in nums:
if num % 2 == 0:
total += num
return total
| simplelr_Taco | [
{
"content": "Question:\n```\nWrite a function called `sum_even_numbers` which takes a list of integers `nums` and returns the sum of all the even numbers in the list.\n```\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6976,
"level": 1,
"question": "```\nWrite a function called `sum_even_numbers` which takes a list of integers `nums` and returns the sum of all the even numbers in the list.\n```",
"split": "train"
} |
def remove_adjacent_duplicates(s):
if len(s) < 2:
return s
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
return remove_adjacent_duplicates(s[:i] + s[i+2:])
return s | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` containing only lowercase letters, recursively eliminate all adjacent duplicate characters until no such adjacent duplicates remain. Return the final string after all possible eliminations have been performed. For example, given the input \"abbaca\", the output should... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6977,
"level": 1,
"question": "Given a string `s` containing only lowercase letters, recursively eliminate all adjacent duplicate characters until no such adjacent duplicates remain. Return the final string after all possible eliminations have been performed. For example, given the ... |
def create_dict_from_lists(list1=None, list2=None):
if list1 is None:
list1 = []
if list2 is None:
list2 = []
result = {}
min_length = min(len(list1), len(list2))
for i in range(min_length):
key = list1[i]
value = list2[i]
result[key] = value
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes two lists of equal length and creates a dictionary of the elements in each list that have the same index. The function should also handle cases where the lists are not of equal length by only using the length of the shorter list to create the dictionar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6978,
"level": 1,
"question": "Write a Python function that takes two lists of equal length and creates a dictionary of the elements in each list that have the same index. The function should also handle cases where the lists are not of equal length by only using the length of the s... |
def is_balanced_binary(t, binaries):
result = []
for s in binaries:
count = s.count('1')
if count % 2 == 0:
result.append("balanced")
else:
result.append("unbalanced")
return result
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of strings, each string representing a binary number, determine if the binary number has an even or odd number of `1`s. A binary number is considered \"balanced\" if it has an even number of `1`s, and \"unbalanced\" if it has an odd number of `1`s.\n\nWrite a function `is_b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6979,
"level": 1,
"question": "Given a list of strings, each string representing a binary number, determine if the binary number has an even or odd number of `1`s. A binary number is considered \"balanced\" if it has an even number of `1`s, and \"unbalanced\" if it has an odd number... |
def calculate_running_sum(nums, skipped_indices=list()):
current_sum = 0
result = []
skipped = set(skipped_indices)
for idx, num in enumerate(nums):
if idx in skipped:
result.append(current_sum)
else:
current_sum += num
result.append(current_sum)
r... | simplelr_Package | [
{
"content": "Question:\n**Problem:** Implement a function called `calculate_running_sum` in Python that computes the running sum of an input integer array, but skips over specified indices. \n\n### Function Signature:\n```python\ndef calculate_running_sum(nums, skipped_indices=list()):\n \"\"\"\n Calcula... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6980,
"level": 1,
"question": "**Problem:** Implement a function called `calculate_running_sum` in Python that computes the running sum of an input integer array, but skips over specified indices. \n\n### Function Signature:\n```python\ndef calculate_running_sum(nums, skipped_indice... |
def sum_of_squares(input_string):
return sum(int(num)**2 for num in input_string.split(',')) | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a string of comma-separated numbers as input and returns the sum of the squares of those numbers. Assume the input string will always contain valid integers separated by commas.\n\nFor example,\n\n```\ninput: \"1,2,3,4\"\noutput: 30\nExplanation: 1^2 + 2^2 + ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6981,
"level": 1,
"question": "Write a function that takes a string of comma-separated numbers as input and returns the sum of the squares of those numbers. Assume the input string will always contain valid integers separated by commas.\n\nFor example,\n\n```\ninput: \"1,2,3,4\"\nou... |
def common_elements(list1, list2):
"""
Returns a new list containing only the elements that are present in both input lists.
Args:
list1: The first list.
list2: The second list.
Returns:
A new list containing the common elements, with each element appearing once.
"""
co... | simplelr_Filter | [
{
"content": "Question:\nI need to write code that takes two lists as input and returns a new list containing only the elements that are present in both input lists\n\n \n**Here's what I have so far:**\n\n```python\ndef common_elements(list1, list2):\n \"\"\"\n Returns a new list containing only the elements ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6982,
"level": 1,
"question": "I need to write code that takes two lists as input and returns a new list containing only the elements that are present in both input lists\n\n \n**Here's what I have so far:**\n\n```python\ndef common_elements(list1, list2):\n \"\"\"\n Returns a new... |
from typing import List
def sweetest_candies(n: int, k: int, sweetness_levels: List[int]) -> List[int]:
sorted_sweetness = sorted(sweetness_levels, reverse=True)
return sorted_sweetness[:k] | simplelr_Codeforces | [
{
"content": "Question:\nMarcus has a collection of n different types of candies, and each candy type has a distinct sweetness level. He wants to find the k sweetest candies from his collection and eat them. Can you help him determine which candies to eat?\n\nThe input will be two integers n (1 ≤ n ≤ 1000) and ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6983,
"level": 1,
"question": "Marcus has a collection of n different types of candies, and each candy type has a distinct sweetness level. He wants to find the k sweetest candies from his collection and eat them. Can you help him determine which candies to eat?\n\nThe input will be... |
def max_product(arr):
sorted_arr = sorted(arr)
n = len(sorted_arr)
candidate1 = sorted_arr[-1] * sorted_arr[-2] * sorted_arr[-3]
candidate2 = sorted_arr[0] * sorted_arr[1] * sorted_arr[-1]
return max(candidate1, candidate2)
| simplelr_Taco | [
{
"content": "Question:\n### Example\n\nGiven a list of integers, find the maximum product of any three integers in the list.\n\n**Input**\n\n- A single list of integers `arr` (2 <= len(arr) <= 1000, -1000 <= arr[i] <= 1000)\n\n**Output**\n\n- The maximum product of any three integers.\n\n**Example**\n\nInput\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6984,
"level": 1,
"question": "### Example\n\nGiven a list of integers, find the maximum product of any three integers in the list.\n\n**Input**\n\n- A single list of integers `arr` (2 <= len(arr) <= 1000, -1000 <= arr[i] <= 1000)\n\n**Output**\n\n- The maximum product of any three ... |
from collections import deque
def max_sliding_window(arr, k):
if not arr or k == 0 or k > len(arr):
return []
dq = deque()
result = []
for i in range(len(arr)):
# Remove elements from the end which are smaller than the current element
while dq and arr[dq[-1]] <= arr[i]... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are developing a real-time monitoring system that needs to provide continuous updates on the maximum pressure levels recorded in sliding windows of a fixed duration within a stream of sensor data. To facilitate this, you need to implement a function that efficiently ca... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6985,
"level": 1,
"question": "### Scenario\nYou are developing a real-time monitoring system that needs to provide continuous updates on the maximum pressure levels recorded in sliding windows of a fixed duration within a stream of sensor data. To facilitate this, you need to imple... |
import itertools
def all_subsets(arr):
return [list(subset) for r in range(len(arr) + 1) for subset in itertools.combinations(arr, r)] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that returns all possible subsets of a given integer array, including the empty set. The function should be able to handle arrays of varying sizes and data types. The function should also be optimized for performance.\nAnswer:\nLet's think step by step.\n",
"role":... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6986,
"level": 1,
"question": "Create a function that returns all possible subsets of a given integer array, including the empty set. The function should be able to handle arrays of varying sizes and data types. The function should also be optimized for performance.",
"split": "tr... |
def longest_common_subsequence(str1, str2):
m = len(str1)
n = len(str2)
# Create a DP table with dimensions (m+1) x (n+1)
dp = [[0] * (n+1) for _ in range(m+1)]
# Fill the DP table
for i in range(1, m+1):
for j in range(1, n+1):
if str1[i-1] == str2[j-1]:
... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python code snippet to find the longest common subsequence (LCS) between two strings `str1` and `str2`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6987,
"level": 1,
"question": "Create a Python code snippet to find the longest common subsequence (LCS) between two strings `str1` and `str2`.",
"split": "train"
} |
def can_form_palindrome(input_str: str) -> bool:
freq = {}
n = 0
for c in input_str:
if c.isalnum():
c_lower = c.lower()
if c_lower in freq:
freq[c_lower] += 1
else:
freq[c_lower] = 1
n += 1
if n == 0:
return... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Validate Palindrome Permutation\n\n#### Context:\nA palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward (ignoring spaces, punctuation, and capitalization). A permutation is a rearrangement of a sequence. You need t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6988,
"level": 1,
"question": "### Question: Validate Palindrome Permutation\n\n#### Context:\nA palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward (ignoring spaces, punctuation, and capitalization). A permutation is a rear... |
import urllib.request
import urllib.parse
from urllib.error import HTTPError, URLError
def http_request_handler(
url: str, request_type: str, data: dict = None, headers: dict = None
) -> dict:
result = {
'status': 'error',
'response_code': 0,
'final_url': url,
'content': '',
... | simplelr_Docs | [
{
"content": "Question:\n### HTTP Request Handling with `urllib.request`\n\n#### Objective\nIn this task, you will demonstrate your understanding of the `urllib.request` module by writing a function that performs various types of HTTP requests (GET and POST) and handles responses and exceptions appropriately.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6989,
"level": 1,
"question": "### HTTP Request Handling with `urllib.request`\n\n#### Objective\nIn this task, you will demonstrate your understanding of the `urllib.request` module by writing a function that performs various types of HTTP requests (GET and POST) and handles respon... |
def is_rotated_password(password: str, candidate: str) -> bool:
if len(password) != len(candidate):
return False
if len(password) == 0:
return True
return candidate in (password + password) | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nIn a secure communication system, it's critical to identify if a received password is merely a rotated version of a known password from the database for integrity checks. As a developer, you're tasked to implement a function that serves this purpose efficiently.\n\n#### P... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6990,
"level": 1,
"question": "#### Scenario\nIn a secure communication system, it's critical to identify if a received password is merely a rotated version of a known password from the database for integrity checks. As a developer, you're tasked to implement a function that serves ... |
def minimizeTimeDifference(nums):
total = sum(nums)
k = len(nums) // 2
target = total / 2
# Initialize DP: dp[m] is a set of sums possible with m elements
dp = [set() for _ in range(k + 1)]
dp[0].add(0)
for num in nums:
# Iterate from k down to 1 to avoid overwriting dp[m] values t... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums` where each integer represents the number of seconds it takes to complete a task. Your goal is to schedule these tasks on two processors such that the difference between their total completion times is minimized.\n\nWrite a function `minimizeTime... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6991,
"level": 1,
"question": "You are given an array of integers `nums` where each integer represents the number of seconds it takes to complete a task. Your goal is to schedule these tasks on two processors such that the difference between their total completion times is minimized... |
def count_non_null_columns(matrix, row_index):
return sum(1 for value in matrix[row_index] if value is not None) | simplelr_Filter | [
{
"content": "Question:\nI have a scenario where I have to calculate the number of columns that have non-null values in a particular row of a given 2D array (or matrix).\n\nHere is a simple implementation in Python:\n\n```python\ndef count_non_null_columns(matrix, row_index):\n count = 0\n for col_index i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6992,
"level": 1,
"question": "I have a scenario where I have to calculate the number of columns that have non-null values in a particular row of a given 2D array (or matrix).\n\nHere is a simple implementation in Python:\n\n```python\ndef count_non_null_columns(matrix, row_index):\... |
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
| simplelr_Taco | [
{
"content": "Question:\nCreate a function that takes an array of integers and a target integer. The function should return indices of the two numbers such that they add up to the target. Assume that each input would have exactly one solution, and you may not use the same element twice.\n\nExamples:\n\n- Input:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6993,
"level": 1,
"question": "Create a function that takes an array of integers and a target integer. The function should return indices of the two numbers such that they add up to the target. Assume that each input would have exactly one solution, and you may not use the same elem... |
def unique_paths_with_obstacles(obstacle_grid):
m = len(obstacle_grid)
if m == 0:
return 0
n = len(obstacle_grid[0])
dp = [[0] * n for _ in range(m)]
if obstacle_grid[0][0] == 1:
return 0
dp[0][0] = 1
for i in range(m):
for j in range(n):
if i ==... | simplelr_Package | [
{
"content": "Question:\n**Grid Pathfinding with Obstacles**\n\nYou have been tasked with writing a function that computes the number of unique paths from the top-left corner to the bottom-right corner of an `m x n` grid, given that some cells in the grid contain obstacles which cannot be traversed. The only al... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6994,
"level": 1,
"question": "**Grid Pathfinding with Obstacles**\n\nYou have been tasked with writing a function that computes the number of unique paths from the top-left corner to the bottom-right corner of an `m x n` grid, given that some cells in the grid contain obstacles whi... |
from typing import List
def reorder_array(arr: List[int]) -> List[int]:
evens = []
odds = []
for num in arr:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens + odds | simplelr_Apps | [
{
"content": "Question:\n### Kata Task\n\nYou are given an array of integers. Your task is to rearrange the array so that all the even elements appear before all the odd elements.\n\nWrite a function that takes in an array of integers and returns the reordered array with even numbers first, followed by odd numb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6995,
"level": 1,
"question": "### Kata Task\n\nYou are given an array of integers. Your task is to rearrange the array so that all the even elements appear before all the odd elements.\n\nWrite a function that takes in an array of integers and returns the reordered array with even ... |
def reverse_string(s):
if s is None or len(s) == 0:
return None
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse a given string in Python. If the input string is `None` or empty, return `None`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6996,
"level": 1,
"question": "Write a function to reverse a given string in Python. If the input string is `None` or empty, return `None`.",
"split": "train"
} |
def update_inventory(initial_inventory: dict, transactions: list) -> dict:
current_inventory = initial_inventory.copy()
for item, delta in transactions:
current_inventory[item] = max(current_inventory[item] + delta, 0)
return current_inventory | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Scenario\n\nYou are working on a project to help a local grocery store with its inventory management. The store wants to keep track of items' stock levels automatically. Your task is to write a function that updates the inventory based on a list of transactions. Each transac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6997,
"level": 1,
"question": "### Problem Scenario\n\nYou are working on a project to help a local grocery store with its inventory management. The store wants to keep track of items' stock levels automatically. Your task is to write a function that updates the inventory based on a... |
def fruit_basket_weight(fruits: list[dict]) -> int:
total = 0
for fruit in fruits:
total += fruit['weight']
return total | simplelr_Algorithm | [
{
"content": "Question:\n### Fruit Basket Weight Calculation\n\nYou are given a list of fruits, each represented by a dictionary containing the name of the fruit and its weight in grams. Write a function `fruit_basket_weight(fruits: list[dict]) -> int` that computes the total weight of the fruits in the basket.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6998,
"level": 1,
"question": "### Fruit Basket Weight Calculation\n\nYou are given a list of fruits, each represented by a dictionary containing the name of the fruit and its weight in grams. Write a function `fruit_basket_weight(fruits: list[dict]) -> int` that computes the total ... |
def max_product_subarray(arr):
if not arr:
return 0
max_so_far = current_max = current_min = arr[0]
for num in arr[1:]:
temp_max = current_max
temp_min = current_min
current_max = max(num, temp_max * num, temp_min * num)
current_min = min(num, temp_max * num, temp_min... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the contiguous subarray within an array which has maximum product. For example, for the array`[2, 3, -2, 4]`, the contiguous subarray is `[2, 3]` which has maximum product `6`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6999,
"level": 1,
"question": "Write a function to find the contiguous subarray within an array which has maximum product. For example, for the array`[2, 3, -2, 4]`, the contiguous subarray is `[2, 3]` which has maximum product `6`.",
"split": "train"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.