target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
from typing import List
def optimized_multiply(multiplicand: List[List[int]], multiplier: List[List[int]]) -> List[List[int]]:
# Check for empty matrices
if not multiplicand or not multiplier:
return []
m_rows = len(multiplicand)
m_cols = len(multiplicand[0]) if m_rows > 0 else 0
multi... | simplelr_Data_Structure | [
{
"content": "Question:\n### Matrix Multiplication Assessment Question\n\nYou are tasked with implementing an optimized matrix multiplication function. Given two matrices, you should return their product while ensuring the time complexity is reduced as efficiently as possible.\n\n#### Function Signature\n```pyt... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4800,
"level": 1,
"question": "### Matrix Multiplication Assessment Question\n\nYou are tasked with implementing an optimized matrix multiplication function. Given two matrices, you should return their product while ensuring the time complexity is reduced as efficiently as possible.... |
def find_word_index(words: list, target: str) -> int:
if not words:
raise ValueError("The input list must be non-empty")
if not target:
raise ValueError("The target word must be a non-empty string")
for index, word in enumerate(words):
if word == target:
return index
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are given a list of strings and a target word. Your task is to find the index of the first occurrence of the target word in the list. If the target word is not in the list, return `-1`.\n\n### Input\n- A list of strings `words`, where each string is non-empty.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4801,
"level": 1,
"question": "### Problem Statement\nYou are given a list of strings and a target word. Your task is to find the index of the first occurrence of the target word in the list. If the target word is not in the list, return `-1`.\n\n### Input\n- A list of strings `word... |
def rotated_array_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
if arr[low] <= arr[mid]: # Left half is sorted
if arr[low] <= target <= arr[mid]:
high = mid - 1
... | simplelr_Taco | [
{
"content": "Question:\nWrite a function, `rotated_array_search(arr, target)`, that searches for a `target` value within a rotated sorted array `arr` and returns its index if found. The array was initially sorted in ascending order, but at some pivot unknown to you, it was rotated. Assume no duplicate numbers ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4802,
"level": 1,
"question": "Write a function, `rotated_array_search(arr, target)`, that searches for a `target` value within a rotated sorted array `arr` and returns its index if found. The array was initially sorted in ascending order, but at some pivot unknown to you, it was ro... |
import re
from typing import List
def extract_numbers(input_string: str) -> List[int]:
numbers = re.findall(r'-?\d+', input_string)
return [int(num) for num in numbers] | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Validate and Extract Numbers from String\n\n**Problem Description**:\nWrite a function `extract_numbers(input_string: str) -> List[int]` that scans through the given input string, validates it, and extracts all numeric values present in it. The function should ignore any n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4803,
"level": 1,
"question": "### Question: Validate and Extract Numbers from String\n\n**Problem Description**:\nWrite a function `extract_numbers(input_string: str) -> List[int]` that scans through the given input string, validates it, and extracts all numeric values present in i... |
def rotate_array(arr: list, steps: int) -> list:
if not arr:
return []
n = len(arr)
effective_steps = steps % n
return arr[-effective_steps:] + arr[:-effective_steps] | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function named `rotate_array` that rotates the elements of an array to the right by a given number of steps. This will help you understand array manipulation and how indices work in Python.\n\n**Function Signature:**\n```python\ndef rotate_array(arr: list, st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4804,
"level": 1,
"question": "You are required to write a function named `rotate_array` that rotates the elements of an array to the right by a given number of steps. This will help you understand array manipulation and how indices work in Python.\n\n**Function Signature:**\n```pyt... |
def roman_to_int(s):
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
prev = 0
for char in s:
current = roman_dict[char]
if current > prev and prev != 0:
total -= 2 * prev
total += current
prev = current
return total... | simplelr_Taco | [
{
"content": "Question:\n# Description\n\nWrite a function that takes a string input representing a Roman numeral and converts it to an integer. The function should handle Roman numerals as defined by their standard form, where 'I' is 1, 'V' is 5, 'X' is 10, 'L' is 50, 'C' is 100, 'D' is 500, and 'M' is 1000. S... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4805,
"level": 1,
"question": "# Description\n\nWrite a function that takes a string input representing a Roman numeral and converts it to an integer. The function should handle Roman numerals as defined by their standard form, where 'I' is 1, 'V' is 5, 'X' is 10, 'L' is 50, 'C' is ... |
def swap_dict_keys_values(original):
swapped = {}
for key, value in original.items():
swapped[value] = key
return swapped | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a dictionary with string keys and values and returns a new dictionary where the keys and values are swapped. If the values in the original dictionary are not unique, the new dictionary should only include the last key-value pair encountered with each u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4806,
"level": 1,
"question": "Write a Python function that takes a dictionary with string keys and values and returns a new dictionary where the keys and values are swapped. If the values in the original dictionary are not unique, the new dictionary should only include the last key... |
def filtered_words(words: list, include_y: bool = False) -> list:
forbidden_vowels = {'a', 'e', 'i', 'o', 'u'}
if include_y:
forbidden_vowels.add('y')
return [word for word in words if not any(c.lower() in forbidden_vowels for c in word)] | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function called `filtered_words` which processes a given list of words and filters out those that contain any vowel (a, e, i, o, u). The function should also be able to accept an additional optional parameter `include_y` which, if set to `True`, will also ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4807,
"level": 1,
"question": "You are tasked with creating a function called `filtered_words` which processes a given list of words and filters out those that contain any vowel (a, e, i, o, u). The function should also be able to accept an additional optional parameter `include_y` ... |
def contains_substring(main_str, sub_str):
return sub_str in main_str | simplelr_Filter | [
{
"content": "Question:\nProvide a Python function to check if a given string contains a specific substring using the `in` keyword.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4808,
"level": 1,
"question": "Provide a Python function to check if a given string contains a specific substring using the `in` keyword.",
"split": "train"
} |
import numpy as np
from sklearn.utils import check_X_y, assert_all_finite
from scipy.sparse import isspmatrix
def validate_ml_data(X, y, allowed_sparse_formats=None, multi_output=False):
"""
Validate the input data for a machine learning task.
Parameters:
- X: array-like, shape (n_samples, n_features)... | simplelr_Docs | [
{
"content": "Question:\n**Coding Assessment Question: Input Validation for Machine Learning Data using Scikit-learn Utilities**\n\n**Objective**:\nIn this task, you are required to implement a function `validate_ml_data` that validates input data for a machine learning model using scikit-learn's utility functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4809,
"level": 1,
"question": "**Coding Assessment Question: Input Validation for Machine Learning Data using Scikit-learn Utilities**\n\n**Objective**:\nIn this task, you are required to implement a function `validate_ml_data` that validates input data for a machine learning model ... |
def remove_duplicates(lst):
"""This function removes duplicates from a list while preserving the original order of elements."""
seen = []
return [x for x in lst if not (x in seen or seen.append(x))] | simplelr_Filter | [
{
"content": "Question:\ndef remove_duplicates(lst):\n \"\"\"This function removes duplicates from a list while preserving the original order of elements.\"\"\"\n seen = []\n return [x for x in lst if not (x in seen or seen.append(x))]\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4810,
"level": 1,
"question": "def remove_duplicates(lst):\n \"\"\"This function removes duplicates from a list while preserving the original order of elements.\"\"\"\n seen = []\n return [x for x in lst if not (x in seen or seen.append(x))]",
"split": "train"
} |
def max_subarray_indices(arr):
if not arr:
return None # or raise ValueError("Array is empty")
current_max = global_max = arr[0]
current_start = global_start = 0
current_end = global_end = 0
for i in range(1, len(arr)):
temp = current_max + arr[i]
if arr[i] > temp:... | simplelr_Evol | [
{
"content": "Question:\nConsider a list of integers. Write a function to identify and return the starting and ending indices of the subarray with the maximum sum. If there are multiple subarrays with the same maximum sum, return the indices of the first one you find. Ensure that your function employs an effici... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4811,
"level": 1,
"question": "Consider a list of integers. Write a function to identify and return the starting and ending indices of the subarray with the maximum sum. If there are multiple subarrays with the same maximum sum, return the indices of the first one you find. Ensure t... |
def max_items(prices, k):
prices.sort()
total = 0
count = 0
for price in prices:
if total + price <= k:
total += price
count += 1
else:
break
return count | simplelr_Apps | [
{
"content": "Question:\nGiven a list of non-negative integers representing the prices of items, and a non-negative integer `k`, find the maximum number of items you can buy with exactly `k` amount of money.\n\nFor example,\n```\nprices = [1, 3, 2, 5, 4], k = 7 -> 3 (buy items with prices 1, 2, and 4)\nprices =... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4812,
"level": 1,
"question": "Given a list of non-negative integers representing the prices of items, and a non-negative integer `k`, find the maximum number of items you can buy with exactly `k` amount of money.\n\nFor example,\n```\nprices = [1, 3, 2, 5, 4], k = 7 -> 3 (buy items... |
def trackUsage(logs):
usage_counts = {}
for product in logs:
if product in usage_counts:
usage_counts[product] += 1
else:
usage_counts[product] = 1
return usage_counts
| simplelr_Taco | [
{
"content": "Question:\nA company needs to monitor and track the frequency of their product usage based on logs from user activities. Each log entry contains a string representing a single product usage event. The company wants to determine how many times each unique product has been used. \n\nGiven a list of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4813,
"level": 1,
"question": "A company needs to monitor and track the frequency of their product usage based on logs from user activities. Each log entry contains a string representing a single product usage event. The company wants to determine how many times each unique product ... |
def character_frequencies(s):
freq = {}
for c in s:
if c == ' ':
continue
if c in freq:
freq[c] += 1
else:
freq[c] = 1
if not freq:
max_freq = 0
max_chars = []
else:
max_freq = max(freq.values())
max_chars = [k ... | simplelr_Apps | [
{
"content": "Question:\nYou are given a string consisting of lowercase alphabets and spaces. You need to find the frequency of each distinct character in the string. Return the frequencies as a dictionary where the keys are the characters and the values are the respective counts.\n\nAdditionally, find the char... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4814,
"level": 1,
"question": "You are given a string consisting of lowercase alphabets and spaces. You need to find the frequency of each distinct character in the string. Return the frequencies as a dictionary where the keys are the characters and the values are the respective cou... |
from typing import List
def anagram_groups(strings: List[str]) -> List[List[str]]:
anagram_dict = {}
group_keys_order = []
for s in strings:
key = ''.join(sorted(s))
if key not in anagram_dict:
anagram_dict[key] = []
group_keys_order.append(key)
anagram_dict[... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function called `anagram_groups` that takes a list of strings as input and returns a list of lists, where each sublist contains strings that are anagrams of each other. The strings within each sublist should be in the same order as they appeared in the input list. Ensure ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4815,
"level": 1,
"question": "Write a Python function called `anagram_groups` that takes a list of strings as input and returns a list of lists, where each sublist contains strings that are anagrams of each other. The strings within each sublist should be in the same order as they ... |
import bisect
def max_subarray_sum_with_constraint(arr, S):
max_sum = 0
current_prefix = 0
sorted_prefix = [0] # Maintain a list of prefix sums in sorted order
for num in arr:
current_prefix += num
target = current_prefix - S
# Find the earliest prefix in sorted_prefix >= tar... | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers, you need to find the maximum possible sum of a contiguous subarray with a constraint: the sum of elements in the subarray should not be greater than a given integer `S`.\n\nWrite a function `max_subarray_sum_with_constraint(arr, S)` that takes in an array of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4816,
"level": 1,
"question": "Given an array of integers, you need to find the maximum possible sum of a contiguous subarray with a constraint: the sum of elements in the subarray should not be greater than a given integer `S`.\n\nWrite a function `max_subarray_sum_with_constraint(... |
def are_permutations(str1: str, str2: str) -> bool:
if len(str1) != len(str2):
return False
count1 = {}
for c in str1:
count1[c] = count1.get(c, 0) + 1
count2 = {}
for c in str2:
count2[c] = count2.get(c, 0) + 1
return count1 == count2 | simplelr_Algorithm | [
{
"content": "Question:\n### String Permutation Checker\n\nYou are given two strings and you need to check if one string is a permutation of the other. A string is considered a permutation of another if it contains the same characters with the same frequencies, but in different orders.\n\n### Implementation Det... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4817,
"level": 1,
"question": "### String Permutation Checker\n\nYou are given two strings and you need to check if one string is a permutation of the other. A string is considered a permutation of another if it contains the same characters with the same frequencies, but in differen... |
def rotate_array(arr: list[int], k: int) -> list[int]:
n = len(arr)
if n == 0:
return []
effective_k = k % n
return arr[-effective_k:] + arr[:-effective_k] | simplelr_Algorithm | [
{
"content": "Question:\n**Array Rotation Challenge**\n\n### Scenario\n\nYou are required to implement an efficient algorithm for rotating the elements of an array. This functionality is crucial in scenarios such as text processing, data manipulation, or even gaming mechanics where cyclic rotations are common.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4818,
"level": 1,
"question": "**Array Rotation Challenge**\n\n### Scenario\n\nYou are required to implement an efficient algorithm for rotating the elements of an array. This functionality is crucial in scenarios such as text processing, data manipulation, or even gaming mechanics ... |
def sort_tuples_by_second_element(tuples_list):
return sorted(tuples_list, key=lambda x: x[1]) | simplelr_Filter | [
{
"content": "Question:\nCan I create a Python function that sorts a list of tuples based on the alphabetical order of the second element in each tuple?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4819,
"level": 1,
"question": "Can I create a Python function that sorts a list of tuples based on the alphabetical order of the second element in each tuple?",
"split": "train"
} |
def string_to_list(s):
stripped_str = s.strip()
if len(stripped_str) > 5:
return list(stripped_str)
else:
return None | simplelr_Filter | [
{
"content": "Question:\nWrite a function in the Python language to convert a string to a list. The string may contain special characters and numbers. The function should remove any leading or trailing spaces in the string. Additionally, the function should only convert the string to a list if the string length... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4820,
"level": 1,
"question": "Write a function in the Python language to convert a string to a list. The string may contain special characters and numbers. The function should remove any leading or trailing spaces in the string. Additionally, the function should only convert the st... |
def perform_operations(operations):
current = 0.0
for op in operations:
parts = op.split()
cmd = parts[0]
x = float(parts[1])
if cmd == 'ADD':
current += x
elif cmd == 'MULTIPLY':
current *= x
elif cmd == 'SUBTRACT':
current -= ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `operations` where each element represents a certain type of operation to be performed on a numerical value, starting at zero. The operations are described by the following convention:\n- \"ADD x\" means adding `x` to the current value.\n- \"MULTIPLY x\" m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4821,
"level": 1,
"question": "You are given an integer array `operations` where each element represents a certain type of operation to be performed on a numerical value, starting at zero. The operations are described by the following convention:\n- \"ADD x\" means adding `x` to the... |
def generate_matrix(n):
matrix = [[0 for _ in range(n)] for _ in range(n)]
top, bottom = 0, n - 1
left, right = 0, n - 1
num = 1
while top <= bottom and left <= right:
# Fill top row from left to right
for i in range(left, right + 1):
matrix[top][i] = num
num ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to create an n x n matrix filled with elements from 1 to n*n in spiral order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4822,
"level": 1,
"question": "Write a function to create an n x n matrix filled with elements from 1 to n*n in spiral order.",
"split": "train"
} |
def longest_consecutive_substring(s: str) -> str:
if not s:
return ""
max_length = 1
max_start = 0
start = 0
for i in range(1, len(s)):
if s[i] != s[i-1]:
current_length = i - start
if current_length > max_length:
max_length = current... | simplelr_Codeforces | [
{
"content": "Question:\nIn a faraway land, there is a famous computer scientist named Riveta who loves strings. Riveta has recently come up with a fascinating new problem related to string manipulation. Given a string s containing only lowercase English letters, Riveta is interested in finding the longest subs... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4823,
"level": 1,
"question": "In a faraway land, there is a famous computer scientist named Riveta who loves strings. Riveta has recently come up with a fascinating new problem related to string manipulation. Given a string s containing only lowercase English letters, Riveta is int... |
from typing import List, Tuple
def events_overlap(events: List[Tuple[int, int]]) -> bool:
sorted_events = sorted(events, key=lambda x: x[0])
for i in range(len(sorted_events) - 1):
current_end = sorted_events[i][1]
next_start = sorted_events[i+1][0]
if current_end > next_start:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Scheduling Timed Events\n\nYou are going to implement a scheduler that tracks a list of events and determines if any two events overlap or not.\n\n#### Rules:\n1. Each event is represented as a tuple `(start, end)` where `start` and `end` are integers denoting the start and end time... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4824,
"level": 1,
"question": "### Scheduling Timed Events\n\nYou are going to implement a scheduler that tracks a list of events and determines if any two events overlap or not.\n\n#### Rules:\n1. Each event is represented as a tuple `(start, end)` where `start` and `end` are integ... |
def add_binary_strings(a: str, b: str) -> str:
i = len(a) - 1
j = len(b) - 1
carry = 0
result = []
while i >= 0 or j >= 0 or carry > 0:
a_bit = int(a[i]) if i >= 0 else 0
b_bit = int(b[j]) if j >= 0 else 0
total = a_bit + b_bit + carry
sum_bit = total % ... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with implementing a function that combines two binary strings by adding them together, similar to how binary addition is performed manually. You will write a function `add_binary_strings` that takes in two string arguments, each representing a binary number, and returns t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4825,
"level": 1,
"question": "You are tasked with implementing a function that combines two binary strings by adding them together, similar to how binary addition is performed manually. You will write a function `add_binary_strings` that takes in two string arguments, each represen... |
def custom_sort(books):
# Separate even and odd numbers
evens = [x for x in books if x % 2 == 0]
odds = [x for x in books if x % 2 != 0]
# Sort each list
evens.sort()
odds.sort()
# Concatenate the sorted lists with evens first
return evens + odds
# Test cases
print(custom_sort... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Objective:\nTo demonstrate your understanding of sorting algorithms and their application, you need to implement a function that sorts a list of integers with a custom order of precedence.\n\n#### Scenario:\nImagine you work at a digital book libra... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4826,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Objective:\nTo demonstrate your understanding of sorting algorithms and their application, you need to implement a function that sorts a list of integers with a custom order of precedence.\n\n#### Scenario:\nImagi... |
def is_sorted(arr):
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True | simplelr_Filter | [
{
"content": "Question:\nUsing only the standard library of Python, how can you check if an array of integers is sorted?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4827,
"level": 1,
"question": "Using only the standard library of Python, how can you check if an array of integers is sorted?",
"split": "train"
} |
def lengthOfLongestSubstringKDistinct(s, n):
char_count = {}
left = 0
max_length = 0
for right in range(len(s)):
char = s[right]
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# If the number of distinct characters... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` and an integer `n`, return _the length of the longest substring of `s` that contains at most `n` distinct characters_.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4828,
"level": 1,
"question": "Given a string `s` and an integer `n`, return _the length of the longest substring of `s` that contains at most `n` distinct characters_.",
"split": "train"
} |
def longest_substring_without_repeating_characters(s: str) -> str:
char_index = {}
left = 0
max_length = 0
start = 0
for right in range(len(s)):
char = s[right]
if char in char_index and char_index[char] >= left:
left = char_index[char] + 1
char_index[char] =... | simplelr_Filter | [
{
"content": "Question:\nYou are given a string containing only lowercase English letters. You need to find the longest substring without repeating characters.\n\n Example:\n\nInput: \"abcabcbb\"\nOutput: \"abc\"\n\nInput: \"bbbbb\"\nOutput: \"b\"\n\nInput: \"pwwkew\"\nOutput: \"wke\"\n\n Constraints:\n\n 1 <= ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4829,
"level": 1,
"question": "You are given a string containing only lowercase English letters. You need to find the longest substring without repeating characters.\n\n Example:\n\nInput: \"abcabcbb\"\nOutput: \"abc\"\n\nInput: \"bbbbb\"\nOutput: \"b\"\n\nInput: \"pwwkew\"\nOutput:... |
def longest_substring_with_two_distinct(s):
char_map = {}
left = 0
max_len = 0
for right in range(len(s)):
char = s[right]
char_map[char] = char_map.get(char, 0) + 1
while len(char_map) > 2:
left_char = s[left]
char_map[left_char] -= 1
if cha... | simplelr_Taco | [
{
"content": "Question:\nGiven a string of lowercase English letters, determine the length of the longest substring that contains at most two distinct characters. \n\n### Examples\n```python\nlongest_substring_with_two_distinct('eceba') => 3 # \"ece\"\nlongest_substring_with_two_distinct('ccaabbb') => 5 # \"a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4830,
"level": 1,
"question": "Given a string of lowercase English letters, determine the length of the longest substring that contains at most two distinct characters. \n\n### Examples\n```python\nlongest_substring_with_two_distinct('eceba') => 3 # \"ece\"\nlongest_substring_with_... |
def product_except_self(numList):
n = len(numList)
if n == 0:
return []
prefix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * numList[i-1]
suffix = [1] * n
for i in range(n-2, -1, -1):
suffix[i] = suffix[i+1] * numList[i+1]
result = [prefix[i... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes as input a list of integers called `numList`. The function should return a new list where each element is the product of all the integers in `numList` except the element at the same index. Specifically, if `numList` is `[1, 2, 3, 4]`, the function should ret... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4831,
"level": 1,
"question": "Create a function that takes as input a list of integers called `numList`. The function should return a new list where each element is the product of all the integers in `numList` except the element at the same index. Specifically, if `numList` is `[1,... |
def guess_number_game(target: int, guesses: list) -> str:
for i in range(len(guesses)):
guess = guesses[i]
if guess == target:
# Determine the current player
if i % 2 == 0:
# It's Player A's turn
# Check if the next guess (Player B's) is also t... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that simulates a number-guessing game. The rules are as follows:\n\n1. There are two players: Player A and Player B.\n2. Each player alternatively guesses a number.\n3. The target number is randomly selected from a given range, but it is hidden from both players.\n4. Th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4832,
"level": 1,
"question": "Write a function that simulates a number-guessing game. The rules are as follows:\n\n1. There are two players: Player A and Player B.\n2. Each player alternatively guesses a number.\n3. The target number is randomly selected from a given range, but it ... |
def replace_whitespace_with_underscore(s):
return s.replace(" ", "_") | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to replace whitespaces with underscores. Here is an example \"hello world\" should be converted to \"hello_world\". How can this be done using python's built-in string methods?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4833,
"level": 1,
"question": "Write a python function to replace whitespaces with underscores. Here is an example \"hello world\" should be converted to \"hello_world\". How can this be done using python's built-in string methods?",
"split": "train"
} |
from collections import Counter
def most_frequent_element(nums):
counts = Counter(nums)
max_count = max(counts.values())
max_numbers = [num for num, count in counts.items() if count == max_count]
return min(max_numbers) | simplelr_Evol | [
{
"content": "Question:\nDevise a function that discerns the most frequent element within a supplied list of integers. If multiple elements share the highest frequency, the function should return the smallest of these elements. Implement and return the ensuing value.\n\nSample Input: [4, 1, 2, 2, 3, 3, 3, 4, 4,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4834,
"level": 1,
"question": "Devise a function that discerns the most frequent element within a supplied list of integers. If multiple elements share the highest frequency, the function should return the smallest of these elements. Implement and return the ensuing value.\n\nSample... |
import torch
def add_tensors_with_broadcast(tensor1: torch.Tensor, tensor2: torch.Tensor) -> torch.Tensor:
"""
Adds two tensors if they are broadcastable, otherwise raises a ValueError.
:param tensor1: First input tensor.
:param tensor2: Second input tensor.
:return: A tensor resulting from broadc... | simplelr_Docs | [
{
"content": "Question:\n<|Analysis Begin|>\n\nThe provided documentation explains the broadcasting semantics in PyTorch, which supports NumPy-like broadcasting for tensor operations. The central idea is that PyTorch can automatically expand tensors to make operations possible without making copies of the data.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4835,
"level": 1,
"question": "<|Analysis Begin|>\n\nThe provided documentation explains the broadcasting semantics in PyTorch, which supports NumPy-like broadcasting for tensor operations. The central idea is that PyTorch can automatically expand tensors to make operations possible... |
def manipulate_bytearrays(a: bytearray, b: bytearray, start_a: int, end_a: int, start_b: int, end_b: int) -> bytearray:
"""
Manipulates two input bytearrays by concatenating specified slices.
Parameters:
- a: A bytearray object.
- b: A bytearray object.
- start_a: Start index for slicing bytear... | simplelr_Docs | [
{
"content": "Question:\n### ByteArray Manipulations\n\n#### Objective\nImplement a Python function that performs several manipulations on bytearrays using the provided C API and macro functions. The function should accept two bytearrays and return a new bytearray that is the concatenation of specified slices f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4836,
"level": 1,
"question": "### ByteArray Manipulations\n\n#### Objective\nImplement a Python function that performs several manipulations on bytearrays using the provided C API and macro functions. The function should accept two bytearrays and return a new bytearray that is the ... |
def min_intervals_to_remove(intervals):
if not intervals:
return 0
# Sort intervals by their end times
intervals.sort(key=lambda x: x[1])
count = 1
last_end = intervals[0][1]
for i in range(1, len(intervals)):
if intervals[i][0] >= last_end:
count += 1
las... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of intervals `intervals` where each interval is a pair of integers `[start, end]` representing a time period during which a job is being performed. Determine _the minimum number of intervals you need to remove_ to make the remaining intervals non-overlapping. Return... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4837,
"level": 1,
"question": "You are given a list of intervals `intervals` where each interval is a pair of integers `[start, end]` representing a time period during which a job is being performed. Determine _the minimum number of intervals you need to remove_ to make the remainin... |
def vowel_count(s):
vowels = "aeiouAEIOU"
sum_vowels = 0
for char in s:
if char in vowels:
sum_vowels += 1
return f"Number of vowels: {sum_vowels}" | simplelr_Evol | [
{
"content": "Question:\nExamine the Python code provided and identify any logical or syntactical errors. \n\ndef vowel_count(s):\n vowels = \"aeiouAEIOU\"\n sum_vowels = 0\n for char in s:\n if char in vowels:\n sum_vowels += 1\n return \"Number of vowels:\" + sum_vowels\nAnswer:\nLet's think step ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4838,
"level": 1,
"question": "Examine the Python code provided and identify any logical or syntactical errors. \n\ndef vowel_count(s):\n vowels = \"aeiouAEIOU\"\n sum_vowels = 0\n for char in s:\n if char in vowels:\n sum_vowels += 1\n return \"Number of vowels:\" + sum... |
def max_product_subarray(nums):
if not nums:
return 0 # Return 0 for an empty array
max_prod = min_prod = result = nums[0]
for num in nums[1:]:
temp = max_prod
current_max = max(num, temp * num, min_prod * num)
current_min = min(num, temp * num, min_prod *... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the maximum product of any contiguous subarray. You are given an array of integers that may contain both positive and negative numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4839,
"level": 1,
"question": "Write a function to calculate the maximum product of any contiguous subarray. You are given an array of integers that may contain both positive and negative numbers.",
"split": "train"
} |
import math
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = int(math.sqrt(n))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True | simplelr_Package | [
{
"content": "Question:\nWrite a function `is_prime(n)` that takes a single integer \\( n \\) as input and returns `True` if \\( n \\) is a prime number and `False` otherwise. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The implementation should be ef... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4840,
"level": 1,
"question": "Write a function `is_prime(n)` that takes a single integer \\( n \\) as input and returns `True` if \\( n \\) is a prime number and `False` otherwise. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itse... |
def find_single_number(nums):
res = 0
for num in nums:
res ^= num
return res | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a list of integers where every element appears twice except for one. Find the element that appears only once without using extra memory for another list. You should aim for a linear runtime complexity.\n\nFor example, given the list [4, 3, 2, 4, 1, 3, 2], it should return ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4841,
"level": 1,
"question": "You are given a list of integers where every element appears twice except for one. Find the element that appears only once without using extra memory for another list. You should aim for a linear runtime complexity.\n\nFor example, given the list [4, 3... |
def nth_highest_score(scores: list, n: int) -> int:
if n < 1:
return None
unique_scores = list(set(scores))
if len(unique_scores) < n:
return None
unique_scores.sort(reverse=True)
return unique_scores[n-1] | simplelr_Evol | [
{
"content": "Question:\nYou are given a list of integers representing the scores of participants in a competition. Your task is to write a Python function that calculates and returns the nth highest unique score from the list. If the nth highest unique score does not exist, the function should return None.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4842,
"level": 1,
"question": "You are given a list of integers representing the scores of participants in a competition. Your task is to write a Python function that calculates and returns the nth highest unique score from the list. If the nth highest unique score does not exist, t... |
def find_missing_events(event_timestamps, low, high):
missing = []
if not event_timestamps:
if low <= high:
return [(low, high)]
else:
return []
# Check initial gap
first = event_timestamps[0]
if first > low:
missing.append((low, first - 1))
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Context\nYour organization maintains a log of timestamps (in seconds) when events occur on a server. However, you need to identify periods (in seconds) when no events were recorded within a specified time range.\n\n### Task\nWrite a function `find_missing_events` that identifies and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4843,
"level": 1,
"question": "### Context\nYour organization maintains a log of timestamps (in seconds) when events occur on a server. However, you need to identify periods (in seconds) when no events were recorded within a specified time range.\n\n### Task\nWrite a function `find_... |
from typing import List
def findDuplicates(numbers: List[int]) -> List[int]:
counts = {}
duplicates = []
for num in numbers:
if num in counts:
counts[num] += 1
if counts[num] == 2:
duplicates.append(num)
else:
counts[num] = 1
return du... | simplelr_Apps | [
{
"content": "Question:\nWrite a function named `findDuplicates` that takes a list of integers as input and returns a list of integers that are duplicates in the given list. The duplicates should be returned in the order they first appear in the input list. If there are no duplicates, the function should return... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4844,
"level": 1,
"question": "Write a function named `findDuplicates` that takes a list of integers as input and returns a list of integers that are duplicates in the given list. The duplicates should be returned in the order they first appear in the input list. If there are no dup... |
def is_solution(a, b, c, x):
return a * x**2 + b * x + c == 0 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to determine if a number is a solution to a given quadratic equation. The function should take three parameters, representing the coefficients of the quadratic equation, and one parameter for the number to check.\nAnswer:\nLet's think step by step.\n",
"role"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4845,
"level": 1,
"question": "Write a python function to determine if a number is a solution to a given quadratic equation. The function should take three parameters, representing the coefficients of the quadratic equation, and one parameter for the number to check.",
"split": "t... |
def is_consecutive(stack):
if len(stack) <= 1:
return True
for i in range(len(stack) - 1):
if stack[i+1] != stack[i] + 1:
return False
return True | simplelr_Data_Structure | [
{
"content": "Question:\n### Verify Consecutive Elements in Stack\n\n#### Scenario\nJohn is working on a project where he needs to validate if given sequences of numbers in stacks are consecutive. He wants to maintain the integrity of the stacks while performing this check for sequences starting from the bottom... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4846,
"level": 1,
"question": "### Verify Consecutive Elements in Stack\n\n#### Scenario\nJohn is working on a project where he needs to validate if given sequences of numbers in stacks are consecutive. He wants to maintain the integrity of the stacks while performing this check for... |
from typing import List
def count_sunny_buildings(heights: List[int]) -> int:
current_max = 0
count = 0
for height in heights:
if height > current_max:
count += 1
current_max = height
return count | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a list of integers representing heights of buildings standing in a line. The amount of sunlight a building receives depends on whether there are taller buildings to its left side that block the sunlight. Specifically, a building will not receive sunlight if there is at lea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4847,
"level": 1,
"question": "You are given a list of integers representing heights of buildings standing in a line. The amount of sunlight a building receives depends on whether there are taller buildings to its left side that block the sunlight. Specifically, a building will not ... |
def digital_root(n):
if n == 0:
return 0
remainder = n % 9
return 9 if remainder == 0 else remainder | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to add all the digits of a number until the result is a single digit. This is known as the digital root of a number. For example, the digital root of 16 is 1 + 6 = 7. If the result is not a single digit, keep summing the digits until a single digit is obtained.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4848,
"level": 1,
"question": "Write a python function to add all the digits of a number until the result is a single digit. This is known as the digital root of a number. For example, the digital root of 16 is 1 + 6 = 7. If the result is not a single digit, keep summing the digits ... |
def is_palindrome(s):
filtered = [c.lower() for c in s if c.isalnum()]
filtered_str = ''.join(filtered)
return filtered_str == filtered_str[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string and returns whether the string is a palindrome (reads the same backward as forward). A palindrome does not need to be limited to alphabetic characters; it can also include spaces, digits, and punctuation. Additionally, the function should be case-in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4849,
"level": 1,
"question": "Create a function that takes a string and returns whether the string is a palindrome (reads the same backward as forward). A palindrome does not need to be limited to alphabetic characters; it can also include spaces, digits, and punctuation. Additiona... |
def xor_cipher(text, key):
# Calculate how many times the key needs to be repeated
key_repeats = len(text) // len(key) + (1 if len(text) % len(key) != 0 else 0)
key_str = key * key_repeats
# Use zip to pair each text character with the corresponding key character
# then XOR them and join into a stri... | simplelr_Filter | [
{
"content": "Question:\nThis is related to cryptography and I am trying to understand it through coding.\n\nWhat I am trying to do is understand how XOR cipher works.\n\n**Here's what I understand:**\n\nXOR is a bitwise operation that returns **1** if the corresponding bits in two operands are **different**. H... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4850,
"level": 1,
"question": "This is related to cryptography and I am trying to understand it through coding.\n\nWhat I am trying to do is understand how XOR cipher works.\n\n**Here's what I understand:**\n\nXOR is a bitwise operation that returns **1** if the corresponding bits i... |
from typing import List
def rearrange_even_odd(lst: List[int]) -> List[int]:
evens = []
odds = []
for num in lst:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens + odds | simplelr_Apps | [
{
"content": "Question:\nWrite a function that rearranges an integer array in such a way that all even numbers appear before all the odd numbers while maintaining their original relative order. Your function should take a list of integers as input and return a new list with the integers rearranged as specified.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4851,
"level": 1,
"question": "Write a function that rearranges an integer array in such a way that all even numbers appear before all the odd numbers while maintaining their original relative order. Your function should take a list of integers as input and return a new list with th... |
def separate_digits(s):
digits = []
for char in s:
if char.isdigit():
digits.append(int(char))
return digits | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a string of numbers, separates them into individual digits, and returns a list of those digits. The function should ignore any non-numeric characters and handle strings with mixed content.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4852,
"level": 1,
"question": "Create a function that takes in a string of numbers, separates them into individual digits, and returns a list of those digits. The function should ignore any non-numeric characters and handle strings with mixed content.",
"split": "train"
} |
def reverse_string(s):
reversed_s = s[::-1]
if s == reversed_s:
return f"The input is a palindrome: {s}"
else:
return reversed_s | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string and returns the string in reverse order. Additionally, the function should be able to handle a special case where if the input string is a palindrome (reads the same backward as forward), it should return a message saying \"The input is a pali... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4853,
"level": 1,
"question": "Write a Python function that takes a string and returns the string in reverse order. Additionally, the function should be able to handle a special case where if the input string is a palindrome (reads the same backward as forward), it should return a m... |
def calculate_fuel(amount, efficiency):
return int(amount * efficiency) | simplelr_Apps | [
{
"content": "Question:\nYou are tasked with helping an automotive company to enhance the efficiency of their fuel stations. Write a function, `calculate_fuel(amount, efficiency)`, that computes the maximum distance a vehicle can travel given the amount of fuel in gallons and the vehicle's fuel efficiency in mi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4854,
"level": 1,
"question": "You are tasked with helping an automotive company to enhance the efficiency of their fuel stations. Write a function, `calculate_fuel(amount, efficiency)`, that computes the maximum distance a vehicle can travel given the amount of fuel in gallons and ... |
def sort_dicts_by_key(dict_list, key):
with_key = [d for d in dict_list if key in d]
without_key = [d for d in dict_list if key not in d]
sorted_with_key = sorted(with_key, key=lambda x: x[key])
return sorted_with_key + without_key | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to sort a list of dictionaries based on a specific key. For example, if the key is `'age'`, the function should sort the list of dictionaries in ascending order based on the `'age'` key. If the key does not exist in some dictionaries, those dictionaries should be... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4855,
"level": 1,
"question": "Write a Python function to sort a list of dictionaries based on a specific key. For example, if the key is `'age'`, the function should sort the list of dictionaries in ascending order based on the `'age'` key. If the key does not exist in some diction... |
def digit_sum_factorial(n):
if n == 0:
factorial = 1
else:
factorial = 1
for i in range(1, n + 1):
factorial *= i
s = str(factorial)
total = 0
for c in s:
total += int(c)
return total
| simplelr_Taco | [
{
"content": "Question:\n# Task\nGiven an integer `n`, your task is to compute the sum of the digits of `n!` (n factorial).\n\n# Input/Output\n\n- `[input]` integer `n`\n\n `0 ≤ n ≤ 100`\n\n\n- `[output]` an integer\n \n The sum of the digits of `n!`\n\n# Example\n\nThe function `digit_sum_factorial(10)` w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4856,
"level": 1,
"question": "# Task\nGiven an integer `n`, your task is to compute the sum of the digits of `n!` (n factorial).\n\n# Input/Output\n\n- `[input]` integer `n`\n\n `0 ≤ n ≤ 100`\n\n\n- `[output]` an integer\n \n The sum of the digits of `n!`\n\n# Example\n\nThe f... |
def ternary_search(arr, left, right, key):
"""
Searches for key in arr[left..right]
Parameters:
- arr (List[int]): A list of integers sorted in ascending order.
- left (int): The starting index of the segment to be searched.
- right (int): The ending index of the segment to be searched.
... | simplelr_Data_Structure | [
{
"content": "Question:\n**Ternary Search Algorithm Implementation**\n\n### Objective\nImplement the ternary search algorithm in Python to determine if a given element (key) exists in a sorted array, and if so, return its index. The array is guaranteed to be sorted in ascending order.\n\n### Function Signature\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4857,
"level": 1,
"question": "**Ternary Search Algorithm Implementation**\n\n### Objective\nImplement the ternary search algorithm in Python to determine if a given element (key) exists in a sorted array, and if so, return its index. The array is guaranteed to be sorted in ascendin... |
def rotate_matrix(matrix: list) -> None:
n = len(matrix)
if n == 0:
return
for layer in range(n // 2):
first = layer
last = n - layer - 1
for i in range(first, last):
# Save the top element
top = matrix[first][i]
# Move the lef... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function called `rotate_matrix` in Python. This function will rotate a given N x N matrix 90 degrees clockwise. The function should accept a single argument `matrix`, which is a 2D list representing the N x N matrix.\n\nYour implementation must ensure the fol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4858,
"level": 1,
"question": "You are required to write a function called `rotate_matrix` in Python. This function will rotate a given N x N matrix 90 degrees clockwise. The function should accept a single argument `matrix`, which is a 2D list representing the N x N matrix.\n\nYour... |
def rearrange_list(lst):
even = []
odd = []
for idx, num in enumerate(lst):
if idx % 2 == 0:
even.append(num)
else:
odd.append(num)
# Sort even in ascending order and odd in descending order
even_sorted = sorted(even)
odd_sorted = sorted(odd, reverse=True)... | simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, rearrange the list in such a way that the even-indexed elements are sorted in ascending order and the odd-indexed elements are sorted in descending order. Your task is to write a function that takes the list of integers as input, rearranges it according to the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4859,
"level": 1,
"question": "Given a list of integers, rearrange the list in such a way that the even-indexed elements are sorted in ascending order and the odd-indexed elements are sorted in descending order. Your task is to write a function that takes the list of integers as inp... |
def is_valid_domain(s):
# Check the string is at least two characters long
if len(s) < 2:
return False
# Check the string starts with a letter
if not s[0].isalpha():
return False
# Check all characters are allowed (letters, digits, hyphens, periods)
allowed_characters = set("ab... | simplelr_Filter | [
{
"content": "Question:\nYour task is to generate a simple test to evaluate whether a string is a valid domain name. Here are the rules: \n- It should start with a letter.\n- It should contain only letters (both uppercase and lowercase), digits, hyphens, and periods.\n- No two consecutive hyphens are allowed.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4860,
"level": 1,
"question": "Your task is to generate a simple test to evaluate whether a string is a valid domain name. Here are the rules: \n- It should start with a letter.\n- It should contain only letters (both uppercase and lowercase), digits, hyphens, and periods.\n- No two... |
def calculate_team_score(players):
"""
Calculate the total score of a team based on individual player scores.
Parameters:
players (list): List of dictionaries, each containing the player name and their score.
Example: [{'name': 'Alice', 'score': 10}, {'name': 'Bob', 'score': 20}]
... | simplelr_Package | [
{
"content": "Question:\nDevelop a function named `calculate_team_score` that computes the total score of a team based on individual player scores. The function should accept a list of dictionaries, each representing a player with their respective score, and return the sum of these scores.\n\n**Function Signatu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4861,
"level": 1,
"question": "Develop a function named `calculate_team_score` that computes the total score of a team based on individual player scores. The function should accept a list of dictionaries, each representing a player with their respective score, and return the sum of ... |
def max_product(nums):
if len(nums) < 2:
return None # Not enough elements to form a product
max1 = max2 = -float('inf')
min1 = min2 = float('inf')
for num in nums:
if num > max1:
max2 = max1
max1 = num
elif num > max2:
max2 = num
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum product of two elements in a list using Kadane's algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4862,
"level": 1,
"question": "Write a python function to find the maximum product of two elements in a list using Kadane's algorithm.",
"split": "train"
} |
import math
def shortest_distance(x1: int, y1: int, x2: int, y2: int) -> float:
dx = x2 - x1
dy = y2 - y1
return math.sqrt(dx ** 2 + dy ** 2) | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\n#### Context\nA logistics company uses a simplified navigation system for plotting routes based on a grid. To ensure efficient delivery, a utility function is required to determine the shortest path (in terms of distance) between two points on the grid.\n\n#### Task\nWri... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4863,
"level": 1,
"question": "### Question\n\n#### Context\nA logistics company uses a simplified navigation system for plotting routes based on a grid. To ensure efficient delivery, a utility function is required to determine the shortest path (in terms of distance) between two po... |
def convert_number(number):
"""
Converts a given integer from decimal to binary, octal, and hexadecimal representations.
Args:
number (int): The decimal number to be converted.
Returns:
tuple: A tuple containing three strings representing the number in binary, octal, and hexadecimal re... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that converts a given number from decimal to binary, octal, and hexadecimal representations. The function should return a tuple containing all three representations as strings. Include a docstring that explains the functionality of the function and provides examp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4864,
"level": 1,
"question": "Write a Python function that converts a given number from decimal to binary, octal, and hexadecimal representations. The function should return a tuple containing all three representations as strings. Include a docstring that explains the functionality... |
def sum_of_squares(n):
if not isinstance(n, int) or n <= 0:
return 0
return n * (n + 1) * (2 * n + 1) // 6 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the sum of squares of the first n natural numbers. You should ensure that the function is efficient and handles edge cases, such as when n is non-positive.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4865,
"level": 1,
"question": "Write a python function to find the sum of squares of the first n natural numbers. You should ensure that the function is efficient and handles edge cases, such as when n is non-positive.",
"split": "train"
} |
def bbq_planner(guests: int) -> dict:
sausages = 3 * guests
soda = 2 * guests
salad = 200 * guests
return {
'sausages': sausages,
'soda': soda,
'salad': salad
} | simplelr_Apps | [
{
"content": "Question:\n# Backyard BBQ\n\nA family is planning a backyard BBQ and needs to calculate how much food to prepare based on the number of guests. They have decided on the following serving sizes:\n\n- Each guest eats 3 sausages.\n- Each guest drinks 2 cans of soda.\n- Each guest eats 200 grams of sa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4866,
"level": 1,
"question": "# Backyard BBQ\n\nA family is planning a backyard BBQ and needs to calculate how much food to prepare based on the number of guests. They have decided on the following serving sizes:\n\n- Each guest eats 3 sausages.\n- Each guest drinks 2 cans of soda.... |
def subtract(a, b):
return a - b | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python Subtract node that subtracts two input values and returns the result?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4867,
"level": 1,
"question": "How can I create a Python Subtract node that subtracts two input values and returns the result?",
"split": "train"
} |
def total_surface_area_of_cuboids(cuboids):
total = 0
for cuboid in cuboids:
l, w, h = cuboid
total += 2 * (l * w + l * h + w * h)
return total | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the surface area of a 3D object that consists of multiple cuboids. The function should take a list of cuboids, where each cuboid is represented as a list of three integers [length, width, height]. The function should return the total surface area of all the cubo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4868,
"level": 1,
"question": "Write a function to find the surface area of a 3D object that consists of multiple cuboids. The function should take a list of cuboids, where each cuboid is represented as a list of three integers [length, width, height]. The function should return the... |
import pandas as pd
def get_top_n_purchases(filename: str, customer_id: str, n: int) -> pd.DataFrame:
# Read the CSV file into a DataFrame
df = pd.read_csv(filename)
# Filter the data for the specified customer
filtered_df = df[df['CustomerID'] == customer_id]
# Sort the filtered data by ... | simplelr_Package | [
{
"content": "Question:\n**Task**: Create a function named `get_top_n_purchases(filename, customer_id, n)` that processes a CSV file using **pandas**. The CSV file contains sales data with columns such as `CustomerID`, `PurchaseDate`, `ProductName`, and `Amount`. The function should:\n\n1. Read the entire CSV f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4869,
"level": 1,
"question": "**Task**: Create a function named `get_top_n_purchases(filename, customer_id, n)` that processes a CSV file using **pandas**. The CSV file contains sales data with columns such as `CustomerID`, `PurchaseDate`, `ProductName`, and `Amount`. The function ... |
import string
def count_word_frequency(paragraph, word):
target = word.lower()
count = 0
for w in paragraph.split():
cleaned = w.lower().strip(string.punctuation)
if cleaned == target:
count += 1
return count | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to count the frequency of a given word in a paragraph. The function should be case-insensitive and should also ignore punctuation marks.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4870,
"level": 1,
"question": "Write a python function to count the frequency of a given word in a paragraph. The function should be case-insensitive and should also ignore punctuation marks.",
"split": "train"
} |
def find_magic_index(nums):
n = len(nums)
if n == 0:
return -1
if nums[0] == 0:
return 0
low, high = 0, n - 1
result = -1
while low <= high:
mid = (low + high) // 2
if nums[mid] >= mid:
result = mid
high = mid - 1
else:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` sorted in **non-decreasing** order. Your task is to determine whether there exists a number in the array that is equal to its **index value** (0-based). If such a number exists, return its index. If there are multiple such numbers, return the index ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4871,
"level": 1,
"question": "You are given an integer array `nums` sorted in **non-decreasing** order. Your task is to determine whether there exists a number in the array that is equal to its **index value** (0-based). If such a number exists, return its index. If there are multi... |
def sum_two_numbers(num1, num2):
"""
Returns the sum of two numbers.
"""
return num1 + num2 | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes two numbers as arguments and returns their sum.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4872,
"level": 1,
"question": "Create a Python function that takes two numbers as arguments and returns their sum.",
"split": "train"
} |
def arrange_colors(n, arr):
if n == 0:
return []
arr.sort()
k = (n + 1) // 2
lower = arr[:k]
higher = arr[k:]
result = []
i = 0 # index for lower
j = len(higher) - 1 # index for higher, starting from the end
for pos in range(n):
if pos % 2 == 0:
# even p... | simplelr_Taco | [
{
"content": "Question:\nA digital designer is developing an application to enhance user experiences. One of the features requires evaluating the visual impact of different colors in a specific layout. The designer is experimenting with different sequences of colors represented by integers in an array. The goal... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4873,
"level": 1,
"question": "A digital designer is developing an application to enhance user experiences. One of the features requires evaluating the visual impact of different colors in a specific layout. The designer is experimenting with different sequences of colors represente... |
def longest_arith_seq_length(arr):
n = len(arr)
if n == 0:
return 0
max_length = 1 # The minimum possible length is 1
dp = []
for i in range(n):
current_dict = {}
for j in range(i):
d = arr[i] - arr[j]
length = 2 # Minimum length is 2 (elements j and... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of `n` integers, return the length of the **longest arithmetic subsequence** in the array. An arithmetic subsequence is one where the difference between consecutive elements is the same. For example, in the array `[1, 7, 10, 13, 14, 19]`, the longest arithmetic subsequenc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4874,
"level": 1,
"question": "Given an array of `n` integers, return the length of the **longest arithmetic subsequence** in the array. An arithmetic subsequence is one where the difference between consecutive elements is the same. For example, in the array `[1, 7, 10, 13, 14, 19]`... |
def maxSubArraySum(arr):
current_max = max_so_far = arr[0]
for num in arr[1:]:
current_max = max(num, current_max + num)
max_so_far = max(max_so_far, current_max)
return max_so_far
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, the task is to find the maximum sum of any contiguous subarray. This problem is commonly known as the \"Maximum Subarray Sum\" problem.\n\nFor example, the maximum sum for the subarray of $[-2,1,-3,4,-1,2,1,-5,4]$ is $\\boldsymbol{6}$ since the subarray with th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4875,
"level": 1,
"question": "Given a list of integers, the task is to find the maximum sum of any contiguous subarray. This problem is commonly known as the \"Maximum Subarray Sum\" problem.\n\nFor example, the maximum sum for the subarray of $[-2,1,-3,4,-1,2,1,-5,4]$ is $\\boldsy... |
from typing import List
def subarray_sums(arr: List[int]) -> List[int]:
n = len(arr)
prefix_sum = [0] * (n + 1)
for i in range(n):
prefix_sum[i + 1] = prefix_sum[i] + arr[i]
result = []
for i in range(n):
for j in range(i, n):
current_sum = prefix_sum[j + 1] - prefix_sum... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge: Subarray Sum Calculation\n\nYou are required to write a function to calculate the sum of all subarrays of a given array of integers. A subarray is a contiguous part of the array.\n\n#### Function Signature\n```python\ndef subarray_sums(arr: List[int]) -> List[int]:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4876,
"level": 1,
"question": "### Coding Challenge: Subarray Sum Calculation\n\nYou are required to write a function to calculate the sum of all subarrays of a given array of integers. A subarray is a contiguous part of the array.\n\n#### Function Signature\n```python\ndef subarray... |
def longest_common_subsequence(s1, s2):
m = len(s1)
n = len(s2)
# Create a table with (m+1) rows and (n+1) columns
table = [[0] * (n + 1) for _ in range(m + 1)]
# Fill the table
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i-1] == s2[j-1]:
ta... | simplelr_Filter | [
{
"content": "Question:\nDesign an algorithm in Python to find the longest common sub-sequence between two strings.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4877,
"level": 1,
"question": "Design an algorithm in Python to find the longest common sub-sequence between two strings.",
"split": "train"
} |
def process_strings(string_list, target, prefix):
result = []
for s in string_list:
if target in s:
result.append(prefix + s)
else:
result.append(s)
return result | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python function to process a list of strings, where I need to find all the strings that contain a specific substring and then modify those strings in a specific way? For example, if the substring is \"cat\", and I want to prepend \"feline-\" to each string contain... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4878,
"level": 1,
"question": "Can you help me with a Python function to process a list of strings, where I need to find all the strings that contain a specific substring and then modify those strings in a specific way? For example, if the substring is \"cat\", and I want to prepend... |
def dailyTemperatures(temperatures):
n = len(temperatures)
result = [0] * n
stack = []
for i in range(n):
while stack and temperatures[i] > temperatures[stack[-1]]:
j = stack.pop()
result[j] = i - j
stack.append(i)
return result | simplelr_Apps | [
{
"content": "Question:\n# Detail\n\nYou are given an array of integers representing the daily temperatures, where temperatures[i] is the temperature on the ith day. You need to return an array answer such that answer[i] is the number of days you would have to wait after the ith day to get a warmer temperature.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4879,
"level": 1,
"question": "# Detail\n\nYou are given an array of integers representing the daily temperatures, where temperatures[i] is the temperature on the ith day. You need to return an array answer such that answer[i] is the number of days you would have to wait after the i... |
import math
def custom_fizz_buzz(n, div1, div2, word_map):
# Compute the least common multiple (LCM) of div1 and div2
gcd = math.gcd(div1, div2)
lcm = (div1 * div2) // gcd
result = []
for i in range(1, n + 1):
if i % lcm == 0:
if lcm in word_map:
result.appe... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with writing a function that simulates a basic version of the popular \"FizzBuzz\" problem, but with custom string substitutions for multiples.\n\nThe function should be named `custom_fizz_buzz` and should take four parameters:\n1. `n`: An integer representing the count u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4880,
"level": 1,
"question": "You are tasked with writing a function that simulates a basic version of the popular \"FizzBuzz\" problem, but with custom string substitutions for multiples.\n\nThe function should be named `custom_fizz_buzz` and should take four parameters:\n1. `n`: ... |
def longest_consecutive(arr):
num_set = set(arr)
max_length = 0
for num in num_set:
if (num - 1) not in num_set:
current_length = 1
current_num = num
while (current_num + 1) in num_set:
current_length += 1
current_num += 1
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the length of the longest consecutive elements sequence in an unsorted array of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4881,
"level": 1,
"question": "Write a function to find the length of the longest consecutive elements sequence in an unsorted array of integers.",
"split": "train"
} |
from typing import List
def simulated_selection_sort(arr: List[int]) -> List[int]:
arr = arr.copy()
print(f"Iteration 0: {' '.join(map(str, arr))}")
for i in range(len(arr) - 1):
min_idx = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem: Simulated Selection Sort\n\nGiven an array of integers, implement the selection sort algorithm that prints the array after each iteration of the main loop to simulate its progress.\n\n#### Function Signature\n```python\ndef simulated_selection_sort(arr: List[int]) -> List[i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4882,
"level": 1,
"question": "### Problem: Simulated Selection Sort\n\nGiven an array of integers, implement the selection sort algorithm that prints the array after each iteration of the main loop to simulate its progress.\n\n#### Function Signature\n```python\ndef simulated_selec... |
def sum_of_odds(a, b):
start = min(a, b)
end = max(a, b)
return sum(num for num in range(start, end + 1) if num % 2 != 0) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the sum of all odd numbers between two given numbers (inclusive).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4883,
"level": 1,
"question": "Write a python function to calculate the sum of all odd numbers between two given numbers (inclusive).",
"split": "train"
} |
from collections import Counter
def find_duplicates(lst):
counts = Counter(lst)
return [k for k, v in counts.items() if v > 1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the duplicate elements of a given list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4884,
"level": 1,
"question": "Write a python function to find the duplicate elements of a given list.",
"split": "train"
} |
def unique_elements(arr):
seen = set()
result = []
for num in arr:
if num not in seen:
seen.add(num)
result.append(num)
return result | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes an integer array as input and returns a new array containing only the unique elements from the original array, in the order that they first appeared. Do not use any built-in functions that directly perform this task. \n\nExample:\nInput: [4, 5, 9, 4, 5, 6, 7,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4885,
"level": 1,
"question": "Write a function that takes an integer array as input and returns a new array containing only the unique elements from the original array, in the order that they first appeared. Do not use any built-in functions that directly perform this task. \n\nExa... |
def intersection(list1, list2):
set1 = set(list1)
set2 = set(list2)
common = set1.intersection(set2)
return list(common) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the intersection of two lists. The function should take two lists as input and return a list containing the common elements. The returned list should not contain any duplicates. For example, the intersection of [1, 2, 3, 4] and [3, 4, 5, 6] is [3, 4].\nAn... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4886,
"level": 1,
"question": "Write a Python function to find the intersection of two lists. The function should take two lists as input and return a list containing the common elements. The returned list should not contain any duplicates. For example, the intersection of [1, 2, 3,... |
from collections import Counter
def findExtraChar(s: str, t: str) -> str:
count = Counter(s)
for char in t:
if count[char] > 0:
count[char] -= 1
else:
return char
| simplelr_Taco | [
{
"content": "Question:\nYou are given two strings, `s` and `t`, where `t` is formed by shuffling the characters of `s` and then adding one additional character somewhere in the shuffled string. Write a function to find the extra character in `t`.\n\nFunction Description:\n\nComplete the function findExtraChar ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4887,
"level": 1,
"question": "You are given two strings, `s` and `t`, where `t` is formed by shuffling the characters of `s` and then adding one additional character somewhere in the shuffled string. Write a function to find the extra character in `t`.\n\nFunction Description:\n\nC... |
def arrange_scores(scores, order):
return [scores[id] for id in order] | simplelr_Leetcode | [
{
"content": "Question:\nA classroom is organizing a line-up competition where students need to stand in a specific order according to their scores. Each student is identified by their unique ID.\n\nGiven an array of integers `scores` where `scores[i]` represents the score of the student with `ID i`, and an arr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4888,
"level": 1,
"question": "A classroom is organizing a line-up competition where students need to stand in a specific order according to their scores. Each student is identified by their unique ID.\n\nGiven an array of integers `scores` where `scores[i]` represents the score of ... |
def calculate_power_modulo(a, b, m):
result = 1
a = a % m # Reduce 'a' modulo 'm' to simplify calculations
while b > 0:
if b % 2 == 1:
result = (result * a) % m
a = (a * a) % m
b = b // 2
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function named `calculate_power_modulo` that calculates \\(a^b \\mod m\\) efficiently. This function should use a more efficient algorithm than the naive approach of multiplying `a` by itself `b` times and then taking the modulo `m`. Utilize the property that \\(a^{b/2} \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4889,
"level": 1,
"question": "Write a Python function named `calculate_power_modulo` that calculates \\(a^b \\mod m\\) efficiently. This function should use a more efficient algorithm than the naive approach of multiplying `a` by itself `b` times and then taking the modulo `m`. Uti... |
from typing import List
def find_missing_number(arr: List[int]) -> int:
n = len(arr)
if n < 2:
return None # This case is not possible as per the problem constraints
possible_ds = set()
# Consider the first few differences as possible d candidates
for i in range(min(3, n - 1)):
... | simplelr_Algorithm | [
{
"content": "Question:\n### Find Missing Number in Arithmetic Progression\n\n#### Problem Statement\nGiven a list of `n` integers that form an arithmetic progression but are missing exactly one element, write a function `find_missing_number(arr: List[int]) -> int` that identifies and returns the missing number... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4890,
"level": 1,
"question": "### Find Missing Number in Arithmetic Progression\n\n#### Problem Statement\nGiven a list of `n` integers that form an arithmetic progression but are missing exactly one element, write a function `find_missing_number(arr: List[int]) -> int` that identi... |
def first_non_repeating_character(s):
counts = {}
for char in s:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
for char in s:
if counts[char] == 1:
return char
return None | simplelr_Filter | [
{
"content": "Question:\nThis code defines a function that takes a string as input and returns the first non-repeating character in the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4891,
"level": 1,
"question": "This code defines a function that takes a string as input and returns the first non-repeating character in the string.",
"split": "train"
} |
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif target < arr[mid]:
high = mid - 1
else:
low = mid + 1
return -1 | simplelr_Algorithm | [
{
"content": "Question:\n**Scenario**:\nYour development team is tasked with improving the efficiency of an inventory management system. One of the critical parts of the system involves locating specific items in a large inventory dataset. This dataset can be in the form of a sorted list, and you need to implem... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4892,
"level": 1,
"question": "**Scenario**:\nYour development team is tasked with improving the efficiency of an inventory management system. One of the critical parts of the system involves locating specific items in a large inventory dataset. This dataset can be in the form of a ... |
from typing import List
def replace_borders(matrix: List[List[int]]) -> List[List[int]]:
if not matrix:
return []
m = len(matrix)
n = len(matrix[0]) if m > 0 else 0
borders = []
for i in range(m):
if i == 0 or i == m - 1:
borders.extend(matrix[i])
else:... | simplelr_Package | [
{
"content": "Question:\nGiven a matrix of integers representing a 2D grid, write a function `replace_borders(matrix)` that replaces the border elements of the matrix with the largest integer within the border. Assume the matrix is non-empty and contains at least one row and one column.\n\n### Function Signatur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4893,
"level": 1,
"question": "Given a matrix of integers representing a 2D grid, write a function `replace_borders(matrix)` that replaces the border elements of the matrix with the largest integer within the border. Assume the matrix is non-empty and contains at least one row and o... |
def merge_sorted_arrays(arr1: list[int], arr2: list[int]) -> list[int]:
i = j = 0
merged = []
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
merged.append(arr1[i])
i += 1
else:
merged.append(arr2[j])
j += 1
merged.extend(arr1... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question: Merge Two Sorted Arrays\n\n#### Context\nMerging two sorted arrays into one sorted array is a fundamental programming problem that helps in understanding array manipulations and handling edge cases efficiently.\n\n#### Problem Statement\nWrite a function `merge_sort... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4894,
"level": 1,
"question": "### Coding Question: Merge Two Sorted Arrays\n\n#### Context\nMerging two sorted arrays into one sorted array is a fundamental programming problem that helps in understanding array manipulations and handling edge cases efficiently.\n\n#### Problem Stat... |
from collections import Counter
def can_transform_by_swaps(str1: str, str2: str) -> bool:
return Counter(str1) == Counter(str2) | simplelr_Algorithm | [
{
"content": "Question:\n### String Permutations with Character Swaps\n\n#### Context:\nYou are given two strings of equal length consisting only of lowercase letters. Your goal is to determine if one string can be transformed into the other by swapping any two characters in the string any number of times.\n\n#... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4895,
"level": 1,
"question": "### String Permutations with Character Swaps\n\n#### Context:\nYou are given two strings of equal length consisting only of lowercase letters. Your goal is to determine if one string can be transformed into the other by swapping any two characters in t... |
def char_frequency(s):
counts = {}
for char in s:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
return counts | simplelr_Filter | [
{
"content": "Question:\nYou are given a string containing only lowercase letters and spaces.\n\nTask:\n- Count the frequency of each character (including spaces) in the string.\n\nExample:\n\nInput: \"hello world\"\n\nOutput:\n{\n'h': 1,\n'e': 1,\n'l': 3,\n'o': 2,\n' ': 1,\n'w': 1,\n'r': 1,\n'd': 1\n\n}\n\nCan... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4896,
"level": 1,
"question": "You are given a string containing only lowercase letters and spaces.\n\nTask:\n- Count the frequency of each character (including spaces) in the string.\n\nExample:\n\nInput: \"hello world\"\n\nOutput:\n{\n'h': 1,\n'e': 1,\n'l': 3,\n'o': 2,\n' ': 1,\n'... |
# Sample list of numbers
numbers = [1, 2, 3, 4]
# Method 1: Manual calculation
def cumulative_sum(numbers):
cumulative_sum = []
running_total = 0
for num in numbers:
running_total += num
cumulative_sum.append(running_total)
return cumulative_sum
# Method 2: Using itertools.accumulate
f... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code example to calculate the cumulative sum of a list of numbers?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4897,
"level": 1,
"question": "Can you provide a Python code example to calculate the cumulative sum of a list of numbers?",
"split": "train"
} |
def isArithmeticProgression(nums):
n = len(nums)
if n <= 1:
return True
diff = nums[1] - nums[0]
for i in range(2, n):
if nums[i] - nums[i-1] != diff:
return False
return True | simplelr_Apps | [
{
"content": "Question:\nGiven a list of integers, determine whether the list forms an arithmetic progression or not. An arithmetic progression is a sequence of numbers in which the difference of any two successive members is a constant.\n\nWrite a function `isArithmeticProgression(nums)` that takes a list of i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4898,
"level": 1,
"question": "Given a list of integers, determine whether the list forms an arithmetic progression or not. An arithmetic progression is a sequence of numbers in which the difference of any two successive members is a constant.\n\nWrite a function `isArithmeticProgre... |
def min_total_travel_distance(positions):
if not positions:
return 0
sorted_positions = sorted(positions)
n = len(sorted_positions)
median = sorted_positions[n // 2]
total = sum(abs(x - median) for x in sorted_positions)
return total
| simplelr_Taco | [
{
"content": "Question:\nDescription\nA delivery company has deployed autonomous robots to deliver packages. Each robot is initially at position 0 on an infinite number line. You need to program a function to calculate the minimum total distance that all robots need to travel in order to deliver packages to spe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4899,
"level": 1,
"question": "Description\nA delivery company has deployed autonomous robots to deliver packages. Each robot is initially at position 0 on an infinite number line. You need to program a function to calculate the minimum total distance that all robots need to travel ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.