target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
def find_common_elements(arr1, arr2):
i = j = 0
res = []
len1, len2 = len(arr1), len(arr2)
while i < len1 and j < len2:
if arr1[i] < arr2[j]:
i += 1
elif arr1[i] > arr2[j]:
j += 1
else:
res.append(arr1[i])
current = arr1[i]
... | simplelr_Filter | [
{
"content": "Question:\nDesign an algorithm to find the common elements between two sorted arrays. If there are no common elements, the algorithm should return an empty array. Please also consider the time and space complexity of your solution.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9900,
"level": 1,
"question": "Design an algorithm to find the common elements between two sorted arrays. If there are no common elements, the algorithm should return an empty array. Please also consider the time and space complexity of your solution.",
"split": "train"
} |
def merge_sorted_lists(a, b):
result = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] < b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
result += a[i:]
result += b[j:]
return result
| simplelr_Taco | [
{
"content": "Question:\nComplete the function that accepts two sorted lists of integers and merges them into a single sorted list. The original lists should not be modified.\n\n## Examples\n```\n[1, 3, 5], [2, 4, 6] ==> [1, 2, 3, 4, 5, 6]\n[7, 8], [1, 2, 3, 4, 6] ==> [1, 2, 3, 4, 6, 7, 8]\n```\nAnswer:\nLet's ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9901,
"level": 1,
"question": "Complete the function that accepts two sorted lists of integers and merges them into a single sorted list. The original lists should not be modified.\n\n## Examples\n```\n[1, 3, 5], [2, 4, 6] ==> [1, 2, 3, 4, 5, 6]\n[7, 8], [1, 2, 3, 4, 6] ==> [1, 2, 3... |
def find_duplicates(lst):
seen = set()
duplicates = []
added = set()
for num in lst:
if num in seen:
if num not in added:
duplicates.append(num)
added.add(num)
else:
seen.add(num)
return duplicates | simplelr_Filter | [
{
"content": "Question:\nDefine a function called `find_duplicates` that takes a list of integers as input and returns a new list containing only the duplicate elements from the input list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9902,
"level": 1,
"question": "Define a function called `find_duplicates` that takes a list of integers as input and returns a new list containing only the duplicate elements from the input list.",
"split": "train"
} |
def remove_duplicates(nums):
if not nums:
return 0
write_pointer = 0
for i in range(1, len(nums)):
if nums[i] != nums[write_pointer]:
write_pointer += 1
nums[write_pointer] = nums[i]
return write_pointer + 1 | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **sorted** integer array `nums` of length `n`. Your task is to remove all duplicate elements in-place such that each unique element appears only **once** while preserving the sorted order. The relative order of the elements should not be changed. After removing the dupli... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9903,
"level": 1,
"question": "You are given a **sorted** integer array `nums` of length `n`. Your task is to remove all duplicate elements in-place such that each unique element appears only **once** while preserving the sorted order. The relative order of the elements should not b... |
def second_largest_and_smallest(arr):
if len(arr) < 2:
return []
sorted_arr = sorted(arr)
second_smallest = sorted_arr[1]
second_largest = sorted_arr[-2]
return [second_smallest, second_largest] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers as input and returns an array containing the second largest and second smallest numbers from the input array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9904,
"level": 1,
"question": "Create a function that takes an array of integers as input and returns an array containing the second largest and second smallest numbers from the input array.",
"split": "train"
} |
def longest_consecutive_subsequence(nums: list[int]) -> int:
if not nums:
return 0
s = set(nums)
max_len = 0
for x in s:
if (x - 1) not in s:
current_len = 1
current_num = x + 1
while current_num in s:
current_len += 1
c... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Question:\nYou are required to develop a function that calculates the Longest Consecutive Subsequence (LCS) in a given list of integers. The LCS is defined as the length of the longest subsequence of consecutive integers in the list.\n\n**Function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9905,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Question:\nYou are required to develop a function that calculates the Longest Consecutive Subsequence (LCS) in a given list of integers. The LCS is defined as the length of the longest subsequence of consecutive i... |
from typing import List
def ternary_search(left: int, right: int, key: int, arr: List[int]) -> int:
while left <= right:
mid1 = left + (right - left) // 3
mid2 = right - (right - left) // 3
if arr[mid1] == key:
return mid1
if arr[mid2] == key:
return... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a sorted array of integers and a target integer. Your task is to implement the `ternary_search` function to find the index of the target integer within the sorted array. If the target integer is found, return its index; otherwise, return -1.\n\n### Function Signature\n\n``... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9906,
"level": 1,
"question": "You are given a sorted array of integers and a target integer. Your task is to implement the `ternary_search` function to find the index of the target integer within the sorted array. If the target integer is found, return its index; otherwise, return ... |
def count_valid_subarrays(nums, x, y):
current_run = 0
result = 0
for num in nums:
if x <= num <= y:
current_run += 1
else:
if current_run > 0:
result += current_run * (current_run + 1) // 2
current_run = 0
if current_run > 0:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` and two integers `x` and `y`. A subarray is valid if its minimum value is at least `x` and its maximum value is at most `y`. Return the total number of valid subarrays in `nums`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9907,
"level": 1,
"question": "You are given an integer array `nums` and two integers `x` and `y`. A subarray is valid if its minimum value is at least `x` and its maximum value is at most `y`. Return the total number of valid subarrays in `nums`.",
"split": "train"
} |
from typing import List
def sum_of_squares(arr: List[int]) -> int:
return sum(num ** 2 for num in set(arr)) | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of Squares of Distinct Elements\n\n#### Problem Statement\nYou are given an array of positive integers. Your task is to find the sum of the squares of all distinct elements in the array. If the array is empty, return 0.\n\n### Function Signature\n```python\ndef sum_of_squares(ar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9908,
"level": 1,
"question": "### Sum of Squares of Distinct Elements\n\n#### Problem Statement\nYou are given an array of positive integers. Your task is to find the sum of the squares of all distinct elements in the array. If the array is empty, return 0.\n\n### Function Signatur... |
def most_frequent_element(lst):
if not lst:
return None
freq = {}
min_element = None
max_freq = 0
for num in lst:
freq[num] = freq.get(num, 0) + 1
current_freq = freq[num]
if current_freq > max_freq:
max_freq = current_freq
min_element = num
... | simplelr_Filter | [
{
"content": "Question:\nHey, can you help me with a Python function to find the most frequent element in a list? If there are multiple elements with the same highest frequency, it should return the smallest one in terms of value.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9909,
"level": 1,
"question": "Hey, can you help me with a Python function to find the most frequent element in a list? If there are multiple elements with the same highest frequency, it should return the smallest one in terms of value.",
"split": "train"
} |
def maxProduct(nums):
if not nums:
return 0
max_so_far = min_so_far = result = nums[0]
for i in range(1, len(nums)):
if nums[i] < 0:
max_so_far, min_so_far = min_so_far, max_so_far
max_so_far = max(nums[i], max_so_far * nums[i])
min_so_far = min(nums[i], min_so... | simplelr_Filter | [
{
"content": "Question:\n### A non-empty list of non-negative integers is given, and we need to find the maximum value that can be obtained by multiplying all the numbers in any contiguous subarray.\n### The maximum product of a subarray can be found using Kadane's algorithm, which is a dynamic programming appr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9910,
"level": 1,
"question": "### A non-empty list of non-negative integers is given, and we need to find the maximum value that can be obtained by multiplying all the numbers in any contiguous subarray.\n### The maximum product of a subarray can be found using Kadane's algorithm, ... |
def count_even_odd_digits(num):
num = abs(num)
num_str = str(num)
even_count = 0
odd_count = 0
for char in num_str:
digit = int(char)
if digit % 2 == 0:
even_count += 1
else:
odd_count += 1
return (even_count, odd_count) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function named `count_even_odd_digits` that takes an integer `num` as input and returns a tuple with the first element being the count of even digits in `num` and the second element being the count of odd digits in `num`. The function should handle negative integers by tr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9911,
"level": 1,
"question": "Write a Python function named `count_even_odd_digits` that takes an integer `num` as input and returns a tuple with the first element being the count of even digits in `num` and the second element being the count of odd digits in `num`. The function sh... |
def linear_search(arr, value):
for i in range(len(arr)):
if arr[i] == value:
return True
return False | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two parameters: an array and a value. The function should return true if the value is present in the array, and false otherwise. However, the function should implement a linear search algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9912,
"level": 1,
"question": "Create a function that takes two parameters: an array and a value. The function should return true if the value is present in the array, and false otherwise. However, the function should implement a linear search algorithm.",
"split": "train"
} |
from collections import Counter
def most_frequent_word(text):
text_lower = text.lower()
punct = {'.', ',', '!', '?'}
words = text_lower.split()
stripped_words = []
for word in words:
stripped = word.strip(''.join(punct))
if stripped:
stripped_words.append(stripped)
... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a string of text as input, processes it, and outputs the word that appears the most frequently in the text. If two or more words have the highest frequency, return the one that appears first in alphabetic order. The function should be case-insensitive and ign... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9913,
"level": 1,
"question": "Write a function that takes a string of text as input, processes it, and outputs the word that appears the most frequently in the text. If two or more words have the highest frequency, return the one that appears first in alphabetic order. The function... |
def categorize_integers(int_list):
result = {
'Divisible by 2': [],
'Divisible by 3': [],
'Neither': []
}
for num in int_list:
if num % 2 == 0:
result['Divisible by 2'].append(num)
else:
if num % 3 == 0:
result['Divisible by 3']... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function that processes a list of integers to categorize them into three lists based on their divisibility by 2, 3, or neither. The function will return a dictionary with keys 'Divisible by 2', 'Divisible by 3', and 'Neither', corresponding to the lists of... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9914,
"level": 1,
"question": "You are tasked with creating a function that processes a list of integers to categorize them into three lists based on their divisibility by 2, 3, or neither. The function will return a dictionary with keys 'Divisible by 2', 'Divisible by 3', and 'Neit... |
def find_reachable_nodes(graph, source):
if source not in graph:
return set()
stack = []
visited = set()
stack.append(source)
visited.add(source)
while stack:
node = stack.pop()
for neighbor in graph[node]:
if neighbor not in visited:
visited.a... | simplelr_Filter | [
{
"content": "Question:\n# Given a directed graph, implement a stack-based algorithm to find all reachable nodes from a given source node.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9915,
"level": 1,
"question": "# Given a directed graph, implement a stack-based algorithm to find all reachable nodes from a given source node.",
"split": "train"
} |
def reverse_integer(n):
sign = -1 if n < 0 else 1
n *= sign
reversed_n = 0
while n > 0:
reversed_n = reversed_n * 10 + n % 10
n //= 10
return sign * reversed_n | simplelr_Filter | [
{
"content": "Question:\ndef reverse_integer(n):\n sign = -1 if n < 0 else 1\n n *= sign\n reversed_n = 0\n while n > 0:\n reversed_n = reversed_n * 10 + n % 10\n n //= 10\n return sign * reversed_n\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9916,
"level": 1,
"question": "def reverse_integer(n):\n sign = -1 if n < 0 else 1\n n *= sign\n reversed_n = 0\n while n > 0:\n reversed_n = reversed_n * 10 + n % 10\n n //= 10\n return sign * reversed_n",
"split": "train"
} |
def square_list(numbers):
"""Squares each number in a list.
Args:
numbers: A list of integers.
Returns:
A new list with the squares of the original integers.
"""
return [x ** 2 for x in numbers] | simplelr_Filter | [
{
"content": "Question:\nHere are the instructions for the task:\n\n* **Input:** A list of integers.\n* **Output:** A new list with the squares of the original integers.\n\nCan you write a Python code snippet to achieve this?\n\n```python\ndef square_list(numbers):\n \"\"\"Squares each number in a list.\n\n A... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9917,
"level": 1,
"question": "Here are the instructions for the task:\n\n* **Input:** A list of integers.\n* **Output:** A new list with the squares of the original integers.\n\nCan you write a Python code snippet to achieve this?\n\n```python\ndef square_list(numbers):\n \"\"\"Sq... |
import math
def main():
"""
This script welcomes the user, calculates square roots, and allows
the user to perform multiple calculations.
"""
user_name = input("Please enter your name: ")
print(f"Welcome, {user_name}!")
while True:
try:
number = float(input("Enter a... | simplelr_Filter | [
{
"content": "Question:\nPlease write a Python script that performs the following:\n\n1. Asks the user for their name.\n2. Prints a welcome message using the user's name.\n3. Asks the user to enter a number.\n4. Prints thesquare root of the number entered by the user.\n5. Asks the user if they would like to per... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9918,
"level": 1,
"question": "Please write a Python script that performs the following:\n\n1. Asks the user for their name.\n2. Prints a welcome message using the user's name.\n3. Asks the user to enter a number.\n4. Prints thesquare root of the number entered by the user.\n5. Asks... |
def check_subarray_average(nums, k, x):
n = len(nums)
if k <= 0 or k > n:
return False
target = x * k
current_sum = sum(nums[:k])
if current_sum >= target:
return True
for i in range(1, n - k + 1):
current_sum = current_sum - nums[i-1] + nums[i + k - 1]
if current... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` of length `n` and an integer `k`. Your task is to determine whether there exists a subarray of `nums` of length `k` such that the average of the elements in the subarray is greater than or equal to a given integer `x`. If such a subarray exists, ret... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9919,
"level": 1,
"question": "You are given an integer array `nums` of length `n` and an integer `k`. Your task is to determine whether there exists a subarray of `nums` of length `k` such that the average of the elements in the subarray is greater than or equal to a given integer ... |
def first_non_repeated(s):
# Count the frequency of each character
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
# Find the first character with count 1
for char in s:
if counts[char] == 1:
return char
return None | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns the first non-repeated character in the string. If all characters are repeated or the string is empty, the function should return `None`. You should aim for a solution that has an optimal time complexity.\n\n**Example:**\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9920,
"level": 1,
"question": "Write a Python function that takes a string as input and returns the first non-repeated character in the string. If all characters are repeated or the string is empty, the function should return `None`. You should aim for a solution that has an optimal... |
MOD = 10**9 + 7
def number_of_paths(grid):
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
if grid[0][0] == 1 or grid[m-1][n-1] == 1:
return 0
dp = [[0] * n for _ in range(m)]
dp[0][0] = 1
for i in range(m):
for j in range(n):
... | simplelr_Taco | [
{
"content": "Question:\nImagine you're given a rectangular grid of cells with dimensions m by n, where each cell can either be empty or blocked. You are positioned at the top-left corner of the grid, and you need to find the number of distinct paths to reach the bottom-right cell. You can only move either down... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9921,
"level": 1,
"question": "Imagine you're given a rectangular grid of cells with dimensions m by n, where each cell can either be empty or blocked. You are positioned at the top-left corner of the grid, and you need to find the number of distinct paths to reach the bottom-right ... |
def trap(heights):
n = len(heights)
if n < 3:
return 0
left_max = [0] * n
right_max = [0] * n
left_max[0] = heights[0]
for i in range(1, n):
left_max[i] = max(left_max[i-1], heights[i])
right_max[-1] = heights[-1]
for i in range(n-2, -1, -1):
right_max[i] = max... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of `n` positive integers representing the heights of `n` buildings, arrange them in such a way that the water trapped between them after a rain can be maximized. You need to return the maximum amount of water that can be trapped. \n\nAn array of heights `heights = [h1, h2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9922,
"level": 1,
"question": "Given an array of `n` positive integers representing the heights of `n` buildings, arrange them in such a way that the water trapped between them after a rain can be maximized. You need to return the maximum amount of water that can be trapped. \n\nAn ... |
def primaryDiagonalSum(N, Mat):
total = 0
for i in range(N):
total += Mat[i][i]
return total
| simplelr_Taco | [
{
"content": "Question:\nGiven an integer N and a square matrix Mat of dimensions NxN, the task is to find the primary diagonal sum of the matrix. The primary diagonal of a matrix consists of those elements that lie on the diagonal that runs from the top left corner to the bottom right corner.\n\nExample 1:\nIn... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9923,
"level": 1,
"question": "Given an integer N and a square matrix Mat of dimensions NxN, the task is to find the primary diagonal sum of the matrix. The primary diagonal of a matrix consists of those elements that lie on the diagonal that runs from the top left corner to the bot... |
def find_two_sum(nums, target):
seen = {}
for index, num in enumerate(nums):
complement = target - num
if complement in seen:
return (seen[complement], index)
seen[num] = index
return None | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are given an array of integers and an integer target. Your task is to find out whether two numbers in the array sum up to the given target. If such a pair exists, return the indices of the two numbers in a tuple (index1, index2). Note that the indices should b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9924,
"level": 1,
"question": "### Problem Statement\nYou are given an array of integers and an integer target. Your task is to find out whether two numbers in the array sum up to the given target. If such a pair exists, return the indices of the two numbers in a tuple (index1, inde... |
def max_profit(prices):
if len(prices) < 2:
return 0
min_price = prices[0]
max_profit = 0
for price in prices[1:]:
current_profit = price - min_price
if current_profit > max_profit:
max_profit = current_profit
if price < min_price:
min_price = pric... | simplelr_Codeforces | [
{
"content": "Question:\nGiven a list of stock prices for a company over a period of days, you are to find out the maximum profit that can be achieved by buying and then later selling one share of the stock. \n\n- You are allowed to complete at most one transaction, meaning you buy one and sell one share of the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9925,
"level": 1,
"question": "Given a list of stock prices for a company over a period of days, you are to find out the maximum profit that can be achieved by buying and then later selling one share of the stock. \n\n- You are allowed to complete at most one transaction, meaning yo... |
def nth_fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for i in range(2, n + 1):
c = a + b
a, b = b, c
return b | simplelr_Filter | [
{
"content": "Question:\nHow do I write a Python function which can return the Nth term of a sequence defined by a recursive formula?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9926,
"level": 1,
"question": "How do I write a Python function which can return the Nth term of a sequence defined by a recursive formula?",
"split": "train"
} |
def string_analysis(input_str):
result = {}
result['uppercase'] = input_str.upper()
result['lowercase'] = input_str.lower()
result['length'] = len(input_str)
vowels = {'a', 'e', 'i', 'o', 'u'}
vowel_count = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
for char in input_str:
low... | simplelr_Evol | [
{
"content": "Question:\nImplement a function that takes a string as input and returns a dictionary with the following details:\n\n1. The original string in all uppercase letters.\n2. The original string in all lowercase letters.\n3. The length of the original string.\n4. The count of each vowel (a, e, i, o, u)... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9927,
"level": 1,
"question": "Implement a function that takes a string as input and returns a dictionary with the following details:\n\n1. The original string in all uppercase letters.\n2. The original string in all lowercase letters.\n3. The length of the original string.\n4. The ... |
def caesar_cipher(message, shift):
encrypted = []
for c in message:
if c.isupper():
encrypted_char = chr(((ord(c) - ord('A') + shift) % 26) + ord('A'))
encrypted.append(encrypted_char)
elif c.islower():
encrypted_char = chr(((ord(c) - ord('a') + shift) % 26) +... | simplelr_Filter | [
{
"content": "Question:\nCreate a function in Python that implements a simple Caesar Cipher, where a message is encrypted by shifting the letters by a fixed number of positions in the alphabet. The function should take two parameters: the message to be encrypted and the shift value. It should return the encrypt... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9928,
"level": 1,
"question": "Create a function in Python that implements a simple Caesar Cipher, where a message is encrypted by shifting the letters by a fixed number of positions in the alphabet. The function should take two parameters: the message to be encrypted and the shift ... |
def reverse_words(sentence):
words = sentence.split()
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes an English sentence as input and returns the sentence with each word's letters reversed but with the words in their original order.\n\nThe input will consist of a single string containing alphabetic characters and spaces. The sentence will neither start nor e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9929,
"level": 1,
"question": "Write a function that takes an English sentence as input and returns the sentence with each word's letters reversed but with the words in their original order.\n\nThe input will consist of a single string containing alphabetic characters and spaces. Th... |
def reverse_number(num):
is_negative = False
if num < 0:
is_negative = True
num = abs(num)
reversed_str = str(num)[::-1]
reversed_num = int(reversed_str)
if is_negative:
reversed_num = -reversed_num
return reversed_num
# Example usage:
print(reverse_number(123)) # Out... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python script that can reverse the digits of a number and return the reversed number. The script should handle negative numbers as well.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9930,
"level": 1,
"question": "Write a Python script that can reverse the digits of a number and return the reversed number. The script should handle negative numbers as well.",
"split": "train"
} |
from collections import Counter
def are_anagrams(str1, str2):
if len(str1) != len(str2):
return False
return Counter(str1) == Counter(str2)
# Example usage:
print(are_anagrams("listen", "silent")) # Output: True
print(are_anagrams("hello", "world")) # Output: False | simplelr_Filter | [
{
"content": "Question:\nHow can I demonstrate that two strings are anagrams without sorting them, using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9931,
"level": 1,
"question": "How can I demonstrate that two strings are anagrams without sorting them, using Python?",
"split": "train"
} |
import heapq
def shortest_path(grid):
if not grid or not grid[0]:
return 0 # Handle empty grid case
n = len(grid)
m = len(grid[0])
# Initialize distance matrix with infinity
distance = [[float('inf')] * m for _ in range(n)]
distance[0][0] = grid[0][0] # Starting point's dist... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the shortest path in a grid from the top-left corner to the bottom-right corner. Return the total distance traveled. The grid is represented as a 2D array where each cell contains the distance cost to move into that cell.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9932,
"level": 1,
"question": "Write a function to find the shortest path in a grid from the top-left corner to the bottom-right corner. Return the total distance traveled. The grid is represented as a 2D array where each cell contains the distance cost to move into that cell.",
"... |
def find_first_duplicate(nums):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
return nums[i]
return None | simplelr_Filter | [
{
"content": "Question:\nGiven an array of integers, implement a function that uses a loop to find and return the first duplicate in the array.\n\nExample:\nInput: [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]\nOutput: 1\n\nExample:\nInput: [2, 3, 4, 5, 6, 7, 8, 9]\nOutput: None \n\nNote: The function should return the first ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9933,
"level": 1,
"question": "Given an array of integers, implement a function that uses a loop to find and return the first duplicate in the array.\n\nExample:\nInput: [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]\nOutput: 1\n\nExample:\nInput: [2, 3, 4, 5, 6, 7, 8, 9]\nOutput: None \n\nNote: Th... |
from typing import List
def search(nums: List[int], target: int) -> bool:
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return True
# Handle duplicates on the left
if nums[low] == nums[mid]:
if nums... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given an array of integers `nums` which is initially sorted in non-decreasing order but has been rotated at an unknown pivot. The array may contain duplicates. Your task is to determine if the target value exists within this array. Implement a function that takes `nums` and `tar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9934,
"level": 1,
"question": "You are given an array of integers `nums` which is initially sorted in non-decreasing order but has been rotated at an unknown pivot. The array may contain duplicates. Your task is to determine if the target value exists within this array. Implement a ... |
import re
def split_string(s):
return [word for word in re.split(r'[, ]+', s) if word] | simplelr_Filter | [
{
"content": "Question:\nCould you provide a Python function that can split a string into a list of words, considering both spaces and commas as delimiters?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9935,
"level": 1,
"question": "Could you provide a Python function that can split a string into a list of words, considering both spaces and commas as delimiters?",
"split": "train"
} |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import validation_curve, learning_curve
def analyze_model_performance(estimator, X, y, param_name, param_range, train_sizes, cv=5):
"""
Plots the validation curve and learning curve for a given estimator and dataset.
Param... | simplelr_Docs | [
{
"content": "Question:\n**Question: Analyze Model Performance with Validation and Learning Curves**\n\n**Objective:**\nYour task is to implement a function that plots both the validation curve and learning curve for a given estimator using the provided dataset. You should demonstrate a deep understanding of in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9936,
"level": 1,
"question": "**Question: Analyze Model Performance with Validation and Learning Curves**\n\n**Objective:**\nYour task is to implement a function that plots both the validation curve and learning curve for a given estimator using the provided dataset. You should dem... |
def capitalizeWord(text):
words = text.split()
capitalized = [word.capitalize() for word in words]
return ' '.join(capitalized) | simplelr_Leetcode | [
{
"content": "Question:\nYou are working on a text editor that provides a special operation called **capitalizeWord**. This operation takes a string and capitalizes the first letter of each word. Given a string `text`, implement a function to perform this operation. A word is defined as a sequence of non-space... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9937,
"level": 1,
"question": "You are working on a text editor that provides a special operation called **capitalizeWord**. This operation takes a string and capitalizes the first letter of each word. Given a string `text`, implement a function to perform this operation. A word is... |
def shift_right_circular(s):
return s[-1] + s[:-1] if s else s | simplelr_Filter | [
{
"content": "Question:\nI am a beginner to coding and I am trying to implement an algorithm that reads an input string and returns a string that is the result of shifting each character in the string one position to the right in a circular manner. \n\nFor example, if I input the string \"hello\", the output wo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9938,
"level": 1,
"question": "I am a beginner to coding and I am trying to implement an algorithm that reads an input string and returns a string that is the result of shifting each character in the string one position to the right in a circular manner. \n\nFor example, if I input ... |
def transform_dict(input_dict):
output_dict = {}
for value in input_dict.values():
output_dict[value['ip']] = value['os']
return output_dict
# Example usage:
transformed = transform_dict({
1: {"ip": "192.168.1.1", "os": "Windows"},
2: {"ip": "192.168.1.2", "os": "Ubuntu"},
3: {"ip": "19... | simplelr_Filter | [
{
"content": "Question:\nI have a dictionary with IP addresses of computers in a network and their respective operating systems. The dictionary is like this: \n`{1: {\"ip\": \"192.168.1.1\", \"os\": \"Windows\"}, 2: {\"ip\": \"192.168.1.2\", \"os\": \"Ubuntu\"}, 3: {\"ip\": \"192.168.1.3\", \"os\": \"MacOS\"}}`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9939,
"level": 1,
"question": "I have a dictionary with IP addresses of computers in a network and their respective operating systems. The dictionary is like this: \n`{1: {\"ip\": \"192.168.1.1\", \"os\": \"Windows\"}, 2: {\"ip\": \"192.168.1.2\", \"os\": \"Ubuntu\"}, 3: {\"ip\": \"... |
def find_closest_keys(dictionary, value):
smallest_diff = float('inf')
closest_keys = []
for key, val in dictionary.items():
current_diff = abs(val - value)
if current_diff < smallest_diff:
smallest_diff = current_diff
closest_keys = [key]
elif current_diff ==... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the closest value key in a dictionary to a given value. If there are multiple keys with the same closest value, return all of them in a list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9940,
"level": 1,
"question": "Write a python function to find the closest value key in a dictionary to a given value. If there are multiple keys with the same closest value, return all of them in a list.",
"split": "train"
} |
def draw_diagonal_pattern(n: int, char: str) -> list[str]:
result = []
for i in range(n):
row = []
for j in range(n):
if i == j or i + j == n - 1:
row.append(char)
else:
row.append(' ')
result.append(''.join(row))
return result | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Description\nYou need to write a Python function that simulates a simple pattern drawing on a 2D grid. Given the dimensions of the grid and a character to be used in drawing, the function will generate a square pattern where each diagonal line from the top-left to the bottom... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9941,
"level": 1,
"question": "### Problem Description\nYou need to write a Python function that simulates a simple pattern drawing on a 2D grid. Given the dimensions of the grid and a character to be used in drawing, the function will generate a square pattern where each diagonal l... |
def celsius_to_fahrenheit(celsius):
return celsius * (9/5) + 32 | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `celsius_to_fahrenheit` that converts a temperature from Celsius to Fahrenheit and returns the result. The function should take a single argument, the temperature in Celsius, and return the temperature in Fahrenheit as a float. The formula to convert Celsius to F... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9942,
"level": 1,
"question": "Write a Python function `celsius_to_fahrenheit` that converts a temperature from Celsius to Fahrenheit and returns the result. The function should take a single argument, the temperature in Celsius, and return the temperature in Fahrenheit as a float. ... |
def odd_index_characters(s):
return s[1::2] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that , given a string, will return a new string that contains only the odd-indexed characters from the original string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9943,
"level": 1,
"question": "Create a function that , given a string, will return a new string that contains only the odd-indexed characters from the original string.",
"split": "train"
} |
def enhanced_insertion_sort(arr: list) -> list:
n = len(arr)
# Pre-check if the array is already sorted
is_sorted = True
for i in range(n-1):
if arr[i] > arr[i+1]:
is_sorted = False
break
if is_sorted:
return arr
for i in range(1, n):
key... | simplelr_Data_Structure | [
{
"content": "Question:\nEnhanced Insertion Sort\n\n#### Problem Statement\nYou are tasked with enhancing the Insertion Sort algorithm to handle larger arrays more efficiently while maintaining its in-place sorting property. Your optimized version should terminate early if the array is already sorted at any poi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9944,
"level": 1,
"question": "Enhanced Insertion Sort\n\n#### Problem Statement\nYou are tasked with enhancing the Insertion Sort algorithm to handle larger arrays more efficiently while maintaining its in-place sorting property. Your optimized version should terminate early if the... |
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
def reduce_dimensionality(data: np.ndarray) -> tuple:
# Create a pipeline with standardization and PCA
pipeline = Pipeline([
('scaler', StandardScaler()),
... | simplelr_Docs | [
{
"content": "Question:\n## Problem Statement\n\nYou are provided with a dataset consisting of multiple features. Your task is to implement a scikit-learn pipeline that performs the following steps:\n\n1. Standardizes the data (features) using `StandardScaler`.\n2. Reduces the dimensionality of the dataset usin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9945,
"level": 1,
"question": "## Problem Statement\n\nYou are provided with a dataset consisting of multiple features. Your task is to implement a scikit-learn pipeline that performs the following steps:\n\n1. Standardizes the data (features) using `StandardScaler`.\n2. Reduces the... |
def minPipelineCost(depths):
if len(depths) <= 1:
return 0
return max(depths) - min(depths) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `depths` where `depths[i]` represents the depth of the `i-th` well in a village. A pipeline system is being planned such that it minimizes the total length of pipelines needed to connect all the wells. A pipeline can connect two wells `i` and `j` with a co... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9946,
"level": 1,
"question": "You are given an integer array `depths` where `depths[i]` represents the depth of the `i-th` well in a village. A pipeline system is being planned such that it minimizes the total length of pipelines needed to connect all the wells. A pipeline can conn... |
def find_minimum_element(nums):
if not nums:
return None
return min(nums) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the minimum element in a given list of integers. The function should return the minimum element. 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": 9947,
"level": 1,
"question": "Write a Python function to find the minimum element in a given list of integers. The function should return the minimum element. If the list is empty, the function should return `None`.",
"split": "train"
} |
from typing import TypeVar
import numbers
T = TypeVar('T', bound=numbers.Number)
def reverse_array(arr: list[T]) -> list[T]:
return arr[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts an integer array and reverses its elements. The function should be generic and able to handle arrays of any numeric type.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9948,
"level": 1,
"question": "Create a function that accepts an integer array and reverses its elements. The function should be generic and able to handle arrays of any numeric type.",
"split": "train"
} |
def find_longest_consecutive_subsequence(nums):
if not nums:
return 0
nums_set = set(nums)
max_length = 0
for num in nums_set:
if (num - 1) not in nums_set:
current_length = 1
current_num = num + 1
while current_num in nums_set:
current... | simplelr_Package | [
{
"content": "Question:\nYou are assigned the task of creating a function to identify the longest consecutive subsequence within an unsorted list of integers. A consecutive subsequence is defined as a sequence of numbers where each number follows the previous one without any gaps. Your solution should be effici... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9949,
"level": 1,
"question": "You are assigned the task of creating a function to identify the longest consecutive subsequence within an unsorted list of integers. A consecutive subsequence is defined as a sequence of numbers where each number follows the previous one without any g... |
def count_flips_to_convert(a: int, b: int) -> int:
diff = a ^ b
count = 0
while diff:
count += diff & 1
diff = diff >> 1
return count | simplelr_Data_Structure | [
{
"content": "Question:\n### Description:\nYou are given two integers, A and B. Your task is to determine the minimal number of bits you need to flip to convert integer A to integer B.\n\n### Input:\n- Two integers A and B, where (0 <= A, B <= 2^31 - 1).\n\n### Output:\n- A single integer representing the numbe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9950,
"level": 1,
"question": "### Description:\nYou are given two integers, A and B. Your task is to determine the minimal number of bits you need to flip to convert integer A to integer B.\n\n### Input:\n- Two integers A and B, where (0 <= A, B <= 2^31 - 1).\n\n### Output:\n- A si... |
def longest_common_prefix(strings):
if not strings:
return ""
prefix = []
min_length = min(len(s) for s in strings)
for i in range(min_length):
char = strings[0][i]
for s in strings[1:]:
if s[i] != char:
return ''.join(prefix)
prefix.append(cha... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python script that finds the longest common prefix among a list of strings? The script should be efficient and easy to understand.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9951,
"level": 1,
"question": "Can you provide a Python script that finds the longest common prefix among a list of strings? The script should be efficient and easy to understand.",
"split": "train"
} |
def sum_of_positive_integers(lst):
return sum(num for num in lst if num > 0) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns the sum of all positive integers in the list. Only consider integers greater than zero as positive.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9952,
"level": 1,
"question": "Create a function that takes a list of integers and returns the sum of all positive integers in the list. Only consider integers greater than zero as positive.",
"split": "train"
} |
def sum_of_squares(n):
n = abs(n)
total = 0
while n > 0:
digit = n % 10
total += digit ** 2
n = n // 10
return total
| simplelr_Taco | [
{
"content": "Question:\nGiven an integer `n`, return the sum of the squares of the digits of `n`. \n\n**Examples:**\n\n```python\nsum_of_squares(123) ==> 14\n# Explanation: 1^2 + 2^2 + 3^2 = 1 + 4 + 9 = 14\n\nsum_of_squares(49) ==> 97\n# Explanation: 4^2 + 9^2 = 16 + 81 = 97\n\nsum_of_squares(0) ==> 0\n# Ex... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9953,
"level": 1,
"question": "Given an integer `n`, return the sum of the squares of the digits of `n`. \n\n**Examples:**\n\n```python\nsum_of_squares(123) ==> 14\n# Explanation: 1^2 + 2^2 + 3^2 = 1 + 4 + 9 = 14\n\nsum_of_squares(49) ==> 97\n# Explanation: 4^2 + 9^2 = 16 + 81 = 97... |
import math
def solution(n):
if n < 0:
return False
s = math.isqrt(n)
return s * s == n | simplelr_Filter | [
{
"content": "Question:\n```python\ndef solution(n):\n # Your solution code goes here.\n return \n\n```\n\n**Function Description:**\n\nThe function should accept a positive integer `n` as input. It should check if the number is a perfect square. If it is, then the function should return `True`; otherwise, it... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9954,
"level": 1,
"question": "```python\ndef solution(n):\n # Your solution code goes here.\n return \n\n```\n\n**Function Description:**\n\nThe function should accept a positive integer `n` as input. It should check if the number is a perfect square. If it is, then the function ... |
def multiply_strings(num1: str, num2: str) -> str:
if num1 == '0' or num2 == '0':
return '0'
num1_rev = [int(c) for c in num1[::-1]]
num2_rev = [int(c) for c in num2[::-1]]
m, n = len(num1_rev), len(num2_rev)
result = [0] * (m + n)
for i in range(n):
for j in range... | simplelr_Data_Structure | [
{
"content": "Question:\n### String Multiplication Algorithm\n\n**Objective**: Implement a function `multiply_strings(num1: str, num2: str) -> str` that multiplies two non-negative integers represented as strings without converting them to integers directly or using any built-in BigInteger library.\n\n#### Guid... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9955,
"level": 1,
"question": "### String Multiplication Algorithm\n\n**Objective**: Implement a function `multiply_strings(num1: str, num2: str) -> str` that multiplies two non-negative integers represented as strings without converting them to integers directly or using any built-... |
def remove_duplicates(numbers):
seen = set()
result = []
for number in numbers:
if number not in seen:
seen.add(number)
result.append(number)
return result | simplelr_Filter | [
{
"content": "Question:\nGiven a list of numbers, write a Python function to return a list with all repeated elements removed.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9956,
"level": 1,
"question": "Given a list of numbers, write a Python function to return a list with all repeated elements removed.",
"split": "train"
} |
def string_lengths(string_list):
if not string_list:
return {}
result = {}
for string in string_list:
result[string] = len(string)
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of strings and returns a dictionary with the strings as keys and their lengths as values. Additionally, the function should handle an empty list by returning an empty dictionary. Ensure your code is self-contained and clear, with all necessary i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9957,
"level": 1,
"question": "Write a Python function that takes a list of strings and returns a dictionary with the strings as keys and their lengths as values. Additionally, the function should handle an empty list by returning an empty dictionary. Ensure your code is self-contai... |
from datetime import datetime
def calculate_trip_duration(start: str, end: str) -> dict:
# Parse the input strings into datetime objects
start_dt = datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
end_dt = datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
# Check if end is before start, return zeros if tru... | simplelr_Package | [
{
"content": "Question:\nWrite a function named `calculate_trip_duration` that takes two datetime strings in the format \"YYYY-MM-DD HH:MM:SS\" and calculates the total duration of the trip in days, hours, and minutes. The function should return the result as a dictionary containing the keys: \"days\", \"hours\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9958,
"level": 1,
"question": "Write a function named `calculate_trip_duration` that takes two datetime strings in the format \"YYYY-MM-DD HH:MM:SS\" and calculates the total duration of the trip in days, hours, and minutes. The function should return the result as a dictionary cont... |
def rotate_outer_layer(matrix):
n = len(matrix)
if n == 0:
return
if n == 1:
return
# Generate perimeter positions
positions = []
# Top row
for j in range(n):
positions.append((0, j))
# Right column
for i in range(1, n-1):
positions.append((i, n-1))
... | simplelr_Algorithm | [
{
"content": "Question:\n### Rotating Squares in NxN Matrix\n\n**Background**:\nAn NxN matrix can be visualized as a grid containing N rows and N columns, and its elements are integers. One common operation on such matrices is rotating the elements, particularly in squares or layers. Your task is to implement a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9959,
"level": 1,
"question": "### Rotating Squares in NxN Matrix\n\n**Background**:\nAn NxN matrix can be visualized as a grid containing N rows and N columns, and its elements are integers. One common operation on such matrices is rotating the elements, particularly in squares or ... |
def longest_word(words: list) -> tuple:
if not words:
return ("", 0)
longest_word = ""
max_length = 0
for word in words:
if len(word) > max_length:
longest_word = word
max_length = len(word)
return (longest_word, max_length) | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a list of words and returns the longest word in the list along with its length. If there are multiple words with the same maximum length, return the first one that appears in the list.\n\nFor example:\nInput: [\"apple\", \"banana\", \"kiwi\", \"strawberry\", ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9960,
"level": 1,
"question": "Write a function that takes a list of words and returns the longest word in the list along with its length. If there are multiple words with the same maximum length, return the first one that appears in the list.\n\nFor example:\nInput: [\"apple\", \"b... |
def reverse_string(s):
return s[::-1] | simplelr_Evol | [
{
"content": "Question:\nWrite a function `reverse_string` that takes a string `s` as an argument and returns the string with its characters in reverse order. For example, if the input is 'abcdef', the output should be 'fedcba'.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9961,
"level": 1,
"question": "Write a function `reverse_string` that takes a string `s` as an argument and returns the string with its characters in reverse order. For example, if the input is 'abcdef', the output should be 'fedcba'.",
"split": "train"
} |
def max_product(nums):
if not nums:
return 0 # Return 0 for empty array; adjust as needed
current_max = current_min = global_max = nums[0]
for num in nums[1:]:
temp_high = current_max * num
temp_low = current_min * num
current_max = max(temp_high, temp_low, num)
curr... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the maximum product of an array, considering both positive and negative numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9962,
"level": 1,
"question": "Write a function to find the maximum product of an array, considering both positive and negative numbers.",
"split": "train"
} |
from typing import List, Tuple
def is_point_inside_polygon(polygon: List[Tuple[int, int]], point: Tuple[int, int]) -> bool:
px, py = point
# Check if the point is a vertex of the polygon
if point in polygon:
return True
# Check if the point lies on any edge of the polygon
n = len(polyg... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are developing an application that processes geometric shapes and needs a utility to check if a provided point lies inside a given polygon. This functionality is crucial for operations like collision detection and geographical mapping.\n\n### Task\nImplement the functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9963,
"level": 1,
"question": "### Scenario\nYou are developing an application that processes geometric shapes and needs a utility to check if a provided point lies inside a given polygon. This functionality is crucial for operations like collision detection and geographical mapping... |
def maxMeetings(startTimes, endTimes):
meetings = sorted(zip(startTimes, endTimes), key=lambda x: x[1])
count = 0
last_end = -1
for start, end in meetings:
if start >= last_end:
count += 1
last_end = end
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two arrays, `startTimes` and `endTimes`, where `startTimes[i]` is the start time when a meeting `i` begins, and `endTimes[i]` is the end time when meeting `i` ends. These arrays are of equal length, representing multiple meetings. A person can attend a meeting if it starts... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9964,
"level": 1,
"question": "You are given two arrays, `startTimes` and `endTimes`, where `startTimes[i]` is the start time when a meeting `i` begins, and `endTimes[i]` is the end time when meeting `i` ends. These arrays are of equal length, representing multiple meetings. A perso... |
from typing import List, Tuple, Optional
from collections import defaultdict
def is_one_sparse(stream: List[Tuple[int, str]]) -> Optional[int]:
net = defaultdict(int)
for amount, sign in stream:
if sign == '+':
net[amount] += amount
else:
net[amount] -= amount
non_ze... | simplelr_Data_Structure | [
{
"content": "Question:\n**Scenario:**\nYou are working as a software engineer tasked with stream processing for a financial transaction system. The system captures a stream of transaction tuples (each containing an amount and a sign indicating addition or subtraction). Your goal is to determine if the transact... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9965,
"level": 1,
"question": "**Scenario:**\nYou are working as a software engineer tasked with stream processing for a financial transaction system. The system captures a stream of transaction tuples (each containing an amount and a sign indicating addition or subtraction). Your g... |
from typing import List
def efficient_cocktail_shaker_sort(arr: List[int]) -> List[int]:
n = len(arr)
if n <= 1:
return arr
left = 0
right = n - 1
swapped = True
while swapped:
swapped = False
# Left to Right pass
swapped_left = False
f... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\n\nPlease complete the function `efficient_cocktail_shaker_sort` that sorts an array of integers using an optimized version of the Cocktail Shaker Sort algorithm. The optimized version should attempt to reduce unnecessary passes once no further swaps are found in a single d... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9966,
"level": 1,
"question": "### Question\n\nPlease complete the function `efficient_cocktail_shaker_sort` that sorts an array of integers using an optimized version of the Cocktail Shaker Sort algorithm. The optimized version should attempt to reduce unnecessary passes once no fu... |
import re
def parse_string(s: str) -> dict:
tokens = re.findall(r'(\d+|[a-zA-Z]+|.)', s)
digits = []
words = []
special_chars = []
for token in tokens:
if token.isdigit():
digits.append(token)
elif token.isalpha():
words.append(token)
else:
... | simplelr_Evol | [
{
"content": "Question:\nImplement a function that parses a given string, extracts digits, words, and special characters, and returns them as separate lists. Ensure the function handles the following conditions:\n\n- Digits are defined as continuous sequences of numerical characters.\n- Words are defined as con... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9967,
"level": 1,
"question": "Implement a function that parses a given string, extracts digits, words, and special characters, and returns them as separate lists. Ensure the function handles the following conditions:\n\n- Digits are defined as continuous sequences of numerical char... |
def common_elements(arr1: list[int], arr2: list[int]) -> list[int]:
"""
Returns a sorted array of the common elements between two input sorted arrays.
"""
i = j = 0
result = []
while i < len(arr1) and j < len(arr2):
if arr1[i] == arr2[j]:
result.append(arr1[i])
i ... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Find the Common Elements in Sorted Arrays\n\nYou are asked to implement a function that takes two sorted arrays and returns a new array containing the common elements between the two arrays. The output array should also be sorted.\n\n#### Function Signature\n```python\ndef... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9968,
"level": 1,
"question": "### Question: Find the Common Elements in Sorted Arrays\n\nYou are asked to implement a function that takes two sorted arrays and returns a new array containing the common elements between the two arrays. The output array should also be sorted.\n\n####... |
def text_editor(n, operations):
text = []
undo_stack = []
for op in operations:
if op.startswith('ADD'):
x = op.split()[1]
text.append(x)
undo_stack.append(x)
elif op == 'UNDO':
if undo_stack:
text.pop()
undo_sta... | simplelr_Taco | [
{
"content": "Question:\nLinda is building a simple text editor and needs to implement an undo operation. The text editor initially contains an empty string. Each operation is either adding a character to the string, or undoing the latest operation.\n\nCreate a function `text_editor(n: int, operations: List[str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9969,
"level": 1,
"question": "Linda is building a simple text editor and needs to implement an undo operation. The text editor initially contains an empty string. Each operation is either adding a character to the string, or undoing the latest operation.\n\nCreate a function `text_... |
import re
def reverse_words_in_string(s: str) -> str:
if not s:
return s
tokens = re.findall(r'\s+|\S+', s)
words = [t for t in tokens if t.strip() != '']
reversed_words = words[::-1]
result = []
word_idx = 0
for token in tokens:
if token.strip() != '':
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\nYou are given a function that calculates the reverse of a string. Your task is to implement a new function named `reverse_words_in_string(s: str) -> str` that reverses the order of words in a given string while keeping the relative order of spaces intact.\n\n### ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9970,
"level": 1,
"question": "### Problem Statement:\nYou are given a function that calculates the reverse of a string. Your task is to implement a new function named `reverse_words_in_string(s: str) -> str` that reverses the order of words in a given string while keeping the relat... |
def sum_of_even_numbers(n):
return n * (n + 1) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the sum of the first n even natural numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9971,
"level": 1,
"question": "Write a python function to find the sum of the first n even natural numbers.",
"split": "train"
} |
def merge_lists_unique(list1, list2):
combined = list1 + list2
unique_elements = set(combined)
sorted_list = sorted(unique_elements)
return sorted_list | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function called \"merge_lists_unique\" that takes in two lists as parameters and returns a new list that contains the unique elements from both lists, in sorted order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9972,
"level": 1,
"question": "Write a Python function called \"merge_lists_unique\" that takes in two lists as parameters and returns a new list that contains the unique elements from both lists, in sorted order.",
"split": "train"
} |
def unique_paths_with_obstacles(grid):
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
if grid[0][0] == -1 or grid[m-1][n-1] == -1:
return 0
dp = [[0] * n for _ in range(m)]
dp[0][0] = 1 # Starting point
for i in range(m):
for j in range(n):
if i == 0 ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a 2D grid of `m` x `n` integers, find the number of unique paths from the top-left corner to the bottom-right corner. You can only move either down or right at any point in time. Additionally, some cells may be blocked (represented by a -1) and cannot be traversed. Return the numb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9973,
"level": 1,
"question": "Given a 2D grid of `m` x `n` integers, find the number of unique paths from the top-left corner to the bottom-right corner. You can only move either down or right at any point in time. Additionally, some cells may be blocked (represented by a -1) and c... |
def atm_simulation(commands: list) -> list:
current_balance = 0
results = []
for command in commands:
action, amount = command
if action == "DEPOSIT":
current_balance += amount
elif action == "WITHDRAW":
if current_balance >= amount:
current_ba... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are tasked with writing a function that simulates the behavior of an ATM machine. The function will manage deposits, withdrawals, and balance inquiries. It should handle multiple transactions while ensuring that overdraft does not occur.\n\n#### Function Sig... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9974,
"level": 1,
"question": "### Problem Statement\n\nYou are tasked with writing a function that simulates the behavior of an ATM machine. The function will manage deposits, withdrawals, and balance inquiries. It should handle multiple transactions while ensuring that overdraft d... |
def char_to_number_sum(s):
char_to_num = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10}
total = 0
for char in s:
if char in char_to_num:
total += char_to_num[char]
return total | simplelr_Filter | [
{
"content": "Question:\nCreate a dictionary in Python mapping the following characters to numbers: A = 1, B = 2, C = 3, D = 4, E = 5, F = 6, G = 7, H = 8, I = 9, J = 10. The function should ignore any character that is not in the given list. Additionally, the function should return the sum of the numbers assoc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9975,
"level": 1,
"question": "Create a dictionary in Python mapping the following characters to numbers: A = 1, B = 2, C = 3, D = 4, E = 5, F = 6, G = 7, H = 8, I = 9, J = 10. The function should ignore any character that is not in the given list. Additionally, the function should ... |
from typing import List, Tuple, Optional
def nearest_parking_spot(grid: List[List[int]]) -> Optional[Tuple[int, int]]:
min_dist = float('inf')
result = None
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 0:
distance = i + j
if d... | simplelr_Taco | [
{
"content": "Question:\nYou're managing a parking lot and want to help drivers find the nearest available parking spot. The parking lot can be represented as a 2D grid, where each cell is either taken (denoted by a value of `1`) or available (denoted by a value of `0`). Additionally, the grid starts at the top... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9976,
"level": 1,
"question": "You're managing a parking lot and want to help drivers find the nearest available parking spot. The parking lot can be represented as a 2D grid, where each cell is either taken (denoted by a value of `1`) or available (denoted by a value of `0`). Addit... |
def compare_length(a, b):
len_a = len(str(abs(a)))
len_b = len(str(abs(b)))
if len_a > len_b:
return "LONGER"
elif len_a == len_b:
return "SAME"
else:
return "SHORTER" | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two integers, a and b, and returns \"LONGER\" if a is longer than b, \"SAME\" if they are equal length, and \"SHORTER\" if a is shorter than b. An integer's length is defined as the number of digits it contains.\nAnswer:\nLet's think step by step.\n",
"r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9977,
"level": 1,
"question": "Create a function that takes two integers, a and b, and returns \"LONGER\" if a is longer than b, \"SAME\" if they are equal length, and \"SHORTER\" if a is shorter than b. An integer's length is defined as the number of digits it contains.",
"split"... |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def create_faceted_scatter_plot(data: pd.DataFrame):
# Set the Seaborn theme to ensure visual consistency
sns.set_theme()
# Create the faceted scatter plot using relplot
g = sns.relplot(
data=data,
x="total_bill"... | simplelr_Docs | [
{
"content": "Question:\n### Question: Creating a Multi-faceted Scatter Plot with Seaborn\n\n#### Objective:\nWrite a function `create_faceted_scatter_plot` that takes in a `pandas.DataFrame` and outputs a multi-faceted scatter plot using `seaborn` with the following specifications:\n\n1. The scatter plot shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9978,
"level": 1,
"question": "### Question: Creating a Multi-faceted Scatter Plot with Seaborn\n\n#### Objective:\nWrite a function `create_faceted_scatter_plot` that takes in a `pandas.DataFrame` and outputs a multi-faceted scatter plot using `seaborn` with the following specifica... |
import seaborn as sns
import matplotlib.pyplot as plt
def create_visualizations():
# Load the tips dataset
tips = sns.load_dataset("tips")
# Create a figure with two subplots
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# Univariate histogram for total_bill
sns.histplot(ax=axes[0],... | simplelr_Docs | [
{
"content": "Question:\n**Coding Question: Visualization with Seaborn**\n\n**Objective:**\nCreate a comprehensive visualization that displays the distribution and relationships of specific variables in a dataset using seaborn's `histplot` function.\n\n**Problem Statement:**\nYou have been provided with the `ti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9979,
"level": 1,
"question": "**Coding Question: Visualization with Seaborn**\n\n**Objective:**\nCreate a comprehensive visualization that displays the distribution and relationships of specific variables in a dataset using seaborn's `histplot` function.\n\n**Problem Statement:**\n... |
from collections import defaultdict
def count_anagrammatic_pairs(s):
n = len(s)
freq_map = defaultdict(int)
for l in range(1, n + 1):
for i in range(n - l + 1):
substr = s[i:i + l]
freq = {}
for c in substr:
freq[c] = freq.get(c, 0) + 1
... | simplelr_Code_Contests | [
{
"content": "Question:\n**Problem Statement: Finding Anagrammatic Pairs**\n\nAn anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the words \"listen\" and \"silent\" are anagrams of each other.\n\nIn ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9980,
"level": 1,
"question": "**Problem Statement: Finding Anagrammatic Pairs**\n\nAn anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the words \"listen\" and \"silent\"... |
def maxSubArraySum(arr, k):
n = len(arr)
if n < k:
return 0
# Compute the prefix sum array
prefix = [0] * (n + 1)
for i in range(n):
prefix[i+1] = prefix[i] + arr[i]
# Compute the suffix maximum array
suffix_max = [0] * (n + 1)
suffix_max[n] = prefix[n]
for ... | simplelr_Evol | [
{
"content": "Question:\nGiven an integer array `arr` and an integer `k`, write a function `maxSubArraySum(arr, k)` that computes the maximum sum of a subarray with at least length `k`. The function should return the maximum sum of such a subarray. If no valid subarray exists, return 0.\n\n**Example:**\n```\nIn... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9981,
"level": 1,
"question": "Given an integer array `arr` and an integer `k`, write a function `maxSubArraySum(arr, k)` that computes the maximum sum of a subarray with at least length `k`. The function should return the maximum sum of such a subarray. If no valid subarray exists,... |
def find_max(lst):
if not lst:
return None
current_max = lst[0]
for number in lst[1:]:
if number > current_max:
current_max = number
return current_max | simplelr_Filter | [
{
"content": "Question:\nGiven a list of integers, write a Python function to find the maximum number in the list using the built-in functions. Make sure to handle the case where the list is empty by returning None. Additionally, you are not allowed to use the built-in max() function or any sorting functions.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9982,
"level": 1,
"question": "Given a list of integers, write a Python function to find the maximum number in the list using the built-in functions. Make sure to handle the case where the list is empty by returning None. Additionally, you are not allowed to use the built-in max() f... |
def maxRectangleArea(heights):
stack = []
max_area = 0
n = len(heights)
for i in range(n):
while stack and heights[i] < heights[stack[-1]]:
h = stack.pop()
left = stack[-1] if stack else -1
width = i - left - 1
max_area = max(max_area, heights[h] *... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers representing the heights of the buildings in a city skyline. The array is structured such that heights[i] is the height of the ith building. \n\nWrite a program that calculates the maximum area of a rectangle formed by any combination of contiguous bui... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9983,
"level": 1,
"question": "You are given an array of integers representing the heights of the buildings in a city skyline. The array is structured such that heights[i] is the height of the ith building. \n\nWrite a program that calculates the maximum area of a rectangle formed b... |
import fnmatch
def filter_files(filenames: list[str], pattern: str) -> list[str]:
# Check for invalid characters in the pattern
allowed_chars = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-*?")
for c in pattern:
if c not in allowed_chars:
raise ValueError(f"Inva... | simplelr_Algorithm | [
{
"content": "Question:\n### File Type Filter\n\n**Problem Statement:**\n\nWrite a function `filter_files` that filters a list of filenames based on a given file extension or pattern. The function should return a list of filenames that match the provided extension or pattern. If no filenames match the given ext... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9984,
"level": 1,
"question": "### File Type Filter\n\n**Problem Statement:**\n\nWrite a function `filter_files` that filters a list of filenames based on a given file extension or pattern. The function should return a list of filenames that match the provided extension or pattern. ... |
def kth_largest_element(nums, k):
sorted_nums = sorted(nums, reverse=True)
return sorted_nums[k-1] | simplelr_Filter | [
{
"content": "Question:\nYou have a list of integers called nums and an integer k. Write a Python function to return the kth largest element in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9985,
"level": 1,
"question": "You have a list of integers called nums and an integer k. Write a Python function to return the kth largest element in the list.",
"split": "train"
} |
import heapq
from typing import List
def find_kth_largest(nums: List[int], k: int) -> int:
return heapq.nlargest(k, nums)[-1] | simplelr_Algorithm | [
{
"content": "Question:\n### Find Kth Largest Element in an Array\n\n#### Scenario\nYou are tasked with developing software for data analysis which includes finding the k-th largest element in a list of numbers. This is a common requirement in statistical analysis and data processing workflows.\n\n#### Task\nWr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9986,
"level": 1,
"question": "### Find Kth Largest Element in an Array\n\n#### Scenario\nYou are tasked with developing software for data analysis which includes finding the k-th largest element in a list of numbers. This is a common requirement in statistical analysis and data pro... |
def bubble_sort(lst):
for i in range(len(lst)):
for j in range(len(lst) - i - 1):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
return lst
numbers = [64, 34, 25, 12, 22, 11, 90]
sorted_numbers = bubble_sort(numbers)
print(sorted_numbers) | simplelr_Filter | [
{
"content": "Question:\nI've been trying to implement bubble sort but I'm having trouble with it. It seems to only sort a list partially and sometimes doesn't sort it at all. Here's the code:\n```python\ndef bubble_sort(lst):\n for i in range(len(lst)):\n for j in range(len(lst) - 1):\n if... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9987,
"level": 1,
"question": "I've been trying to implement bubble sort but I'm having trouble with it. It seems to only sort a list partially and sometimes doesn't sort it at all. Here's the code:\n```python\ndef bubble_sort(lst):\n for i in range(len(lst)):\n for j in r... |
def find_duplicate_and_missing(nums):
n = len(nums)
present = [False] * (n + 1)
duplicate = 0
for num in nums:
if present[num]:
duplicate = num
else:
present[num] = True
missing = 0
for i in range(1, n + 1):
if not present[i]:
missing =... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums` of length `n`, where every integer between `1` and `n` (inclusive) appears exactly once except one number which appears twice and another number which is missing. Determine the number which appears twice and the number which is missing. Return these two num... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9988,
"level": 1,
"question": "Given an integer array `nums` of length `n`, where every integer between `1` and `n` (inclusive) appears exactly once except one number which appears twice and another number which is missing. Determine the number which appears twice and the number whi... |
import math
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
max_divisor = math.isqrt(n) + 1
for i in range(3, max_divisor, 2):
if n % i == 0:
return False
return True
# Example usage:
print(is_prime(2)) #... | simplelr_Filter | [
{
"content": "Question:\nHow can I design a basic Python script that checks if a given number is a prime number or not? Can you provide a simple example?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9989,
"level": 1,
"question": "How can I design a basic Python script that checks if a given number is a prime number or not? Can you provide a simple example?",
"split": "train"
} |
def is_strictly_sorted(lst):
if len(lst) <= 1:
return True
first = lst[0]
second = lst[1]
if first == second:
return False
direction = 'asc' if second > first else 'desc'
for i in range(1, len(lst)):
current = lst[i]
prev = lst[i-1]
if direction == 'asc':
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to determine if a list of numbers is strictly sorted either in ascending or descending order. A number is considered strictly sorted if each element is either strictly greater than or strictly less than its predecessor.\nAnswer:\nLet's think step by step.\n",
"role"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9990,
"level": 1,
"question": "Write a function to determine if a list of numbers is strictly sorted either in ascending or descending order. A number is considered strictly sorted if each element is either strictly greater than or strictly less than its predecessor.",
"split": "t... |
import re
import binascii
def encode_decode_operations(operations: str, data: bytes) -> bytes:
op_pattern = re.compile(r'([a-zA-Z])(?:\((.*?)\))?')
ops = []
for match in op_pattern.finditer(operations):
op = match.group(1)
arg_str = match.group(2) or ''
ops.append((op, arg_str))
... | simplelr_Docs | [
{
"content": "Question:\n**Python Coding Assessment Question**\n\n### Problem Statement\n\nYou are tasked with implementing a function that performs multiple encoding and decoding operations on binary data using Python's `binascii` module. Your function will receive a string representing a sequence of operation... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9991,
"level": 1,
"question": "**Python Coding Assessment Question**\n\n### Problem Statement\n\nYou are tasked with implementing a function that performs multiple encoding and decoding operations on binary data using Python's `binascii` module. Your function will receive a string r... |
def add_with_carrying(num1: str, num2: str) -> str:
num1_rev = num1[::-1]
num2_rev = num2[::-1]
max_len = max(len(num1_rev), len(num2_rev))
carry = 0
result = []
for i in range(max_len):
digit1 = int(num1_rev[i]) if i < len(num1_rev) else 0
digit2 = int(num2_rev[i]) if i < l... | simplelr_Algorithm | [
{
"content": "Question:\n### Adding With Carrying\n\n#### Problem Statement:\nWrite a function `add_with_carrying(num1: str, num2: str) -> str` that takes two non-negative integer numbers represented as strings `num1` and `num2`, adds them together digit by digit from right to left, and returns the sum as a new... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9992,
"level": 1,
"question": "### Adding With Carrying\n\n#### Problem Statement:\nWrite a function `add_with_carrying(num1: str, num2: str) -> str` that takes two non-negative integer numbers represented as strings `num1` and `num2`, adds them together digit by digit from right to... |
def longest_common_prefix(strs):
if not strs:
return ""
min_len = min(len(s) for s in strs)
if min_len == 0:
return ""
prefix = ""
for i in range(min_len):
current_char = strs[0][i]
for s in strs[1:]:
if s[i] != current_char:
return prefix
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario:\nYou are developing an auto-complete feature for a search engine which presents suggestions based on the user's input. To do this, you need to find the longest common prefix from a list of user queries.\n\n### Task:\nWrite a function `longest_common_prefix(strs)` to determ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9993,
"level": 1,
"question": "### Scenario:\nYou are developing an auto-complete feature for a search engine which presents suggestions based on the user's input. To do this, you need to find the longest common prefix from a list of user queries.\n\n### Task:\nWrite a function `lon... |
def merge_dicts(dict1: dict, dict2: dict) -> dict:
merged = {}
all_keys = set(dict1.keys()).union(set(dict2.keys()))
for key in all_keys:
if key in dict1 and key in dict2:
merged[key] = [dict1[key], dict2[key]]
else:
merged[key] = dict1.get(key, dict2.get(key))
re... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with writing a function named `merge_dicts` in Python. The purpose of this function is to merge two dictionaries. If there are any common keys between the two dictionaries, the values should be combined into a list containing all values for that key, from both dictionarie... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9994,
"level": 1,
"question": "You are tasked with writing a function named `merge_dicts` in Python. The purpose of this function is to merge two dictionaries. If there are any common keys between the two dictionaries, the values should be combined into a list containing all values ... |
def find_anagrams(word, candidates):
word_lower = word.lower()
word_sorted = sorted(word_lower)
result = []
for candidate in candidates:
if len(candidate) != len(word):
continue
candidate_lower = candidate.lower()
candidate_sorted = sorted(candidate_lower)
if ... | simplelr_Apps | [
{
"content": "Question:\n# Task\n\nWrite a function `findAnagrams`/`find_anagrams()` that takes in two parameters:\n- `word` - a string to find anagrams for.\n- `candidates` - a list of strings to be tested as anagrams.\n\nYour function should return a list of candidates that are anagrams of the `word`. \n\nAn ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9995,
"level": 1,
"question": "# Task\n\nWrite a function `findAnagrams`/`find_anagrams()` that takes in two parameters:\n- `word` - a string to find anagrams for.\n- `candidates` - a list of strings to be tested as anagrams.\n\nYour function should return a list of candidates that ... |
def islandPerimeter(grid):
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
perimeter = 0
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
for d in directions:
ni = i + d[0]... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a 2D grid `grid` of size `m x n` that represents a map, where each cell represents land (1) or water (0), find the perimeter of the islands. The island does not have any lakes (water inside that isn't connected to the water around the island). Cells are connected horizontally/vert... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9996,
"level": 1,
"question": "Given a 2D grid `grid` of size `m x n` that represents a map, where each cell represents land (1) or water (0), find the perimeter of the islands. The island does not have any lakes (water inside that isn't connected to the water around the island). Ce... |
def find_duplicates(nums):
counts = {}
seen = set()
result = []
for num in nums:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
if counts[num] == 2 and num not in seen:
result.append(num)
seen.add(num)
return result | simplelr_Filter | [
{
"content": "Question:\n: Implement a function `find_duplicates(nums)` that takes a list of integers `nums` as input and returns a new list containing only the duplicate elements from the input list, preserving their original order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9997,
"level": 1,
"question": ": Implement a function `find_duplicates(nums)` that takes a list of integers `nums` as input and returns a new list containing only the duplicate elements from the input list, preserving their original order.",
"split": "train"
} |
def levenshtein_distance(s1, s2):
m = len(s1)
n = len(s2)
# Create a matrix with (m+1) rows and (n+1) columns initialized to 0
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Fill the first row and column
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] =... | simplelr_Filter | [
{
"content": "Question:\nHow can I efficiently calculate the Levenshtein distance between two strings in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9998,
"level": 1,
"question": "How can I efficiently calculate the Levenshtein distance between two strings in Python?",
"split": "train"
} |
def descending_order_comparison(first_string, second_string, third_string):
strings = [first_string, second_string, third_string]
max_val = max(int(s) for s in strings)
candidates = [s for s in strings if int(s) == max_val]
return min(candidates) | simplelr_Filter | [
{
"content": "Question:\nYou have three strings: `first_string`, `second_string`, and `third_string`. Each of these strings contains a single digit between '0' and '9' (inclusive). \n\nWrite a descending order comparison function that takes these three strings as input and returns the string containing the lar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9999,
"level": 1,
"question": "You have three strings: `first_string`, `second_string`, and `third_string`. Each of these strings contains a single digit between '0' and '9' (inclusive). \n\nWrite a descending order comparison function that takes these three strings as input and re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.