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 convert_to_title(num):
if num == 0:
return ""
result = ""
while num > 0:
num -= 1
remainder = num % 26
char = chr(ord('A') + remainder)
result = char + result
num = num // 26
return result | simplelr_Apps | [
{
"content": "Question:\nConvert a non-negative integer to its corresponding column title as appear in an Excel sheet.\n\nFor example:\n\nExample 1:\n\nInput: 1\nOutput: \"A\"\n\n\nExample 2:\n\nInput: 28\nOutput: \"AB\"\n\n\nExample 3:\n\nInput: 701\nOutput: \"ZY\"\n\n\nNote:\n- The input is a non-negative int... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8400,
"level": 1,
"question": "Convert a non-negative integer to its corresponding column title as appear in an Excel sheet.\n\nFor example:\n\nExample 1:\n\nInput: 1\nOutput: \"A\"\n\n\nExample 2:\n\nInput: 28\nOutput: \"AB\"\n\n\nExample 3:\n\nInput: 701\nOutput: \"ZY\"\n\n\nNote:... |
def find_intersection_point(line1, line2):
epsilon = 1e-9
# Extract points from each line
(x1, y1), (x2, y2) = line1
(x3, y3), (x4, y4) = line2
# Calculate the denominator
denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
# If denominator is near zero, lines are parallel or coin... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question: Intersection Point of Two Lines\nYou are tasked with writing a function to find the intersection point of two lines in a 2D plane. Each line is defined by two points. Implement a function `find_intersection_point(line1: Tuple[Tuple[float, float], Tuple[float, float]... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8401,
"level": 1,
"question": "### Coding Question: Intersection Point of Two Lines\nYou are tasked with writing a function to find the intersection point of two lines in a 2D plane. Each line is defined by two points. Implement a function `find_intersection_point(line1: Tuple[Tuple... |
def swap_pair(num: int) -> int:
even_mask = 0x55555555 # Binary: 0101 0101 0101 0101 0101 0101 0101 0101
odd_mask = 0xAAAAAAAA # Binary: 1010 1010 1010 1010 1010 1010 1010 1010
even_bits = num & even_mask
odd_bits = num & odd_mask
result = (even_bits << 1) | (odd_bits >> 1)
return result & 0x... | simplelr_Data_Structure | [
{
"content": "Question:\n### Bit Swapping Challenge\n\nYou are tasked with designing an algorithm to swap every pair of adjacent bits in a given non-negative integer. This means every odd-indexed bit will be swapped with the even-indexed bit next to it.\n\n#### Function Signature\n```python\ndef swap_pair(num: ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8402,
"level": 1,
"question": "### Bit Swapping Challenge\n\nYou are tasked with designing an algorithm to swap every pair of adjacent bits in a given non-negative integer. This means every odd-indexed bit will be swapped with the even-indexed bit next to it.\n\n#### Function Signat... |
def is_prime(n: int) -> bool:
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0:
return False
# Write n-1 as d * 2^s
d = n - 1
s = 0
while d % 2 == 0:
d //= 2
s += 1
# Deterministic bases for n < 2^64
bases = [2, 3, 5, 7, 11, 1... | simplelr_Data_Structure | [
{
"content": "Question:\n**Scenario:**\nYou have been asked to develop a component for a large-scale cryptographic application that involves frequent prime number validation to ensure the security and integrity of the system. The efficiency and correctness of your prime-checking algorithm are crucial as the sys... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8403,
"level": 1,
"question": "**Scenario:**\nYou have been asked to develop a component for a large-scale cryptographic application that involves frequent prime number validation to ensure the security and integrity of the system. The efficiency and correctness of your prime-checki... |
def filter_positive_numbers(arr):
return [num for num in arr if num > 0] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers (Both Positive and Negative) and returns a new array which contains all the positive numbers from the original array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8404,
"level": 1,
"question": "Create a function that takes an array of integers (Both Positive and Negative) and returns a new array which contains all the positive numbers from the original array.",
"split": "train"
} |
def unique_numbers(lst):
counts = {}
for num in lst:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
result = []
for num in lst:
if counts[num] == 1:
result.append(num)
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a python function to return the list of numbers that occur only once in a list of integers. The function should not use any inbuilt python library functions for removing duplicates.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8405,
"level": 1,
"question": "Write a python function to return the list of numbers that occur only once in a list of integers. The function should not use any inbuilt python library functions for removing duplicates.",
"split": "train"
} |
import heapq
def dijkstra(graph, start):
# Initialize distances to all nodes as infinity except the start node
distances = {node: float('infinity') for node in graph}
distances[start] = 0
# Priority queue: (distance, node)
heap = []
heapq.heappush(heap, (0, start))
while heap:
... | simplelr_Evol | [
{
"content": "Question:\nExplain and implement the Dijkstra's algorithm for finding the shortest path in a graph. Your answer should include:\n- An explanation of the algorithm's logic and workflow.\n- A detailed discussion on its time complexity.\n- A Python function illustrating its implementation.\n- An exam... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8406,
"level": 1,
"question": "Explain and implement the Dijkstra's algorithm for finding the shortest path in a graph. Your answer should include:\n- An explanation of the algorithm's logic and workflow.\n- A detailed discussion on its time complexity.\n- A Python function illustra... |
def counter(lst):
result = {}
for index, value in enumerate(lst):
if value in result:
result[value].append(index)
else:
result[value] = [index]
return result | simplelr_Filter | [
{
"content": "Question:\nGiven an input list, you are required to implement a function `counter` that returns a dictionary where the keys are the unique elements in the input list and the values are lists containing the indices at which these elements appear in the input list. Your solution should not rely on a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8407,
"level": 1,
"question": "Given an input list, you are required to implement a function `counter` that returns a dictionary where the keys are the unique elements in the input list and the values are lists containing the indices at which these elements appear in the input list.... |
def shortest_path(graph, start):
# Collect all nodes from the graph and its edges
all_nodes = set(graph.keys())
for node in graph:
for neighbor, _ in graph[node]:
all_nodes.add(neighbor)
# Initialize distances
distances = {node: float('inf') for node in all_nodes}
distan... | simplelr_Algorithm | [
{
"content": "Question:\n### Shortest Path in a Weighted Directed Graph\n\n#### Context\nYou are tasked with implementing an algorithm to find the shortest path from a given source node to all other nodes in a weighted directed graph. The graph is represented as an adjacency list, where each node has a list of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8408,
"level": 1,
"question": "### Shortest Path in a Weighted Directed Graph\n\n#### Context\nYou are tasked with implementing an algorithm to find the shortest path from a given source node to all other nodes in a weighted directed graph. The graph is represented as an adjacency l... |
def bubble_sort(arr):
sorted_arr = []
while arr:
min_val = arr[0]
min_index = 0
for i in range(1, len(arr)):
if arr[i] < min_val:
min_val = arr[i]
min_index = i
sorted_arr.append(arr.pop(min_index))
return sorted_arr | simplelr_Filter | [
{
"content": "Question:\nCreate a sorting algorithm from scratch that can sort an array of integers in ascending order. Additionally, the algorithm should be able to handle duplicate values in the array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8409,
"level": 1,
"question": "Create a sorting algorithm from scratch that can sort an array of integers in ascending order. Additionally, the algorithm should be able to handle duplicate values in the array.",
"split": "train"
} |
def sum_divisible_by(arr, n):
total = 0
for num in arr:
if num % n == 0:
total += num
return total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the sum of all integers in an array that are divisible by a given number n.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8410,
"level": 1,
"question": "Create a function that calculates the sum of all integers in an array that are divisible by a given number n.",
"split": "train"
} |
def count_strings(lst):
counts = {}
for string in lst:
counts[string] = counts.get(string, 0) + 1
return counts | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function that takes a list of strings and returns a dictionary where the keys are the unique strings and the values are the counts of those strings in the list?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8411,
"level": 1,
"question": "Can you provide a Python function that takes a list of strings and returns a dictionary where the keys are the unique strings and the values are the counts of those strings in the list?",
"split": "train"
} |
def longest_uncommon_subsequence(str1: str, str2: str) -> int:
if str1 == str2:
return -1
else:
return max(len(str1), len(str2)) | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Finding the Longest Uncommon Subsequence\n\n**Context**:\nAn uncommon subsequence between two strings is a subsequence that appears in one string but not in the other. Given two strings `str1` and `str2`, we want to find the length of the longest uncommon subsequence.\n\n*... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8412,
"level": 1,
"question": "### Question: Finding the Longest Uncommon Subsequence\n\n**Context**:\nAn uncommon subsequence between two strings is a subsequence that appears in one string but not in the other. Given two strings `str1` and `str2`, we want to find the length of the... |
def is_palindrome(s: str) -> bool:
left = 0
right = len(s) - 1
while left < right:
# Move left pointer to the next alphabetic character
while left < right and not s[left].isalpha():
left += 1
# Move right pointer to the previous alphabetic character
while lef... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n**Problem Statement**:\n\nYou are given a string of lowercase alphabets. Your task is to implement a function that checks if the string is a palindrome by comparing characters case-insensitively while ignoring any non-alphabetic characters.\n\n#### Function Signature:\n```... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8413,
"level": 1,
"question": "### Question\n**Problem Statement**:\n\nYou are given a string of lowercase alphabets. Your task is to implement a function that checks if the string is a palindrome by comparing characters case-insensitively while ignoring any non-alphabetic character... |
def find_max_average(arr, k):
n = len(arr)
if n == 0 or k == 0:
return 0 # Handle edge cases where array is empty or k is zero
current_sum = sum(arr[:k])
max_sum = current_sum
for i in range(k, n):
current_sum = current_sum - arr[i - k] + arr[i]
if current_sum > max_sum:
... | simplelr_Filter | [
{
"content": "Question:\nCreate an algorithm in Python to find the maximum average of a subarray of given length k.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8414,
"level": 1,
"question": "Create an algorithm in Python to find the maximum average of a subarray of given length k.",
"split": "train"
} |
def shift_letters(s):
shifted = []
for char in s:
if char.islower():
if char == 'z':
shifted.append('a')
else:
shifted.append(chr(ord(char) + 1))
elif char.isupper():
if char == 'Z':
shifted.append('A')
... | simplelr_Filter | [
{
"content": "Question:\nDesign a program that takes a string as input and returns a new string where each character has been replaced with the character that follows it in the alphabet.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8415,
"level": 1,
"question": "Design a program that takes a string as input and returns a new string where each character has been replaced with the character that follows it in the alphabet.",
"split": "train"
} |
def remove_duplicates(arr):
seen = set()
result = []
for num in arr:
if num not in seen:
seen.add(num)
result.append(num)
return result
# Example usage:
# input_array = [3, 4, 5, 3, 6, 7, 4]
# output = remove_duplicates(input_array)
# print(output) # Output: [3, 4, 5, 6... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that accepts an array of integers and returns a new array with all the duplicates removed while maintaining the original order. For example, given the input array [3, 4, 5, 3, 6, 7, 4], the program should return [3, 4, 5, 6, 7].\nAnswer:\nLet's think step by step.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8416,
"level": 1,
"question": "Write a Python program that accepts an array of integers and returns a new array with all the duplicates removed while maintaining the original order. For example, given the input array [3, 4, 5, 3, 6, 7, 4], the program should return [3, 4, 5, 6, 7]."... |
import math
def generate_primes(upper_limit: int) -> list[int]:
if upper_limit < 2:
return []
is_prime = [True] * (upper_limit + 1)
is_prime[0], is_prime[1] = False, False
sqrt_limit = int(math.sqrt(upper_limit))
for p in range(2, sqrt_limit + 1):
if is_prime[p]:
for mul... | simplelr_Algorithm | [
{
"content": "Question:\n## Problem: Efficient Prime Number Generation Using the Sieve of Eratosthenes\n\n### Scenario\nYou are required to develop an efficient tool for generating a list of prime numbers within a given range. The tool should utilize the Sieve of Eratosthenes algorithm to optimize performance, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8417,
"level": 1,
"question": "## Problem: Efficient Prime Number Generation Using the Sieve of Eratosthenes\n\n### Scenario\nYou are required to develop an efficient tool for generating a list of prime numbers within a given range. The tool should utilize the Sieve of Eratosthenes ... |
def square_elements_of_tuples(tuples_list):
return [tuple(x ** 2 for x in t) for t in tuples_list] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of tuples as input and returns a list of tuples with each element of the inner tuples squared. For example, if the input is `[(1, 2), (3, 4), (5, 6)]`, the output should be `[(1, 4), (9, 16), (25, 36)]`.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8418,
"level": 1,
"question": "Write a Python function that takes a list of tuples as input and returns a list of tuples with each element of the inner tuples squared. For example, if the input is `[(1, 2), (3, 4), (5, 6)]`, the output should be `[(1, 4), (9, 16), (25, 36)]`.",
"s... |
def bubble_sort_descending(arr):
arr = arr.copy() # Create a copy to avoid modifying the original list
n = len(arr)
for i in range(n):
for j in range(n - i - 1):
if arr[j] < arr[j + 1]:
# Swap elements
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return ar... | simplelr_Filter | [
{
"content": "Question:\nImplement a function to sort a list of positive numbers in descending order using Bubble sort.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8419,
"level": 1,
"question": "Implement a function to sort a list of positive numbers in descending order using Bubble sort.",
"split": "train"
} |
import string
def count_unique_words(filename):
try:
with open(filename, 'r') as file:
text = file.read()
except FileNotFoundError:
print(f"The file {filename} does not exist.")
return 0
words = text.split()
unique_words = set()
for word in words:
... | simplelr_Filter | [
{
"content": "Question:\nI have a text file containing multiple sentences. How can I read this file and count the number of unique words in it using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8420,
"level": 1,
"question": "I have a text file containing multiple sentences. How can I read this file and count the number of unique words in it using Python?",
"split": "train"
} |
from typing import List
def move_zeros(arr: List) -> List:
non_zeros = []
zeros = []
for elem in arr:
if isinstance(elem, int) and not isinstance(elem, bool) and elem == 0:
zeros.append(elem)
else:
non_zeros.append(elem)
return non_zeros + zeros | simplelr_Data_Structure | [
{
"content": "Question:\nYou are working on a data preprocessing system where you need to modify lists containing various elements while standardizing data representation. One common task is to move all zeros to the end of the list, keeping the order of other elements intact. A zero is defined as the integer 0 ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8421,
"level": 1,
"question": "You are working on a data preprocessing system where you need to modify lists containing various elements while standardizing data representation. One common task is to move all zeros to the end of the list, keeping the order of other elements intact. ... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
def apply_pca(X):
"""
Apply PCA to reduce dimensionality of the dataset and visualize it in 2D.
Args:
X (numpy array): Input dataset of shape (n_samples, n_features... | simplelr_Docs | [
{
"content": "Question:\n**Problem Statement:**\n\nYou are given a dataset that consists of images of handwritten digits. Your task is to apply Principal Component Analysis (PCA) to reduce the dimensionality of the dataset and visualize the dataset in 2D. You will also identify the number of components that cap... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8422,
"level": 1,
"question": "**Problem Statement:**\n\nYou are given a dataset that consists of images of handwritten digits. Your task is to apply Principal Component Analysis (PCA) to reduce the dimensionality of the dataset and visualize the dataset in 2D. You will also identif... |
def find_two_sum(nums, target):
seen = {}
for x in nums:
complement = target - x
if complement in seen:
return [complement, x]
seen[x] = True
return [] | simplelr_Filter | [
{
"content": "Question:\nHere is a problem and an algorithm to solve it.\n\n**Problem:** Find the two elements in an array that add up to a given target.\n\n**Example:** \n\nInputs: `nums = [2, 7, 11, 15]` and `target = 9` Outputs: `[2, 7]`\n\n**Algorithm:** \n\n1. Create an empty hashmap `m` to store the eleme... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8423,
"level": 1,
"question": "Here is a problem and an algorithm to solve it.\n\n**Problem:** Find the two elements in an array that add up to a given target.\n\n**Example:** \n\nInputs: `nums = [2, 7, 11, 15]` and `target = 9` Outputs: `[2, 7]`\n\n**Algorithm:** \n\n1. Create an e... |
def frequency_count(lst):
freq = {}
for num in lst:
freq[num] = freq.get(num, 0) + 1
return freq | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts a list of integers. The function should return a dictionary that includes the frequency of each element in the list. If the integer appears more than once, the dictionary should store how many times it appears. If it appears only once, the dictionary shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8424,
"level": 1,
"question": "Create a function that accepts a list of integers. The function should return a dictionary that includes the frequency of each element in the list. If the integer appears more than once, the dictionary should store how many times it appears. If it appe... |
from typing import List
def summarize_ranges(array: List[int]) -> List[str]:
if not array:
return []
result = []
current_start = array[0]
current_end = array[0]
for i in range(1, len(array)):
if array[i] == current_end + 1:
current_end = array[i]
else:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem Context\nYou are working on a system that processes event logs. The logs are represented as integer timestamps in a list and they are sorted in ascending order. Two events are considered to be consecutive if their timestamps differ by exactly one. Your task is to summarize t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8425,
"level": 1,
"question": "### Problem Context\nYou are working on a system that processes event logs. The logs are represented as integer timestamps in a list and they are sorted in ascending order. Two events are considered to be consecutive if their timestamps differ by exact... |
def total_sum(lst):
"""
This function calculates and returns the total sum of all elements in a given list.
Args:
lst (list): A list of numeric elements.
Returns:
int or float: The sum of all elements in the list.
"""
return sum(lst) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to return the total sum of all elements in a list. The function should take the list as an argument and return the sum of its elements.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8426,
"level": 1,
"question": "Write a python function to return the total sum of all elements in a list. The function should take the list as an argument and return the sum of its elements.",
"split": "train"
} |
def max_subarray(nums):
max_so_far = float('-inf')
current_sum = 0
current_start = 0
max_start = 0
max_end = 0
for i in range(len(nums)):
current_sum += nums[i]
if current_sum > max_so_far:
max_so_far = current_sum
max_start = current_start
... | simplelr_Filter | [
{
"content": "Question:\nHere is the problem: \nGiven an array of integers, find the subarray with the largest sum. \n\nExample 1:\nInput: nums = [-2,1,-3,4,-1,2,1,-5,4]\nOutput: [4,-1,2,1]\nExplanation: [4,-1,2,1] has the largest sum 6.\n\nExample 2:\nInput: nums = [1]\nOutput: [1]\nExplanation: [1] has the la... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8427,
"level": 1,
"question": "Here is the problem: \nGiven an array of integers, find the subarray with the largest sum. \n\nExample 1:\nInput: nums = [-2,1,-3,4,-1,2,1,-5,4]\nOutput: [4,-1,2,1]\nExplanation: [4,-1,2,1] has the largest sum 6.\n\nExample 2:\nInput: nums = [1]\nOutpu... |
def canArrange(nums, k):
n = len(nums)
if n % 2 != 0:
return False
remainder = [num % k for num in nums]
freq = {}
for r in remainder:
if r in freq:
freq[r] += 1
else:
freq[r] = 1
for r in freq:
if r == 0:
if freq[r] % 2 != 0:
... | simplelr_Apps | [
{
"content": "Question:\nGiven an integer array nums and an integer k, return true if it is possible to divide this array into pairs of ints such that the sum of each pair is divisible by k, else return false.\n\nExample 1:\nInput: nums = [1,2,3,4,5,10,6,7,8,9], k = 5\nOutput: true\nExplanation: Pairs that can ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8428,
"level": 1,
"question": "Given an integer array nums and an integer k, return true if it is possible to divide this array into pairs of ints such that the sum of each pair is divisible by k, else return false.\n\nExample 1:\nInput: nums = [1,2,3,4,5,10,6,7,8,9], k = 5\nOutput:... |
def is_strong_password(password):
# Check if password is at least 8 characters long
if len(password) < 8:
return False
# Check if password contains any spaces
if ' ' in password:
return False
# Check for at least one lowercase letter
has_lower = any(c.islower() for c in... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to check if a given string is a strong password. A strong password should contain at least one lowercase letter, one uppercase letter, one digit, and one special character. Additionally, it should be at least 8 characters long and not contain any spaces.\nAnswer:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8429,
"level": 1,
"question": "Write a Python function to check if a given string is a strong password. A strong password should contain at least one lowercase letter, one uppercase letter, one digit, and one special character. Additionally, it should be at least 8 characters long a... |
def are_antonyms(word1, word2, antonyms_dict):
if word1 in antonyms_dict and word2 in antonyms_dict[word1]:
return True
if word2 in antonyms_dict and word1 in antonyms_dict[word2]:
return True
return False | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to check if two words are antonyms. To simplify the problem, we assume that the antonyms are predefined in a dictionary. This dictionary will be given as input to the function. The function should take three arguments: the first two are the words to be checked, a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8430,
"level": 1,
"question": "Write a Python function to check if two words are antonyms. To simplify the problem, we assume that the antonyms are predefined in a dictionary. This dictionary will be given as input to the function. The function should take three arguments: the first... |
def max_subarray_sum(arr):
if not arr:
return 0
current_max = max_sum = arr[0]
for i in range(1, len(arr)):
current_max = max(arr[i], current_max + arr[i])
if current_max > max_sum:
max_sum = current_max
return max_sum | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr`, your task is to find a **contiguous subarray** with the **maximum sum** and return that sum. A subarray is a slice of the array that maintains the order of the elements. If all numbers are negative, the maximum sum is the smallest negative number. The s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8431,
"level": 1,
"question": "Given an array of integers `arr`, your task is to find a **contiguous subarray** with the **maximum sum** and return that sum. A subarray is a slice of the array that maintains the order of the elements. If all numbers are negative, the maximum sum is ... |
def min_subarray_len(nums, goal):
min_length = float('inf')
current_sum = 0
left = 0
for right in range(len(nums)):
current_sum += nums[right]
# Slide the window if current sum exceeds the goal
while current_sum > goal and left <= right:
current_sum -= nums[l... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a `nums` array of size `n` containing non-negative integers. You are also given a positive integer `goal`. You need to find the minimum length of a contiguous subarray such that the sum of its elements is **exactly** equal to `goal`. If there is no such subarray, return `-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8432,
"level": 1,
"question": "You are given a `nums` array of size `n` containing non-negative integers. You are also given a positive integer `goal`. You need to find the minimum length of a contiguous subarray such that the sum of its elements is **exactly** equal to `goal`. If t... |
def min_word_partitions(s, wordDict):
if not s:
return 0
if not wordDict:
return -1
L = len(wordDict[0])
n = len(s)
if n % L != 0:
return -1
word_set = set(wordDict)
dp = [float('inf')] * (n + 1)
dp[0] = 0 # Base case: empty string requires 0 parti... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` and a list of strings `wordDict` where all the words are of the same length. The string `s` can be partitioned into one or more non-overlapping substrings, each of which is in `wordDict`. Return _the **minimum number of any partitions** such that each substrin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8433,
"level": 1,
"question": "You are given a string `s` and a list of strings `wordDict` where all the words are of the same length. The string `s` can be partitioned into one or more non-overlapping substrings, each of which is in `wordDict`. Return _the **minimum number of any p... |
def topKFrequent(nums):
count = {}
for num in nums:
if num not in count:
count[num] = 0
count[num] += 1
# Create bucket array where index represents frequency
bucket = [[] for _ in range(len(nums) + 1)]
# Distribute elements into their respective buckets
for nu... | simplelr_Filter | [
{
"content": "Question:\nIn this problem, you will implement a top k frequency sort approach to sort elements in an array.\nGiven the input array [1,1,1,2,2,3], we should return [[1, 3], [2,2], [3,1]] because 1 occurs three times, 2 occurs twice and 3 occurs once. \nThis is similar to a priority queue approach.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8434,
"level": 1,
"question": "In this problem, you will implement a top k frequency sort approach to sort elements in an array.\nGiven the input array [1,1,1,2,2,3], we should return [[1, 3], [2,2], [3,1]] because 1 occurs three times, 2 occurs twice and 3 occurs once. \nThis is si... |
def max_subarray_sum_with_min_length_2(nums):
if len(nums) < 2:
return None # Not expected as per problem statement
max_current = nums[0] + nums[1]
max_global = max_current
for i in range(2, len(nums)):
temp = max(max_current + nums[i], nums[i-1] + nums[i])
max_current = temp
... | simplelr_Filter | [
{
"content": "Question:\nWhat is Python code to determine the maximum sum of a subarray with at least two elements in a given list of integers? Could you also provide an example using the input list [3, -2, 5, -1]?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8435,
"level": 1,
"question": "What is Python code to determine the maximum sum of a subarray with at least two elements in a given list of integers? Could you also provide an example using the input list [3, -2, 5, -1]?",
"split": "train"
} |
def find_longest_substring(string: str) -> tuple[int, str]:
"""
This function finds the length of the longest substring without repeating characters
and returns the longest substring itself.
Args:
string (str): The input string containing lowercase alphabets.
Returns:
tuple[int, st... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a string containing only lowercase alphabets. Your task is to write a function that finds the length of the longest substring without repeating characters and also returns the longest substring itself.\n\n### Function Signature\n```python\ndef find_longest_substring(string... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8436,
"level": 1,
"question": "You are given a string containing only lowercase alphabets. Your task is to write a function that finds the length of the longest substring without repeating characters and also returns the longest substring itself.\n\n### Function Signature\n```python... |
def find_substring(main_str, sub_str):
if len(sub_str) == 0:
return 0
if len(main_str) < len(sub_str):
return -1
sub_len = len(sub_str)
for i in range(len(main_str) - sub_len + 1):
if main_str[i:i+sub_len] == sub_str:
return i
return -1 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that will search for a specific substring within a given string. The function should return the starting index of the first occurrence of the substring or -1 if the substring is not found.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8437,
"level": 1,
"question": "Create a function that will search for a specific substring within a given string. The function should return the starting index of the first occurrence of the substring or -1 if the substring is not found.",
"split": "train"
} |
def square(num):
return num ** 2 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that can handle both integer and float inputs and return the square of the input.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8438,
"level": 1,
"question": "Create a function that can handle both integer and float inputs and return the square of the input.",
"split": "train"
} |
def calculate_shopping_cart(cart):
subtotal = 0.0
for item in cart:
name, quantity, price = item
subtotal += quantity * price
if subtotal < 50:
discount_rate = 0
elif 50 <= subtotal <= 100:
discount_rate = 0.05
else:
discount_rate = 0.10
discount = subtota... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function named `calculate_shopping_cart` that calculates the total price of items in a shopping cart, including a variable discount. This function should:\n\n1. Accept a single parameter `cart`, which is a list of tuples. Each tuple contains the item name,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8439,
"level": 1,
"question": "You are tasked with creating a function named `calculate_shopping_cart` that calculates the total price of items in a shopping cart, including a variable discount. This function should:\n\n1. Accept a single parameter `cart`, which is a list of tuples.... |
from typing import List, Tuple
def usage_statistics(usages: List[float]) -> Tuple[float, float, float]:
max_val = max(usages)
min_val = min(usages)
average = sum(usages) / len(usages)
rounded_average = round(average, 2)
return (max_val, min_val, rounded_average) | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context\nYou are working on a project that involves monitoring system resources, and your task is to analyze and process a list of usage percentages to derive key statistics.\n\n#### Problem Statement\nGiven a list of CPU utilization percentages re... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8440,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context\nYou are working on a project that involves monitoring system resources, and your task is to analyze and process a list of usage percentages to derive key statistics.\n\n#### Problem Statement\nGiven a lis... |
def roman_to_int(s: str) -> int:
roman_values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
for i in range(len(s)):
current = roman_values[s[i]]
if i < len(s) - 1 and current < roman_values[s[i + 1]]:
total -= current
else:
tota... | simplelr_Data_Structure | [
{
"content": "Question:\n### Roman to Integer Conversion Challenge\n\n**Problem Description:**\n\nGiven a string `s` representing a Roman numeral, write a function `roman_to_int(s: str) -> int` that converts this numeral to its integer value. The input string is guaranteed to be within the range from 1 to 3999.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8441,
"level": 1,
"question": "### Roman to Integer Conversion Challenge\n\n**Problem Description:**\n\nGiven a string `s` representing a Roman numeral, write a function `roman_to_int(s: str) -> int` that converts this numeral to its integer value. The input string is guaranteed to ... |
from collections import deque
def reverse_string_deque(s):
dq = deque()
for char in s:
dq.appendleft(char)
return ''.join(dq) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse a string using a deque.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8442,
"level": 1,
"question": "Write a function to reverse a string using a deque.",
"split": "train"
} |
import matplotlib.pyplot as plt
import pandas as pd
def analyze_scores(students):
# Step 1: Print students and their respective scores
print("##### STUDENT SCORES #####")
for index, row in students.iterrows():
print(f'{row["STUDENT"]}: Math={row["Mathematics"]}, Physics={row["Physics"]}, Chemistry=... | simplelr_Package | [
{
"content": "Question:\n**\n\nYou are given a dataset of student information and their respective scores in three subjects: Mathematics, Physics, and Chemistry. Your task is to write a Python function that performs the following tasks:\n\n1. Print a list of students with their respective scores.\n2. Compute an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8443,
"level": 1,
"question": "**\n\nYou are given a dataset of student information and their respective scores in three subjects: Mathematics, Physics, and Chemistry. Your task is to write a Python function that performs the following tasks:\n\n1. Print a list of students with thei... |
def compress_string(s: str) -> str:
if not s:
return s
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(f"{current_char}{count}")
current_char = char
count = 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### String Compression\n\nYou are tasked with implementing a string compression algorithm that reads a string and outputs its compressed version. The compressed string will replace sequences of repeated characters with a single character followed by the count of repeated characters. If ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8444,
"level": 1,
"question": "### String Compression\n\nYou are tasked with implementing a string compression algorithm that reads a string and outputs its compressed version. The compressed string will replace sequences of repeated characters with a single character followed by th... |
def rectangular_prism_volume(length, width, height):
"""
Calculate the volume of a rectangular prism given its dimensions.
Parameters:
length (float): The length of the prism.
width (float): The width of the prism.
height (float): The height of the prism.
Returns:
float: The vo... | simplelr_Filter | [
{
"content": "Question:\n### Goal\nThe goal is to design a function `rectangular_prism_volume` that calculates the volume of a rectangular prism given its dimensions.\nThe function should accept three parameters: length, width, and height. All parameters should be floating-point numbers.\n\n### Constraints\n- T... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8445,
"level": 1,
"question": "### Goal\nThe goal is to design a function `rectangular_prism_volume` that calculates the volume of a rectangular prism given its dimensions.\nThe function should accept three parameters: length, width, and height. All parameters should be floating-poi... |
from collections import deque
def course_schedule(numCourses: int, prerequisites: list) -> list:
adj = [[] for _ in range(numCourses)]
in_degree = [0] * numCourses
for a, b in prerequisites:
adj[b].append(a)
in_degree[a] += 1
queue = deque()
for i in range(numCourses):
if ... | simplelr_Algorithm | [
{
"content": "Question:\nCourse Scheduling Using Topological Sort\n\nYou are given a list of course prerequisites represented as pairs of courses, where the second course in the pair is a prerequisite for the first course. Your task is to find an order for taking all the courses such that all prerequisite cours... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8446,
"level": 1,
"question": "Course Scheduling Using Topological Sort\n\nYou are given a list of course prerequisites represented as pairs of courses, where the second course in the pair is a prerequisite for the first course. Your task is to find an order for taking all the cours... |
def is_rotated(s1: str, s2: str) -> bool:
return s2 in (s1 + s1) | simplelr_Data_Structure | [
{
"content": "Question:\n### Rotated String Check\n\nYou are given two strings `s1` and `s2`. Your task is to determine if `s2` is a rotation of `s1`. A string rotation involves shifting the characters of a string to the left or the right to form another string. For example, \"abcde\" shifted left by 2 characte... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8447,
"level": 1,
"question": "### Rotated String Check\n\nYou are given two strings `s1` and `s2`. Your task is to determine if `s2` is a rotation of `s1`. A string rotation involves shifting the characters of a string to the left or the right to form another string. For example, \... |
def min_distance(houses):
total = 0
for i in range(1, len(houses)):
total += abs(houses[i] - houses[i-1])
return total | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to compute the minimum distance a robot needs to travel to visit all the houses on a street. The street is represented as a list of integers where each integer represents the house number, and the robot starts at the first house in the list. The robot can move to the ne... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8448,
"level": 1,
"question": "Write a function to compute the minimum distance a robot needs to travel to visit all the houses on a street. The street is represented as a list of integers where each integer represents the house number, and the robot starts at the first house in the... |
import heapq
def find_shortest_paths(start_location: str, city_map: dict) -> dict:
# Initialize distances dictionary with infinity
dist = {node: float('infinity') for node in city_map}
dist[start_location] = 0 # Starting point has distance 0
# Priority queue (heap) to process nodes by shortest distan... | simplelr_Algorithm | [
{
"content": "Question:\n**Optimizing Delivery Routes Using Dijkstra's Algorithm**\n\nYou are tasked with finding the shortest delivery route in a city represented as a weighted graph. Given a dataset of locations (nodes) and the distances (weights) between them, use Dijkstra's algorithm to determine the minimu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8449,
"level": 1,
"question": "**Optimizing Delivery Routes Using Dijkstra's Algorithm**\n\nYou are tasked with finding the shortest delivery route in a city represented as a weighted graph. Given a dataset of locations (nodes) and the distances (weights) between them, use Dijkstra'... |
def max_subarray_sum(arr):
if not arr:
return 0
current_max = global_max = arr[0]
for num in arr[1:]:
current_max = max(num, current_max + num)
if current_max > global_max:
global_max = current_max
return global_max | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers and returns the maximum sum of a contiguous subarray. This function will be used in a real-world scenario where we need to find the most profitable period from a stream of daily profit data. Can you provide a function for this?\nAnswer:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8450,
"level": 1,
"question": "Create a function that takes an array of integers and returns the maximum sum of a contiguous subarray. This function will be used in a real-world scenario where we need to find the most profitable period from a stream of daily profit data. Can you pro... |
from typing import List
def fibonacci_modulo(n: int, mod: int) -> List[int]:
if n == 0:
return [0]
elif n == 1:
return [0, 1]
fib_sequence = [0, 1]
prev_prev = 0
prev = 1
for i in range(2, n + 1):
current = (prev + prev_prev) % mod
fib_sequence.append(c... | simplelr_Algorithm | [
{
"content": "Question:\n### Fibonacci Sequence Modulo \n\nYou are tasked with implementing a function that computes the Fibonacci sequence modulo a given number `mod` for the first `n` terms. This function computes the Fibonacci numbers where each number is defined by the recurrence relation:\n\n\\[ F(0) = 0 \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8451,
"level": 1,
"question": "### Fibonacci Sequence Modulo \n\nYou are tasked with implementing a function that computes the Fibonacci sequence modulo a given number `mod` for the first `n` terms. This function computes the Fibonacci numbers where each number is defined by the rec... |
import math
def euclidean_distance(point1, point2):
dx = point2[0] - point1[0]
dy = point2[1] - point1[1]
return math.sqrt(dx**2 + dy**2) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code snippet that defines a function to calculate the Euclidean distance between two points in a 2D space.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8452,
"level": 1,
"question": "Write a Python code snippet that defines a function to calculate the Euclidean distance between two points in a 2D space.",
"split": "train"
} |
def make_drink(fruit_juice, sparkling_water):
"""
This function takes the amount of fruit juice and sparkling water as input and returns a list containing the ingredients and their respective amounts.
Args:
fruit_juice (float): The amount of fruit juice in cups.
sparkling_water (float): The... | simplelr_Filter | [
{
"content": "Question:\nThe following text describes a process for making a drink:\n\n\"Take 1 cup of fruit juice and 1/2 cup of sparkling water. Combine them in a glass and stir. Add ice cubes to the desired amount.\"\n\nWrite a Python function that takes the amount of fruit juice and sparkling water as input... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8453,
"level": 1,
"question": "The following text describes a process for making a drink:\n\n\"Take 1 cup of fruit juice and 1/2 cup of sparkling water. Combine them in a glass and stir. Add ice cubes to the desired amount.\"\n\nWrite a Python function that takes the amount of fruit... |
def find_primes(n):
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(n ** 0.5) + 1):
if sieve[i]:
sieve[i*i : n+1 : i] = [False] * len(sieve[i*i : n+1 : i])
return [i for i, is_prime in enumerate(sieve) if is_prime]
| simplelr_Taco | [
{
"content": "Question:\nCreate a function that takes an integer `n` and returns a list of all prime numbers less than or equal to `n`.\n\nThe function should be optimized to handle larger values of `n` efficiently. You should avoid brute-force methods like checking every single number up to `n` for primality.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8454,
"level": 1,
"question": "Create a function that takes an integer `n` and returns a list of all prime numbers less than or equal to `n`.\n\nThe function should be optimized to handle larger values of `n` efficiently. You should avoid brute-force methods like checking every sing... |
from collections import Counter
def can_form_palindrome(s):
s_processed = s.replace(' ', '').lower()
counts = Counter(s_processed)
odd_counts = 0
for c in counts.values():
if c % 2 != 0:
odd_counts += 1
return 1 if odd_counts <= 1 else 0 | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function that takes in a string and determines if it can be rearranged into a palindrome. A palindrome is a word or phrase that reads the same backward as forward (ignoring spaces, punctuation, and capitalization).\n\n### Input\n- A single string `s` (1 ≤ |s| ≤ 10^5). The string... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8455,
"level": 1,
"question": "Write a function that takes in a string and determines if it can be rearranged into a palindrome. A palindrome is a word or phrase that reads the same backward as forward (ignoring spaces, punctuation, and capitalization).\n\n### Input\n- A single stri... |
def divisible_by_n(arr, n):
if n == 0:
return [-1]
result = []
for num in arr:
if num % n == 0:
result.append(num)
return result if result else [-1] | simplelr_Evol | [
{
"content": "Question:\nWrite a function that receives an integer array and an integer value 'n'. The function should return an array containing elements from the input array that are divisible by 'n'. If no such elements exist, return an array with a single element, -1.\nAnswer:\nLet's think step by step.\n",... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8456,
"level": 1,
"question": "Write a function that receives an integer array and an integer value 'n'. The function should return an array containing elements from the input array that are divisible by 'n'. If no such elements exist, return an array with a single element, -1.",
... |
def filter_and_square_odd_numbers(arr):
"""
This function filters out even numbers from the input array and returns a new list containing the squares of the remaining odd numbers.
Args:
arr (list): A list of integers.
Returns:
list: A list of squares of the odd numbers from the input a... | simplelr_Filter | [
{
"content": "Question:\nI have an array of numbers and I want to filter out the even numbers, then square the remaining numbers. How can I do this in Python? Could you please provide a function that performs this task?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8457,
"level": 1,
"question": "I have an array of numbers and I want to filter out the even numbers, then square the remaining numbers. How can I do this in Python? Could you please provide a function that performs this task?",
"split": "train"
} |
def find_missing_elements(arr: list[int], range_start: int, range_end: int) -> list[int]:
present = set(arr)
missing = []
for num in range(range_start, range_end + 1):
if num not in present:
missing.append(num)
return missing | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Find Missing Elements in Range\n\nYou have recently joined a tech company as a software developer. One of your projects involves working with a range of integers for data processing. Your task is to identify any missing integers within a specific range that are not present... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8458,
"level": 1,
"question": "### Question: Find Missing Elements in Range\n\nYou have recently joined a tech company as a software developer. One of your projects involves working with a range of integers for data processing. Your task is to identify any missing integers within a ... |
def bellman_ford(graph, source):
if not graph:
return True # An empty graph has no cycles
nodes = graph.keys()
V = len(nodes)
infinity = float('inf')
distance = {node: infinity for node in graph}
distance[source] = 0
for _ in range(V - 1):
for u in graph:
... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nYou've been hired as a consultant for a city's traffic management system. The city has a complex road network with roads that can have varying travel times, including roadworks that might introduce negative travel times. You need to develop a system that can assess whethe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8459,
"level": 1,
"question": "#### Scenario\nYou've been hired as a consultant for a city's traffic management system. The city has a complex road network with roads that can have varying travel times, including roadworks that might introduce negative travel times. You need to deve... |
def longest_unique_substring(s: str, k: int) -> int:
n = len(s)
if k == 0 or k > n:
return -1
freq = [0] * 26
unique_count = 0
# Initialize the first window
for i in range(k):
c = s[i]
idx = ord(c) - ord('a')
if freq[idx] == 0:
unique_count +... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Non-repeating Characters in a Substring\n\nYou are given a string `s` and an integer `k`. Write a Python function to find the length of the longest substring with all unique characters that is exactly `k` consecutive characters long. If there is no such substring, return `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8460,
"level": 1,
"question": "### Question: Non-repeating Characters in a Substring\n\nYou are given a string `s` and an integer `k`. Write a Python function to find the length of the longest substring with all unique characters that is exactly `k` consecutive characters long. If t... |
def reverse_dict(original_dict):
reversed_dict = {}
for key, value in original_dict.items():
if value not in reversed_dict:
reversed_dict[value] = key
else:
if isinstance(reversed_dict[value], list):
reversed_dict[value].append(key)
else:
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that reverses the keys and values of a given dictionary, handling potential collisions by storing the values in a list. If the dictionary is empty, return an empty dictionary.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8461,
"level": 1,
"question": "Write a Python program that reverses the keys and values of a given dictionary, handling potential collisions by storing the values in a list. If the dictionary is empty, return an empty dictionary.",
"split": "train"
} |
def remove_duplicates(input_list):
result = []
for item in input_list:
if item not in result:
result.append(item)
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a code to remove the duplicates from a given list without using any built-in functions or data structures such as sets or dictionaries. The input list can contain any type of elements, including nested lists, and the order of the elements should be preserved in the output.\nAnswer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8462,
"level": 1,
"question": "Write a code to remove the duplicates from a given list without using any built-in functions or data structures such as sets or dictionaries. The input list can contain any type of elements, including nested lists, and the order of the elements should ... |
def find_index(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return low
| simplelr_Taco | [
{
"content": "Question:\nGiven a sorted array of distinct integers, return the lowest index at which a given target value can be inserted to maintain the sorted order.\n\nNote:\n\n- The array will be non-empty.\n- The returned index value should not exceed the length of the array.\n\nExample:\n\nInput:\n array... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8463,
"level": 1,
"question": "Given a sorted array of distinct integers, return the lowest index at which a given target value can be inserted to maintain the sorted order.\n\nNote:\n\n- The array will be non-empty.\n- The returned index value should not exceed the length of the ar... |
from collections import Counter
def top_k_frequent(arr, k):
if k == 0:
return []
counts = Counter(arr)
elements = list(counts.items())
sorted_elements = sorted(elements, key=lambda x: (-x[1], x[0]))
top_k = sorted_elements[:k]
result = [x[0] for x in top_k]
return result | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers `arr` and an integer `k`. Write a function to find the `k` most frequent elements in the list. Return the elements as an array in any order. If there are multiple elements with the same frequency, return the ones with the smaller values first.\n\n* For e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8464,
"level": 1,
"question": "You are given a list of integers `arr` and an integer `k`. Write a function to find the `k` most frequent elements in the list. Return the elements as an array in any order. If there are multiple elements with the same frequency, return the ones with t... |
from typing import List
def merge_cat_ids(N: int, M: int, existing_ids: List[int], new_ids: List[int]) -> List[int]:
i = j = 0
merged = []
while i < N and j < M:
if existing_ids[i] <= new_ids[j]:
merged.append(existing_ids[i])
i += 1
else:
merged.append(n... | simplelr_Taco | [
{
"content": "Question:\nAn international cat adoption agency keeps track of the cats in their inventory using an array. Each cat has a unique ID and the array is sorted in ascending order of these IDs. Occasionally, the agency receives a batch of new cats all at once, and they need to merge this new batch (als... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8465,
"level": 1,
"question": "An international cat adoption agency keeps track of the cats in their inventory using an array. Each cat has a unique ID and the array is sorted in ascending order of these IDs. Occasionally, the agency receives a batch of new cats all at once, and the... |
def alternate_strings(s1, s2):
result = []
max_length = max(len(s1), len(s2))
for i in range(max_length):
if i < len(s1):
result.append(s1[i])
if i < len(s2):
result.append(s2[i])
return ''.join(result) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in two strings and returns a new string that is the result of alternating characters from the two input strings. If one string is longer than the other, append the remaining characters of the longer string to the result.\nAnswer:\nLet's think step by step.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8466,
"level": 1,
"question": "Create a function that takes in two strings and returns a new string that is the result of alternating characters from the two input strings. If one string is longer than the other, append the remaining characters of the longer string to the result.",
... |
def check_query(query, words):
query_words = query.split()
for word in words:
if word not in query_words:
return False
return True | simplelr_Filter | [
{
"content": "Question:\nHow do I define a function that takes a query string, a list of acceptable words, and returns true if the query string contains all the words in the list. \nFor example, \n- query string = \"hello world\"\n- list of words = [\"hello\", \"world\"]\n- result = true\n\n- query string = \"h... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8467,
"level": 1,
"question": "How do I define a function that takes a query string, a list of acceptable words, and returns true if the query string contains all the words in the list. \nFor example, \n- query string = \"hello world\"\n- list of words = [\"hello\", \"world\"]\n- re... |
def print_sequence(n):
if n < 1:
print("Input must be at least 1")
return
elif n > 100:
print("Input must be at most 100")
return
else:
for i in range(1, n + 1):
if i % 15 == 0:
print("BuzzFuzz")
elif i % 3 == 0:
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes an integer `n` as input and prints a sequence of numbers from 1 to `n` (inclusive). If `n` is less than 1, the function should print \"Input must be at least 1\". If `n` is greater than 100, the function should print \"Input must be at most 100\". Addi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8468,
"level": 1,
"question": "Write a Python function that takes an integer `n` as input and prints a sequence of numbers from 1 to `n` (inclusive). If `n` is less than 1, the function should print \"Input must be at least 1\". If `n` is greater than 100, the function should print ... |
def is_power_of_two(n):
if n <= 0:
return False
return (n & (n - 1)) == 0 | simplelr_Data_Structure | [
{
"content": "Question:\n### Power of Two Check\n\n#### Background:\nAn important property of numbers in binary systems is their representation of powers of two. Numbers like 1, 2, 4, 8, etc., are powers of two. Your task is to design a function capable of determining whether a given integer is a power of two u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8469,
"level": 1,
"question": "### Power of Two Check\n\n#### Background:\nAn important property of numbers in binary systems is their representation of powers of two. Numbers like 1, 2, 4, 8, etc., are powers of two. Your task is to design a function capable of determining whether ... |
from typing import List
def largest_rectangle_area(heights: List[int]) -> int:
stack = [-1] # Initialize stack with base index
max_area = 0
n = len(heights)
for i in range(n):
# Pop from stack while the current height is less than the stack's top height
while stack[-1] != -1 and h... | simplelr_Apps | [
{
"content": "Question:\nYou are given a list of integers, where each integer represents the height of a bar. The width of each bar is 1. Write a function that takes the list as input and returns an integer representing the largest rectangle that can be formed in a histogram using the bars.\n\nTo clarify, each ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8470,
"level": 1,
"question": "You are given a list of integers, where each integer represents the height of a bar. The width of each bar is 1. Write a function that takes the list as input and returns an integer representing the largest rectangle that can be formed in a histogram u... |
def filter_long_strings(strings, n):
return [s for s in strings if len(s) >= n] | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes an array of strings and an integer `n` as input, and returns a new array containing only the strings whose lengths are greater than or equal to `n`.\n\n### Example\n```python\nfilter_long_strings([\"apple\", \"bat\", \"car\", \"doghouse\"], 4) ==> [\"apple\"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8471,
"level": 1,
"question": "Write a function that takes an array of strings and an integer `n` as input, and returns a new array containing only the strings whose lengths are greater than or equal to `n`.\n\n### Example\n```python\nfilter_long_strings([\"apple\", \"bat\", \"car\"... |
def check_password(password):
return (len(password) >= 8
and any(c.isupper() for c in password)
and any(c.islower() for c in password)
and any(c.isdigit() for c in password)
and any(c in {'!', '@'} for c in password)) | simplelr_Filter | [
{
"content": "Question:\nThis code defines a function called `check_password` that takes a password string as input and checks if it meets the following criteria:\n\n- At least 8 characters long\n- Contains at least one uppercase letter\n- Contains at least one lowercase letter\n- Contains at least one digit\n-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8472,
"level": 1,
"question": "This code defines a function called `check_password` that takes a password string as input and checks if it meets the following criteria:\n\n- At least 8 characters long\n- Contains at least one uppercase letter\n- Contains at least one lowercase lette... |
def sum_of_integers(n):
return n * (n + 1) // 2 if n >= 1 else 0 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as an argument and returns the sum of all integers from 1 to n (inclusive). For example, if the input is 5, the function should return 15 because 1 + 2 + 3 + 4 + 5 = 15.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8473,
"level": 1,
"question": "Create a function that takes an integer as an argument and returns the sum of all integers from 1 to n (inclusive). For example, if the input is 5, the function should return 15 because 1 + 2 + 3 + 4 + 5 = 15.",
"split": "train"
} |
from typing import List
def compare_adjacent(n: int, arr: List[int]) -> List[int]:
return [arr[i] * arr[i+1] for i in range(n-1)]
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `compare_adjacent` that takes an integer `n` and an array of `n` integers as input. The function should return a new array where every element is the product of adjacent elements from the input array. The input array will always contain at least two elements.\n\nExample... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8474,
"level": 1,
"question": "Write a function `compare_adjacent` that takes an integer `n` and an array of `n` integers as input. The function should return a new array where every element is the product of adjacent elements from the input array. The input array will always contai... |
from collections import Counter
def most_frequent_element(lst):
if not lst:
return None
counts = Counter(lst)
return counts.most_common(1)[0][0] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program to find the most frequently occurring element in a list. You should assume that the list can contain any type of elements including integers, strings, and other data types. Your program should be able to handle large lists with millions of elements efficiently.\nA... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8475,
"level": 1,
"question": "Write a Python program to find the most frequently occurring element in a list. You should assume that the list can contain any type of elements including integers, strings, and other data types. Your program should be able to handle large lists with m... |
def is_valid_ipv4_address(s):
parts = s.split('.')
if len(parts) != 4:
return False
for part in parts:
if not part.isdigit():
return False
num = int(part)
if num < 0 or num > 255:
return False
return True | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that determines if a given string is a valid IPv4 address. An IP address is a numeric representation used to identify devices connected to a network. A valid IPv4 address consists of four decimal numbers, each ranging from 0 to 255, separated by dots. For example, \"19... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8476,
"level": 1,
"question": "Create a function that determines if a given string is a valid IPv4 address. An IP address is a numeric representation used to identify devices connected to a network. A valid IPv4 address consists of four decimal numbers, each ranging from 0 to 255, s... |
def factorial(n):
if n < 0:
raise ValueError("Input must be a non-negative integer.")
elif n == 0:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the factorial of a number using an iterative approach in Python. The function should take one argument: the number for which the factorial is to be calculated. The function should return the factorial of the number. If the input is less than 0, the func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8477,
"level": 1,
"question": "Create a function that calculates the factorial of a number using an iterative approach in Python. The function should take one argument: the number for which the factorial is to be calculated. The function should return the factorial of the number. If... |
def roman_to_int(s):
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
numbers = []
for char in s:
numbers.append(roman_dict[char])
total = sum(numbers)
for i in range(1, len(numbers)):
if numbers[i] > numbers[i-1]:
total -= 2 * numbers[i-1]
... | simplelr_Filter | [
{
"content": "Question:\nObjective: To create a Python function that converts Roman numerals to integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8478,
"level": 1,
"question": "Objective: To create a Python function that converts Roman numerals to integers.",
"split": "train"
} |
def count_characters(s):
lowercase_count = 0
uppercase_count = 0
digit_count = 0
for char in s:
if char.islower():
lowercase_count += 1
elif char.isupper():
uppercase_count += 1
elif char.isdigit():
digit_count += 1
return lowercase_count, ... | simplelr_Filter | [
{
"content": "Question:\nYou should write a Python loop to count the number of lowercase letters, uppercase letters, and digits in a given string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8479,
"level": 1,
"question": "You should write a Python loop to count the number of lowercase letters, uppercase letters, and digits in a given string.",
"split": "train"
} |
def longest_increasing_substring(s):
if not s:
return 0
max_length = 1
current_length = 1
for i in range(1, len(s)):
if s[i] > s[i-1]:
current_length += 1
if current_length > max_length:
max_length = current_length
else:
current... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string and returns the length of the longest increasing substring, where an increasing substring is defined as one where each character is greater than the previous character.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8480,
"level": 1,
"question": "Create a function that takes a string and returns the length of the longest increasing substring, where an increasing substring is defined as one where each character is greater than the previous character.",
"split": "train"
} |
def dict_to_tuple_of_sets(d):
return tuple(set(value) for value in d.values()) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that converts a given dictionary of strings into a tuple of sets. Each key in the dictionary corresponds to a set in the tuple, and the elements of the set are the characters of the string value associated with that key in the dictionary. For example, given the d... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8481,
"level": 1,
"question": "Write a Python function that converts a given dictionary of strings into a tuple of sets. Each key in the dictionary corresponds to a set in the tuple, and the elements of the set are the characters of the string value associated with that key in the d... |
from collections import defaultdict
def remove_duplicate_letters(s):
freq = defaultdict(int)
for c in s:
freq[c] += 1
stack = []
included = set()
for c in s:
freq[c] -= 1 # Decrement the count of current character as we process it
if c in included:
continue ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` containing lowercase English letters. You have to remove the duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Write an algorithm that accepts ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8482,
"level": 1,
"question": "You are given a string `s` containing lowercase English letters. You have to remove the duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible result... |
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
def normalize_dataframe(df):
numerical_cols = [col for col in df.columns if pd.api.types.is_numeric_dtype(df[col])]
if not numerical_cols:
raise ValueError("The input DataFrame does not contain any numeric columns.")
df_normali... | simplelr_Package | [
{
"content": "Question:\nImplement a function that normalizes the numerical columns of a given DataFrame using Min-Max scaling. The function should exclude any non-numeric columns from the normalization process and retain them in the output DataFrame as they are.\n\nThe function should raise an exception for:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8483,
"level": 1,
"question": "Implement a function that normalizes the numerical columns of a given DataFrame using Min-Max scaling. The function should exclude any non-numeric columns from the normalization process and retain them in the output DataFrame as they are.\n\nThe functi... |
def max_subarray_sum(arr):
if not arr:
return (0, [])
max_current = max_global = arr[0]
current_start = current_end = best_start = best_end = 0
for i in range(1, len(arr)):
num = arr[i]
if num > max_current + num:
current_start = current_end = i
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the maximum sum of a contiguous subarray within a one-dimensional array of numbers, given the array as input. The function should return the maximum sum and the subarray itself.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8484,
"level": 1,
"question": "Write a Python function to find the maximum sum of a contiguous subarray within a one-dimensional array of numbers, given the array as input. The function should return the maximum sum and the subarray itself.",
"split": "train"
} |
def zero_pad(array, width):
"""
Applies zero padding to a given 1D list of integers.
Args:
array (list): A 1D list of integers.
width (int): The desired length of the output list.
Returns:
list: The zero padded list.
"""
num_zeros = width - len(array)
if num_zeros <= 0:
... | simplelr_Filter | [
{
"content": "Question:\n### Zero Padding\n\nZero padding fills in missing values in a dataset by replacing them with 0. In this problem, we will zero pad a given 1D list of integers. Please fill in the code that applies zero padding to the 1D list.\n\n```python\ndef zero_pad(array, width):\n \"\"\"\n App... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8485,
"level": 1,
"question": "### Zero Padding\n\nZero padding fills in missing values in a dataset by replacing them with 0. In this problem, we will zero pad a given 1D list of integers. Please fill in the code that applies zero padding to the 1D list.\n\n```python\ndef zero_pad(... |
def num_trees(n: int) -> int:
if n == 0:
return 1
dp = [0] * (n + 1)
dp[0] = 1
if n >= 1:
dp[1] = 1
for i in range(2, n + 1):
for k in range(1, i + 1):
left = k - 1
right = i - k
dp[i] += dp[left] * dp[right]
return dp[n] | simplelr_Data_Structure | [
{
"content": "Question:\n### Unique Binary Search Trees Calculation\n\n#### Problem Statement\nYou are tasked with writing a function to determine the number of unique Binary Search Trees (BSTs) that can be constructed using `n` distinct nodes with values from 1 through `n`. In other words, you need to calculat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8486,
"level": 1,
"question": "### Unique Binary Search Trees Calculation\n\n#### Problem Statement\nYou are tasked with writing a function to determine the number of unique Binary Search Trees (BSTs) that can be constructed using `n` distinct nodes with values from 1 through `n`. I... |
def time_to_minutes(time: str) -> int:
"""
Converts a time string in "HH:MM" format to total minutes from midnight.
Args:
time (str): A string representing the time in "HH:MM" format.
Returns:
int: The total number of minutes from midnight.
"""
# Split the time string into hours and mi... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question:\n\nYou are developing a data processing tool to convert a string representation of time in \"HH:MM\" format to the total number of minutes from midnight (00:00). Implement a function that performs this conversion.\n\n#### Function Signature:\n```python\nd... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8487,
"level": 1,
"question": "### Coding Assessment Question:\n\nYou are developing a data processing tool to convert a string representation of time in \"HH:MM\" format to the total number of minutes from midnight (00:00). Implement a function that performs this conversion.\n\n###... |
def first_three_divisible_by_3(arr):
results = []
for num in arr:
if num % 3 == 0:
results.append(num)
if len(results) == 3:
break
for num in results:
print(num) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts an array of integers and prints the first three numbers that are divisible by 3.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8488,
"level": 1,
"question": "Create a function that accepts an array of integers and prints the first three numbers that are divisible by 3.",
"split": "train"
} |
def reverse_and_uppercase(s):
return s[::-1].upper() | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse the order of characters in a given string and then convert all characters to uppercase. Here is an example string: \"Hello, World!\"\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8489,
"level": 1,
"question": "Write a python function to reverse the order of characters in a given string and then convert all characters to uppercase. Here is an example string: \"Hello, World!\"",
"split": "train"
} |
def max_subarray_sum(nums):
if not nums:
return 0
max_ending_here = max_so_far = nums[0]
for num in nums[1:]:
max_ending_here = max(num, max_ending_here + num)
if max_ending_here > max_so_far:
max_so_far = max_ending_here
return max_so_far | simplelr_Filter | [
{
"content": "Question:\nHow can I design a Python function to find the maximum sum of a contiguous subarray within a one-dimensional array of numbers using the Kadane's algorithm?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8490,
"level": 1,
"question": "How can I design a Python function to find the maximum sum of a contiguous subarray within a one-dimensional array of numbers using the Kadane's algorithm?",
"split": "train"
} |
def organize_words(words: list[str]) -> dict[int, list[str]]:
if not words:
return {}
word_length_dict = {}
for word in words:
length = len(word)
if length not in word_length_dict:
word_length_dict[length] = []
word_length_dict[length].append(word)
for key in ... | simplelr_Package | [
{
"content": "Question:\nIn this problem, you need to create a function `organize_words` that takes a list of words and organizes them into categories based on their lengths. The function should return a dictionary where each key is a word length and the corresponding value is a list of words of that length, so... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8491,
"level": 1,
"question": "In this problem, you need to create a function `organize_words` that takes a list of words and organizes them into categories based on their lengths. The function should return a dictionary where each key is a word length and the corresponding value is... |
def flatten(lst):
return [x for x in lst if type(x) is int] | simplelr_Filter | [
{
"content": "Question:\nI have written a script that takes in a list containing integers and/or strings as input. The script should be a function called `flatten` that takes in this list and returns a new list that only contains the integers. All strings should be ignored and not appear in the output list.\nAn... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8492,
"level": 1,
"question": "I have written a script that takes in a list containing integers and/or strings as input. The script should be a function called `flatten` that takes in this list and returns a new list that only contains the integers. All strings should be ignored and... |
def knapsack(values, weights, capacity):
dp = [0] * (capacity + 1)
for i in range(len(values)):
weight = weights[i]
value = values[i]
for w in range(capacity, weight - 1, -1):
if dp[w - weight] + value > dp[w]:
dp[w] = dp[w - weight] + value
return dp[capa... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `n` items where each item has a value and a weight. You are also given a maximum weight capacity of a knapsack. Your goal is to determine the maximum total value of items that can be included in the knapsack without exceeding the weight capacity. Each item can be... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8493,
"level": 1,
"question": "You are given a list of `n` items where each item has a value and a weight. You are also given a maximum weight capacity of a knapsack. Your goal is to determine the maximum total value of items that can be included in the knapsack without exceeding th... |
def find_max_diff(lst):
if len(lst) < 2:
return []
unique = set(lst)
if len(unique) < 2:
return []
min_val = min(lst)
max_val = max(lst)
return [min_val, max_val, max_val - min_val] | simplelr_Apps | [
{
"content": "Question:\nIn this coding challenge, you are required to create a function named **find_max_diff** that takes a list of integers as input. The function should find the two distinct numbers in the list that have the maximum difference between them, and then return a list with the two numbers in asc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8494,
"level": 1,
"question": "In this coding challenge, you are required to create a function named **find_max_diff** that takes a list of integers as input. The function should find the two distinct numbers in the list that have the maximum difference between them, and then return... |
def filtered_values(data, lower_bound=None, upper_bound=None):
result = []
for num in data:
include = True
if lower_bound is not None and num < lower_bound:
include = False
if upper_bound is not None and num > upper_bound:
include = False
if include:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Context\nYou work for a data analysis company where client datasets often include both valid and out-of-bound entries. As part of the preprocessing pipeline, it is essential to filter out invalid entries to conform to clients' range restrictions on the data.\n\n### Problem Statement... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8495,
"level": 1,
"question": "### Context\nYou work for a data analysis company where client datasets often include both valid and out-of-bound entries. As part of the preprocessing pipeline, it is essential to filter out invalid entries to conform to clients' range restrictions on... |
def are_anagrams(s1, s2):
# Normalize both strings: remove spaces and convert to lowercase
s1_normalized = s1.replace(" ", "").lower()
s2_normalized = s2.replace(" ", "").lower()
# If lengths are different, they cannot be anagrams
if len(s1_normalized) != len(s2_normalized):
return Fals... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that checks if two strings are anagrams of each other - `areAnagrams()` (`are_anagrams()` for Python). Strings are anagrams if they contain the same characters in the same frequency, but in any order.\n\nA few examples:\n\n```\nareAnagrams(\"listen\", \"silent\") == tru... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8496,
"level": 1,
"question": "Write a function that checks if two strings are anagrams of each other - `areAnagrams()` (`are_anagrams()` for Python). Strings are anagrams if they contain the same characters in the same frequency, but in any order.\n\nA few examples:\n\n```\nareAnag... |
from collections import Counter
def find_duplicates(arr: list[int]) -> list[int]:
counts = Counter(arr)
added = set()
result = []
for num in arr:
if counts[num] > 1 and num not in added:
result.append(num)
added.add(num)
return result | simplelr_Evol | [
{
"content": "Question:\nYou have an array of integers. Write a function that returns a new array containing only the elements that appear more than once in the input array. Elements should be presented in the same order they first appear in the input array.\n\nFunction Signature:\n```python\ndef find_duplicate... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8497,
"level": 1,
"question": "You have an array of integers. Write a function that returns a new array containing only the elements that appear more than once in the input array. Elements should be presented in the same order they first appear in the input array.\n\nFunction Signat... |
from math import factorial
from collections import Counter
def multiset_permutations(multiset):
if not multiset:
return 1
counts = Counter(multiset)
total = factorial(len(multiset))
denominator = 1
for count in counts.values():
denominator *= factorial(count)
return total // den... | simplelr_Filter | [
{
"content": "Question:\nI've been trying to solve a problem where I have to calculate the number of permutations of a multiset, or a set with repeated elements. I have found the formula for calculating it, but I need a Python code to implement this formula.\nAnswer:\nLet's think step by step.\n",
"role": "... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8498,
"level": 1,
"question": "I've been trying to solve a problem where I have to calculate the number of permutations of a multiset, or a set with repeated elements. I have found the formula for calculating it, but I need a Python code to implement this formula.",
"split": "trai... |
from typing import List
def min_path_sum(grid: List[List[int]]) -> int:
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
if n == 0:
return 0
dp = [0] * n
dp[0] = grid[0][0]
# Initialize the first row
for j in range(1, n):
dp[j] = dp[j-1] + grid[0][j]
... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: (Minimum Path Sum in a Grid)\n\nImplement a function that, given a 2D grid of integers where each cell represents a cost, returns the minimum path sum from the top-left corner to the bottom-right corner. You can only move either down or right at any point in time.\n\n**Fun... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8499,
"level": 1,
"question": "### Question: (Minimum Path Sum in a Grid)\n\nImplement a function that, given a 2D grid of integers where each cell represents a cost, returns the minimum path sum from the top-left corner to the bottom-right corner. You can only move either down or r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.