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 sort_digits(n):
str_n = str(n)
sorted_str_n = ''.join(sorted(str_n))
return sorted_str_n | simplelr_Filter | [
{
"content": "Question:\nYou've been tasked with creating a function that converts a given integer into a string and then sorts the digits of the string in ascending order. The function should take an integer as input, convert it to a string, sort the digits in ascending order, and return the sorted string.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5100,
"level": 1,
"question": "You've been tasked with creating a function that converts a given integer into a string and then sorts the digits of the string in ascending order. The function should take an integer as input, convert it to a string, sort the digits in ascending order... |
import numpy as np
def matrix_rotate(matrix: np.ndarray) -> np.ndarray:
return np.rot90(matrix, k=-1) | simplelr_Package | [
{
"content": "Question:\nIn this problem, you are tasked with implementing a function `matrix_rotate` that rotates a given square matrix by 90 degrees clockwise. This function emphasizes understanding and manipulating 2-dimensional arrays using the numpy library.\n\n### Function Signature\n```python\nimport num... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5101,
"level": 1,
"question": "In this problem, you are tasked with implementing a function `matrix_rotate` that rotates a given square matrix by 90 degrees clockwise. This function emphasizes understanding and manipulating 2-dimensional arrays using the numpy library.\n\n### Functi... |
def count_vowels(string):
"""Counts the number of vowels in a string.
Args:
string: The string to count vowels in.
Returns:
The number of vowels in the string.
"""
vowels = "aeiouAEIOU"
count = 0
for char in string:
if char in vowels:
count += 1
retu... | simplelr_Filter | [
{
"content": "Question:\nThis is the problem:\n\n> Write a function called `count_vowels` that takes a string as input and returns the number of vowels in the string.\n\nHere are some examples:\n\n* `count_vowels(\"hello\")` should return `2`\n* `count_vowels(\"world\")` should return `1`\n* `count_vowels(\"pro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5102,
"level": 1,
"question": "This is the problem:\n\n> Write a function called `count_vowels` that takes a string as input and returns the number of vowels in the string.\n\nHere are some examples:\n\n* `count_vowels(\"hello\")` should return `2`\n* `count_vowels(\"world\")` shoul... |
def compute_custom_difference(numbers, ignore_low=0, ignore_high=0):
# Ensure ignore_low and ignore_high are non-negative
ignore_low = max(ignore_low, 0)
ignore_high = max(ignore_high, 0)
if not numbers:
return 0
sorted_numbers = sorted(numbers)
n = len(sorted_numbers)
... | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function that computes the difference between the highest and lowest values in a provided list of numbers, but with a twist: the function should allow for ignoring a specified number of highest and lowest values when calculating this difference. For instance, if the user... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5103,
"level": 1,
"question": "Design a Python function that computes the difference between the highest and lowest values in a provided list of numbers, but with a twist: the function should allow for ignoring a specified number of highest and lowest values when calculating this di... |
from typing import List
def min_operations_to_front(queue: List[int], target: int) -> int:
n = len(queue)
min_ops = float('inf')
for i in range(n):
if queue[i] == target:
left = i
right = (n - i) % n
current_min = min(left, right)
if current_min < min... | simplelr_Taco | [
{
"content": "Question:\nGiven a queue represented as a list, implement a function that takes two arguments: the queue and a target number. The function should return the minimum number of operations required to bring the target number to the front of the queue. \n\nYou can perform two types of operations:\n1. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5104,
"level": 1,
"question": "Given a queue represented as a list, implement a function that takes two arguments: the queue and a target number. The function should return the minimum number of operations required to bring the target number to the front of the queue. \n\nYou can pe... |
def sum_integers_from_file():
with open('numbers.txt', 'r') as file:
numbers = [int(line.strip()) for line in file]
return sum(numbers) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that reads a file containing a list of integers and calculates the sum of these integers. The file is named 'numbers.txt' and is located in the same directory as the script. The integers are stored in the file, one per line.\nAnswer:\nLet's think step by step.\n"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5105,
"level": 1,
"question": "Write a Python function that reads a file containing a list of integers and calculates the sum of these integers. The file is named 'numbers.txt' and is located in the same directory as the script. The integers are stored in the file, one per line.",
... |
import os
def copy_environment_file(env_var_name: str, filename: str) -> bool:
env_var_value = os.getenv(env_var_name)
if env_var_value is None:
return False
src_fd = None
dest_fd = None
try:
# Open the source file for reading
src_fd = os.open(env_var_value, os.O_RDONLY)
... | simplelr_Docs | [
{
"content": "Question:\n## Coding Assessment Question\n\n### Objective:\nImplement a Python function that demonstrates proficiency in handling environment variables, managing file descriptors, and interacting with the file system using the `os` module.\n\n### Problem Statement:\nUsing Python's `os` module, wri... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5106,
"level": 1,
"question": "## Coding Assessment Question\n\n### Objective:\nImplement a Python function that demonstrates proficiency in handling environment variables, managing file descriptors, and interacting with the file system using the `os` module.\n\n### Problem Statemen... |
def count_valid_words(words, allowed):
count = 0
for word in words:
valid = True
for c in word:
if c not in allowed:
valid = False
break
if valid:
count += 1
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `words` and a set of characters `allowed`. Your task is to find the number of words that can be constructed using only the characters in `allowed`. Note that each character in `allowed` can be used multiple times in constructing a word. \n\nReturn the count of va... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5107,
"level": 1,
"question": "You are given a list of `words` and a set of characters `allowed`. Your task is to find the number of words that can be constructed using only the characters in `allowed`. Note that each character in `allowed` can be used multiple times in constructing... |
def word_break(word: str, word_dict: set) -> bool:
n = len(word)
dp = [False] * (n + 1)
dp[0] = True
for i in range(1, n + 1):
for j in range(i):
if dp[j] and word[j:i] in word_dict:
dp[i] = True
break
return dp[n] | simplelr_Data_Structure | [
{
"content": "Question:\n### Word Segmentation Using Dynamic Programming\n\n**Objective**: Write a function to determine if a given string can be segmented into a space-separated sequence of one or more dictionary words.\n\n### Function Signature\n```python\ndef word_break(word: str, word_dict: set) -> bool:\n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5108,
"level": 1,
"question": "### Word Segmentation Using Dynamic Programming\n\n**Objective**: Write a function to determine if a given string can be segmented into a space-separated sequence of one or more dictionary words.\n\n### Function Signature\n```python\ndef word_break(wor... |
def MinCoins(denominations, amount):
if amount == 0:
return 0
# Initialize dp array where dp[i] will hold the minimum coins needed for amount i
dp = [float('inf')] * (amount + 1)
dp[0] = 0 # Base case: 0 coins needed to make 0 amount
unique_denoms = list(set(denominations)) # Remove duplic... | simplelr_Taco | [
{
"content": "Question:\nYou are given a set of denominations for an infinite supply of coins and a target amount. Your task is to determine the fewest number of coins needed to make up the given amount. If the target amount cannot be reached using the given denominations, return -1. For example, if the denomin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5109,
"level": 1,
"question": "You are given a set of denominations for an infinite supply of coins and a target amount. Your task is to determine the fewest number of coins needed to make up the given amount. If the target amount cannot be reached using the given denominations, ret... |
from functools import lru_cache
@lru_cache(maxsize=None)
def climb_stairs(n, k):
if n == 0:
return 1
total = 0
for i in range(1, k + 1):
if n - i >= 0:
total += climb_stairs(n - i, k)
return total | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to climb a staircase using recursion. The function should take two parameters: the total number of steps in the staircase (n) and the maximum number of steps one can advance at a time (k). The function should return the number of distinct ways one can climb the s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5110,
"level": 1,
"question": "Write a python function to climb a staircase using recursion. The function should take two parameters: the total number of steps in the staircase (n) and the maximum number of steps one can advance at a time (k). The function should return the number o... |
def sort_books(titles):
return sorted(titles, key=str.lower)
| simplelr_Taco | [
{
"content": "Question:\nAlyssa loves to organize her books in alphabetical order to make it easier to find them. However, she has a habit of quickly putting away her books without following any particular order, creating a mess. Every weekend, she dedicates time to reorganize her bookshelf.\n\nAlyssa has asked... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5111,
"level": 1,
"question": "Alyssa loves to organize her books in alphabetical order to make it easier to find them. However, she has a habit of quickly putting away her books without following any particular order, creating a mess. Every weekend, she dedicates time to reorganize... |
def three_sum(nums):
nums.sort()
res = []
n = len(nums)
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left = i + 1
right = n - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
if current_sum ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of `n` integers, return all unique triplets in the list that sum up to zero. Each triplet in the output must be sorted in ascending order, and the output must not contain duplicate triplets. The function should return a list of lists, where each inner list is the triplet of... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5112,
"level": 1,
"question": "Given a list of `n` integers, return all unique triplets in the list that sum up to zero. Each triplet in the output must be sorted in ascending order, and the output must not contain duplicate triplets. The function should return a list of lists, wher... |
def even_indexed_chars(s):
return s[::2] | simplelr_Filter | [
{
"content": "Question:\nThis project involves writing a Python function that takes a string as input and returns a new string that contains only the even-indexed characters of the input string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5113,
"level": 1,
"question": "This project involves writing a Python function that takes a string as input and returns a new string that contains only the even-indexed characters of the input string.",
"split": "train"
} |
def trap_water(arr):
if not arr:
return 0
n = len(arr)
left_max = [0] * n
right_max = [0] * n
# Compute left_max
current_max = 0
for i in range(n):
left_max[i] = current_max
current_max = max(current_max, arr[i])
# Compute right_max
current_max = 0
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr` where each element `arr[i]` represents the height of a building on that day, return _the maximum amount of water that can be trapped between the buildings_. The buildings can trap water between them based on their height differences, and you need to cal... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5114,
"level": 1,
"question": "Given an array of integers `arr` where each element `arr[i]` represents the height of a building on that day, return _the maximum amount of water that can be trapped between the buildings_. The buildings can trap water between them based on their heig... |
import syslog
def custom_syslog(log_id: str, log_option: int, log_facility: int, messages: list) -> None:
# Initialize the syslog with the given parameters
syslog.openlog(ident=log_id, logoption=log_option, facility=log_facility)
# Iterate through each message and its priority
for message, priorit... | simplelr_Docs | [
{
"content": "Question:\n**Question: Implement a Logging System Using the `syslog` Module**\n\nAs a systems programmer, your task is to implement a Python function that uses the Unix `syslog` library to log various types of system messages. The function should be capable of initializing the syslog with specific... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5115,
"level": 1,
"question": "**Question: Implement a Logging System Using the `syslog` Module**\n\nAs a systems programmer, your task is to implement a Python function that uses the Unix `syslog` library to log various types of system messages. The function should be capable of in... |
def sum_of_unique_numbers(lst):
unique_numbers = set(lst)
return sum(unique_numbers) | simplelr_Filter | [
{
"content": "Question:\nPlease provide a Python code snippet to calculate the sum of all unique numbers in a list. For example, the sum of unique numbers in the list [1, 2, 3, 2, 1] is 1 + 2 + 3 = 6.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5116,
"level": 1,
"question": "Please provide a Python code snippet to calculate the sum of all unique numbers in a list. For example, the sum of unique numbers in the list [1, 2, 3, 2, 1] is 1 + 2 + 3 = 6.",
"split": "train"
} |
def sort_string(s):
return ''.join(sorted(s)) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and returns the string with the characters sorted in ascending order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5117,
"level": 1,
"question": "Create a function that takes a string as input and returns the string with the characters sorted in ascending order.",
"split": "train"
} |
def sum_of_max_min(lst):
return max(lst) + min(lst) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns the sum of the maximum and minimum elements in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5118,
"level": 1,
"question": "Create a function that takes a list of integers and returns the sum of the maximum and minimum elements in the list.",
"split": "train"
} |
def find_smallest_missing_code(nums):
s = set()
for num in nums:
if num > 0:
s.add(num)
if not s:
return 1
if 1 not in s:
return 1
current = 2
while current in s:
current += 1
return current
| simplelr_Taco | [
{
"content": "Question:\n## Background:\n\nYou have been tasked with managing the inventory of a toy store. The inventory system tracks each toy by a unique code that has been generated sequentially starting from 1. Due to a recent system malfunction, some of the toy codes have been corrupted, leaving gaps in t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5119,
"level": 1,
"question": "## Background:\n\nYou have been tasked with managing the inventory of a toy store. The inventory system tracks each toy by a unique code that has been generated sequentially starting from 1. Due to a recent system malfunction, some of the toy codes hav... |
from typing import List
def subarray_sum(nums: List[int], k: int) -> int:
prefix_counts = {0: 1}
current_sum = 0
count = 0
for num in nums:
current_sum += num
count += prefix_counts.get(current_sum - k, 0)
prefix_counts[current_sum] = prefix_counts.get(current_sum, 0) + 1
re... | simplelr_Algorithm | [
{
"content": "Question:\n**Question**: Subarray Sum Equals K\n\nGiven an array of integers and an integer `k`, you need to find the total number of continuous subarrays whose sum equals to `k`. Your task is to write a function that computes this total.\n\n### Function Signature\n```python\ndef subarray_sum(nums... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5120,
"level": 1,
"question": "**Question**: Subarray Sum Equals K\n\nGiven an array of integers and an integer `k`, you need to find the total number of continuous subarrays whose sum equals to `k`. Your task is to write a function that computes this total.\n\n### Function Signatur... |
def count_vowels(s):
count = 0
for c in s:
if c.isalpha():
if c.lower() in {'a', 'e', 'i', 'o', 'u'}:
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\nI have a string, and I want to write a Python function that counts the number of vowels in that string, excluding any non-alphabet characters (such as punctuation and spaces). How can I do this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5121,
"level": 1,
"question": "I have a string, and I want to write a Python function that counts the number of vowels in that string, excluding any non-alphabet characters (such as punctuation and spaces). How can I do this?",
"split": "train"
} |
def to_uppercase(s):
return ''.join([c.upper() if c.isalpha() else c for c in s]) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to convert a given string to uppercase. If the string contains non-alphabetic characters, ignore them but keep the case of the alphabetic characters intact. For example, \"Hello, World!\" should be converted to \"HELLO, WORLD!\".\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5122,
"level": 1,
"question": "Write a function to convert a given string to uppercase. If the string contains non-alphabetic characters, ignore them but keep the case of the alphabetic characters intact. For example, \"Hello, World!\" should be converted to \"HELLO, WORLD!\".",
"... |
def filter_palindromes(identifiers):
return [s for s in identifiers if s == s[::-1]] | simplelr_Filter | [
{
"content": "Question:\nI'm working on a project that involves identifying unique identifiers in a dataset. The identifiers are strings of characters, and I need to filter out those that are palindromes. How can I write a Python function that takes a list of strings and returns a new list containing only the p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5123,
"level": 1,
"question": "I'm working on a project that involves identifying unique identifiers in a dataset. The identifiers are strings of characters, and I need to filter out those that are palindromes. How can I write a Python function that takes a list of strings and retur... |
def trap(heights):
if not heights:
return 0
left = 0
right = len(heights) - 1
max_left = 0
max_right = 0
water = 0
while left <= right:
if heights[left] <= heights[right]:
if heights[left] >= max_left:
max_left = heights[left]
else:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `heights` representing the heights of columns where the width of each column is 1. Compute how much water can be trapped after raining if the columns form a histogram. The function should return an integer representing the total units of trapped water.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5124,
"level": 1,
"question": "You are given an array of integers `heights` representing the heights of columns where the width of each column is 1. Compute how much water can be trapped after raining if the columns form a histogram. The function should return an integer representin... |
def unique_sorted_characters(str1, str2):
combined = str1 + str2
unique_chars = set(combined)
sorted_chars = sorted(unique_chars)
return sorted_chars | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two strings as input and returns a new sorted list of characters, which contains all unique characters from both strings.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5125,
"level": 1,
"question": "Create a function that takes two strings as input and returns a new sorted list of characters, which contains all unique characters from both strings.",
"split": "train"
} |
def sum_of_digits(n):
if n < 0:
reversed_str = str(abs(n))[::-1]
else:
reversed_str = str(n)
total = 0
for c in reversed_str:
total += int(c)
return total | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to return the sum of the digits in a integer number. If the integer number is negative, first reverse the number and then sum the digits.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5126,
"level": 1,
"question": "Write a python function to return the sum of the digits in a integer number. If the integer number is negative, first reverse the number and then sum the digits.",
"split": "train"
} |
def max_binary_indexes(binary_list: list[str]) -> list[int]:
max_value = -1
indexes = []
for index, binary_str in enumerate(binary_list):
current_value = int(binary_str, 2)
if current_value > max_value:
max_value = current_value
indexes = [index]
elif current_... | simplelr_Package | [
{
"content": "Question:\n#### Background:\nYou are given a list of strings where each string represents a binary number. Your task is to find the binary number (as a string) with the highest decimal value and return a list of indexes where this maximum binary number appears in the original list.\n\n#### Task:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5127,
"level": 1,
"question": "#### Background:\nYou are given a list of strings where each string represents a binary number. Your task is to find the binary number (as a string) with the highest decimal value and return a list of indexes where this maximum binary number appears in... |
def merge_lists_to_dict(list1, list2):
result_dict = {}
for key, value in zip(list1, list2):
if value % 3 == 0:
if key in result_dict:
current_value = result_dict[key]
if isinstance(current_value, list):
current_value.append(value)
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to merge two lists of equal length into a dictionary, but the dictionary should only include elements from list1 that have a corresponding element in list2 that is divisible by 3. If there is a repeating element in list1, it should be stored as a list of correspo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5128,
"level": 1,
"question": "Write a Python function to merge two lists of equal length into a dictionary, but the dictionary should only include elements from list1 that have a corresponding element in list2 that is divisible by 3. If there is a repeating element in list1, it sho... |
import csv
def update_websites(filename):
try:
# Read the CSV file
with open(filename, 'r') as file:
reader = csv.reader(file)
websites = list(reader)
except FileNotFoundError:
print(f"The file {filename} does not exist.")
return False
except Permissi... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python script that reads a list of websites from a CSV file, checks if each website starts with \"https://\" or \"http://\", and if not, adds \"http://\" to the beginning. Then the script should save the updated list back to the same CSV file. Please provide the Python script a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5129,
"level": 1,
"question": "Create a Python script that reads a list of websites from a CSV file, checks if each website starts with \"https://\" or \"http://\", and if not, adds \"http://\" to the beginning. Then the script should save the updated list back to the same CSV file.... |
def evaluate_rpn(expression):
tokens = expression.split()
stack = []
for token in tokens:
if token in '+-*/':
b = stack.pop()
a = stack.pop()
if token == '+':
stack.append(a + b)
elif token == '-':
stack.append(a - b)
... | simplelr_Apps | [
{
"content": "Question:\nImplement a function that evaluates RPN (Reverse Polish Notation) expressions. Reverse Polish Notation is a mathematical notation in which every operator follows all of its operands. This notation eliminates the need for parentheses to define operation order.\n\nFor example, the RPN exp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5130,
"level": 1,
"question": "Implement a function that evaluates RPN (Reverse Polish Notation) expressions. Reverse Polish Notation is a mathematical notation in which every operator follows all of its operands. This notation eliminates the need for parentheses to define operation... |
def generate_histogram(frequencies: list[int]) -> list[str]:
histogram = []
for index, freq in enumerate(frequencies):
row = f"{index}: {'*' * freq}"
histogram.append(row)
return histogram | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are tasked with creating a function that generates a text-based histogram from an input list of integers. Each integer represents the frequency of occurrence of an event, and the histogram should visually represent these frequencies using asterisks (`*`).\n\n#... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5131,
"level": 1,
"question": "### Problem Statement\nYou are tasked with creating a function that generates a text-based histogram from an input list of integers. Each integer represents the frequency of occurrence of an event, and the histogram should visually represent these freq... |
from typing import List
from collections import Counter
def is_shuffled_version(list1: List[int], list2: List[int]) -> bool:
if len(list1) != len(list2):
return False
return Counter(list1) == Counter(list2) | simplelr_Algorithm | [
{
"content": "Question:\n### Array Shuffling Validator\n\n#### Context\nIn data analysis and machine learning, it's essential to ensure the randomness of data ordering to avoid biased training in models. A common method to achieve randomness in data ordering is shuffling. The randomness can be validated by stat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5132,
"level": 1,
"question": "### Array Shuffling Validator\n\n#### Context\nIn data analysis and machine learning, it's essential to ensure the randomness of data ordering to avoid biased training in models. A common method to achieve randomness in data ordering is shuffling. The ... |
def does_robot_return(commands):
x = 0
y = 0
for c in commands:
if c == 'U':
y += 1
elif c == 'D':
y -= 1
elif c == 'R':
x += 1
elif c == 'L':
x -= 1
return "YES" if x == 0 and y == 0 else "NO" | simplelr_Codeforces | [
{
"content": "Question:\nA robot can move in a 2D grid starting from the origin (0, 0). The robot can receive a sequence of commands consisting of the letters 'U', 'D', 'L', and 'R', which stand for up, down, left, and right, respectively. Each command moves the robot one unit in the corresponding direction. Th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5133,
"level": 1,
"question": "A robot can move in a 2D grid starting from the origin (0, 0). The robot can receive a sequence of commands consisting of the letters 'U', 'D', 'L', and 'R', which stand for up, down, left, and right, respectively. Each command moves the robot one unit... |
def autocomplete(dictionary: list[str], prefix: str) -> list[str]:
matches = [word for word in dictionary if word.startswith(prefix)]
matches.sort()
return matches | simplelr_Algorithm | [
{
"content": "Question:\n### Question:\n\nYou are tasked with developing an algorithm for autocomplete functionality, which suggests words based on a given prefix. For simplicity, we'll use a dictionary that contains a list of words.\n\nYour goal is to implement the `autocomplete` function that returns all word... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5134,
"level": 1,
"question": "### Question:\n\nYou are tasked with developing an algorithm for autocomplete functionality, which suggests words based on a given prefix. For simplicity, we'll use a dictionary that contains a list of words.\n\nYour goal is to implement the `autocompl... |
def reverse_list_in_place(lst):
lst.reverse() | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and reverses the list in place. The input list should affect the original list, and the function should return nothing.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5135,
"level": 1,
"question": "Create a function that takes a list of integers and reverses the list in place. The input list should affect the original list, and the function should return nothing.",
"split": "train"
} |
from typing import List
def transpose_and_rotate(matrix: List[List[int]]) -> None:
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Rotate 90 degrees clockwise by reversing each row
for ... | simplelr_Algorithm | [
{
"content": "Question:\n### Matrix Transposition and Rotation\n\n**Context**: Transposition and rotation are fundamental operations that can be efficiently performed on matrices. These operations are commonly used in graphics, cryptography, and various data transformation tasks.\n\n**Task**: Write a function t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5136,
"level": 1,
"question": "### Matrix Transposition and Rotation\n\n**Context**: Transposition and rotation are fundamental operations that can be efficiently performed on matrices. These operations are commonly used in graphics, cryptography, and various data transformation tas... |
def duplicate_characters(s):
return ''.join([char * 2 for char in s]) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string, and returns a new string where every character in the original string is duplicated.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5137,
"level": 1,
"question": "Create a function that takes a string, and returns a new string where every character in the original string is duplicated.",
"split": "train"
} |
def string_to_ascii(input_string: str) -> list:
"""
Converts a given string into a list of its corresponding ASCII values.
Args:
input_string (str): The string to be converted into ASCII values.
Returns:
list: A list of integers, each representing the ASCII value of the corresponding c... | simplelr_Filter | [
{
"content": "Question:\nPlease write a Python function that converts a given string to its corresponding ASCII values. The function should accept a string as input and return a list of ASCII values. For example, if the input string is \"hello\", the output should be [104, 101, 108, 108, 111]. Ensure the functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5138,
"level": 1,
"question": "Please write a Python function that converts a given string to its corresponding ASCII values. The function should accept a string as input and return a list of ASCII values. For example, if the input string is \"hello\", the output should be [104, 101... |
def roman_to_integer(s: str) -> int:
"""
Convert a Roman numeral string to an integer.
:param s: A string representing a Roman numeral.
:return: The integer value of the Roman numeral.
"""
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
prev_valu... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question: Roman to Integer Conversion Optimized\n\n#### Background\nThe Roman numeral system uses combinations of letters from the Latin alphabet (I, V, X, L, C, D, M) to represent numbers. A Roman numeral is converted to an integer by summing the individual values, while acc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5139,
"level": 1,
"question": "### Coding Question: Roman to Integer Conversion Optimized\n\n#### Background\nThe Roman numeral system uses combinations of letters from the Latin alphabet (I, V, X, L, C, D, M) to represent numbers. A Roman numeral is converted to an integer by summi... |
def has_mirrored_pairs(arr):
seen = set()
for s in arr:
reversed_s = s[::-1]
if reversed_s in seen:
return True
seen.add(s)
return False | simplelr_Filter | [
{
"content": "Question:\nCreate a function to check if an array has any mirrored pairs. A mirrored pair consists of two elements which are reverse of each other. For example, in the array [\"cat\", \"dog\", \"god\", \"tac\"], (\"cat\", \"tac\") and (\"dog\", \"god\") are mirrored pairs. Make sure to account for... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5140,
"level": 1,
"question": "Create a function to check if an array has any mirrored pairs. A mirrored pair consists of two elements which are reverse of each other. For example, in the array [\"cat\", \"dog\", \"god\", \"tac\"], (\"cat\", \"tac\") and (\"dog\", \"god\") are mirro... |
def evaluate_postfix(expression):
stack = []
tokens = expression.split()
for token in tokens:
if token in '+-*/':
b = stack.pop()
a = stack.pop()
if token == '+':
res = a + b
elif token == '-':
res = a - b
el... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to parse a string containing a postfix expression and calculate its using stack. The input will be a space-separated string. For example, \"231*+\" represents the postfix expression (2+3)*1. The function should support basic operations: addition (+), subtraction (-), mu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5141,
"level": 1,
"question": "Write a function to parse a string containing a postfix expression and calculate its using stack. The input will be a space-separated string. For example, \"231*+\" represents the postfix expression (2+3)*1. The function should support basic operations... |
from typing import List
def comb_sort(arr: List[int]) -> List[int]:
n = len(arr)
if n <= 1:
return arr
gap = n
shrink = 1.3
swapped = True
while gap > 1 or swapped:
gap = int(gap / shrink)
if gap < 1:
gap = 1
swapped = False
for... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario:\nA small tech company is implementing a feature in their product where they need to sort user records based on their unique IDs efficiently. After some analysis, they decide to use Comb Sort as it offers a good balance between time complexity and implementation simplicity ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5142,
"level": 1,
"question": "### Scenario:\nA small tech company is implementing a feature in their product where they need to sort user records based on their unique IDs efficiently. After some analysis, they decide to use Comb Sort as it offers a good balance between time comple... |
def find_indices(nums, target):
indices = []
for index, value in enumerate(nums):
if value == target:
indices.append(index)
return indices | simplelr_Filter | [
{
"content": "Question:\nI have a list of integers, and I need to find all the indices of a specific target integer in the list.\n\nFor example, if I have a list of numbers like this: [3, 5, 2, 5, 7, 5, 8, 5], and I'm looking for the target integer 5, I want to get a list of indices where 5 appears in the list,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5143,
"level": 1,
"question": "I have a list of integers, and I need to find all the indices of a specific target integer in the list.\n\nFor example, if I have a list of numbers like this: [3, 5, 2, 5, 7, 5, 8, 5], and I'm looking for the target integer 5, I want to get a list of i... |
def length_of_lis(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp) | simplelr_Filter | [
{
"content": "Question:\nThis is a challenging problem in computer science\n\nThis is about dynamic programming\n\nI am stuck.\n\nHere's the problem:\n\nYou are given an array of integers 'nums'. \n\nFind the length of the *longest increasing subsequence* (LIS) within 'nums'.\n\nA subsequence is a sequence tha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5144,
"level": 1,
"question": "This is a challenging problem in computer science\n\nThis is about dynamic programming\n\nI am stuck.\n\nHere's the problem:\n\nYou are given an array of integers 'nums'. \n\nFind the length of the *longest increasing subsequence* (LIS) within 'nums'.... |
def two_sum(numbers, target):
seen = set()
for num in numbers:
complement = target - num
if complement in seen:
return (complement, num)
seen.add(num)
return None | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and a target integer as input. The function should return a tuple containing two distinct elements from the list that add up to the target, or None if no such pair exists. Assume that each input would have exactly one solution, and a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5145,
"level": 1,
"question": "Write a Python function that takes a list of integers and a target integer as input. The function should return a tuple containing two distinct elements from the list that add up to the target, or None if no such pair exists. Assume that each input wou... |
def unique_characters(s):
if len(s) == 0:
return ""
elif len(s) == 1:
return s
else:
unique = set(s)
sorted_unique = sorted(unique)
return ''.join(sorted_unique) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the unique characters in a given string. If the string is empty, return an empty string. If the string contains only one character, return that character. Otherwise, return a string composed of unique characters sorted in ascending order. Note that characters sh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5146,
"level": 1,
"question": "Write a function to find the unique characters in a given string. If the string is empty, return an empty string. If the string contains only one character, return that character. Otherwise, return a string composed of unique characters sorted in ascen... |
def largest_rectangle_area(arr):
if not arr:
return 0
stack = [-1] # Initialize stack with -1 to handle the base case
max_area = 0
n = len(arr)
for i in range(n):
# Maintain the stack to only keep indices with increasing heights
while stack[-1] != -1 and arr[i] < a... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` representing the heights of buildings in a skyline, where each building has a width of 1. The array is 0-indexed and the skyline extends infinitely to the left and right with a height of 0. Determine the maximum rectangle area conceivable within ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5147,
"level": 1,
"question": "You are given an array of integers `arr` representing the heights of buildings in a skyline, where each building has a width of 1. The array is 0-indexed and the skyline extends infinitely to the left and right with a height of 0. Determine the maximum... |
from collections import Counter
def longest_palindromic_substring_length(s):
counts = Counter(s)
sum_even_pairs = 0
odds = 0
for cnt in counts.values():
sum_even_pairs += (cnt // 2) * 2
if cnt % 2 != 0:
odds += 1
return sum_even_pairs + (1 if odds else 0) | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s`, you are allowed to re-arrange the characters of the string in any order, but you can only make a **single** re-arrangement. Determine the length of the longest palindromic substring that can be formed from the given string `s`. A palindromic substring is a substring ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5148,
"level": 1,
"question": "Given a string `s`, you are allowed to re-arrange the characters of the string in any order, but you can only make a **single** re-arrangement. Determine the length of the longest palindromic substring that can be formed from the given string `s`. A pa... |
def lexical_order(n):
nums = list(range(1, n + 1))
nums.sort(key=lambda x: str(x))
return nums | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer `n`, return an array `answer` that contains all the integers from `1` to `n` in lexicographical order. Lexicographical order is similar to the dictionary order in which words are arranged. For example, if `n = 13`, the output should be `[1, 10, 11, 12, 13, 2, 3, 4, 5, 6... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5149,
"level": 1,
"question": "Given an integer `n`, return an array `answer` that contains all the integers from `1` to `n` in lexicographical order. Lexicographical order is similar to the dictionary order in which words are arranged. For example, if `n = 13`, the output should be... |
import numpy as np
def inverse_gauss_jordan(a: np.ndarray) -> np.ndarray:
"""
Compute the inverse of matrix A using Gauss-Jordan elimination.
Arguments:
a -- a numpy.ndarray of shape (n, n)
Returns:
A_inv -- a numpy.ndarray of shape (n, n) representing the inverse of A
"""
n = a.shape... | simplelr_Algorithm | [
{
"content": "Question:\n### Matrix Inversion using Gauss-Jordan Elimination\n\nGiven a square matrix `A` of dimension n x n as a numpy array, your task is to find the inverse of `A` using the Gauss-Jordan elimination method. The goal is to compute a matrix `A_inv` such that `A @ A_inv` is approximately the ide... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5150,
"level": 1,
"question": "### Matrix Inversion using Gauss-Jordan Elimination\n\nGiven a square matrix `A` of dimension n x n as a numpy array, your task is to find the inverse of `A` using the Gauss-Jordan elimination method. The goal is to compute a matrix `A_inv` such that `... |
from collections import Counter
def most_frequent_element(lst):
if not lst:
return None
count = Counter()
first_occurrence = {}
for idx, num in enumerate(lst):
if num not in count:
count[num] = 1
first_occurrence[num] = idx
else:
count[num] +=... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to return the most frequent element in a list. If there are multiple elements with the same highest frequency, return the one that appears first in the list. If the list is empty, return None.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5151,
"level": 1,
"question": "Write a python function to return the most frequent element in a list. If there are multiple elements with the same highest frequency, return the one that appears first in the list. If the list is empty, return None.",
"split": "train"
} |
from collections import Counter
def can_form_palindrome(s):
n = len(s)
counts = Counter(s)
odd_counts = sum(1 for cnt in counts.values() if cnt % 2 != 0)
if n % 2 == 0:
return odd_counts == 0
else:
return odd_counts == 1 | simplelr_Apps | [
{
"content": "Question:\n=====Problem Statement=====\nWrite a function that determines if it is possible to rearrange the characters of a given string to form a palindrome. If rearrangement is possible, return True; otherwise, return False.\n\n=====Input Format=====\nA single string, s, consisting of only lower... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5152,
"level": 1,
"question": "=====Problem Statement=====\nWrite a function that determines if it is possible to rearrange the characters of a given string to form a palindrome. If rearrangement is possible, return True; otherwise, return False.\n\n=====Input Format=====\nA single ... |
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
else:
fib_sequence = [0, 1]
for i in range(2, n):
next_term = fib_sequence[i-1] + fib_sequence[i-2]
fib_sequence.append(next_term)
return fib_sequence | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the Fibonacci sequence up to a given number of terms and returns the sequence as a list. The function should take an integer 'n' as an input and return a list of the first 'n' numbers in the Fibonacci sequence.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5153,
"level": 1,
"question": "Create a function that calculates the Fibonacci sequence up to a given number of terms and returns the sequence as a list. The function should take an integer 'n' as an input and return a list of the first 'n' numbers in the Fibonacci sequence.",
"sp... |
from typing import List
def merge_sorted_arrays(arr1: List[int], arr2: List[int]) -> List[int]:
# Combine both arrays into a single list
combined = arr1 + arr2
# Remove duplicates by converting to a set
unique_elements = set(combined)
# Convert the set back to a sorted list
sorted_result = sort... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nSorted arrays are common in various algorithmic problems, and being able to effectively merge and process multiple sorted arrays is a valuable skill in programming. This task involves merging two sorted arrays into a single sorted array while eliminating any duplicate eleme... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5154,
"level": 1,
"question": "### Context\nSorted arrays are common in various algorithmic problems, and being able to effectively merge and process multiple sorted arrays is a valuable skill in programming. This task involves merging two sorted arrays into a single sorted array wh... |
def countDeluxeCookies(x, y):
return min(x // 2, y)
| simplelr_Taco | [
{
"content": "Question:\nGrandma loves baking cookies for special occasions. She has a special recipe that says if a cookie contains exactly 2 'A's and 1 'B', it is considered a deluxe cookie. Given two integers x and y, which represent the number of 'A's and 'B's respectively, determine the maximum number of d... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5155,
"level": 1,
"question": "Grandma loves baking cookies for special occasions. She has a special recipe that says if a cookie contains exactly 2 'A's and 1 'B', it is considered a deluxe cookie. Given two integers x and y, which represent the number of 'A's and 'B's respectively... |
def merge_sorted_arrays(list1, list2):
i = j = 0
result = []
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
result.append(list1[i])
i += 1
else:
result.append(list2[j])
j += 1
result.extend(list1[i:])
result.extend(li... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function `merge_sorted_arrays` that takes as inputs two sorted lists of integers and returns a new list that contains all the elements from both input lists, sorted in non-decreasing order. Your solution should efficiently merge the lists in O(n) time complexity, where n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5156,
"level": 1,
"question": "Write a Python function `merge_sorted_arrays` that takes as inputs two sorted lists of integers and returns a new list that contains all the elements from both input lists, sorted in non-decreasing order. Your solution should efficiently merge the list... |
def min_subarray_sum(arr):
if not arr:
return 0 # Handle empty array case
min_ending_here = min_so_far = arr[0]
for i in range(1, len(arr)):
min_ending_here = min(arr[i], min_ending_here + arr[i])
min_so_far = min(min_so_far, min_ending_here)
return min_so_far | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the minimum sum of a contiguous subarray within a given array of integers. The array can 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": 5157,
"level": 1,
"question": "Write a function to find the minimum sum of a contiguous subarray within a given array of integers. The array can contain both positive and negative numbers.",
"split": "train"
} |
def left_rotate_array(arr: list, positions: int) -> list:
if not arr:
return []
k = positions % len(arr)
return arr[k:] + arr[:k] | simplelr_Algorithm | [
{
"content": "Question:\n### Array Rotation Challenge\n\n#### Objective\nImplement a function `left_rotate_array` that rotates the elements of an array to the left by a specified number of positions.\n\n#### Function Signature\n```python\ndef left_rotate_array(arr: list, positions: int) -> list:\n```\n\n#### In... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5158,
"level": 1,
"question": "### Array Rotation Challenge\n\n#### Objective\nImplement a function `left_rotate_array` that rotates the elements of an array to the left by a specified number of positions.\n\n#### Function Signature\n```python\ndef left_rotate_array(arr: list, posit... |
def calculate_category_totals(transactions: list) -> dict:
category_totals = {}
for transaction in transactions:
category = transaction['category']
amount = transaction['amount']
category_totals[category] = category_totals.get(category, 0) + amount
return category_totals | simplelr_Package | [
{
"content": "Question:\nYou are given a list of dictionaries where each dictionary contains details about a transaction. Each transaction has three keys: 'transaction_id', 'amount', and 'category'. Your task is to write a function `calculate_category_totals` that processes the transactions and returns a dictio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5159,
"level": 1,
"question": "You are given a list of dictionaries where each dictionary contains details about a transaction. Each transaction has three keys: 'transaction_id', 'amount', and 'category'. Your task is to write a function `calculate_category_totals` that processes th... |
from collections import deque
def bfs(adj, start):
"""
Performs a Breadth-First Search (BFS) on a graph represented as an adjacency list.
Args:
adj (dict): The adjacency list representation of the graph.
start: The starting vertex for the BFS traversal.
Returns:
list: A list o... | simplelr_Evol | [
{
"content": "Question:\nWrite a function in Python that implements the Breadth-First Search (BFS) algorithm for a graph represented as an adjacency list. The function should take the adjacency list and a starting vertex as input, and return the order of vertices visited during the BFS traversal. Provide a brie... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5160,
"level": 1,
"question": "Write a function in Python that implements the Breadth-First Search (BFS) algorithm for a graph represented as an adjacency list. The function should take the adjacency list and a starting vertex as input, and return the order of vertices visited durin... |
def create_dict(pairs):
return {pair[0]: pair[1] for pair in pairs}
# Example usage:
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
print(create_dict(pairs)) # Output: {1: 'a', 2: 'b', 3: 'c'} | simplelr_Filter | [
{
"content": "Question:\nHere is a Python function that creates a dictionary from a list of tuples, where each tuple represents a key-value pair. The function currently uses a for loop to add each tuple to the dictionary. I'd like to use a dictionary comprehension to create the dictionary instead.\n\n```python\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5161,
"level": 1,
"question": "Here is a Python function that creates a dictionary from a list of tuples, where each tuple represents a key-value pair. The function currently uses a for loop to add each tuple to the dictionary. I'd like to use a dictionary comprehension to create th... |
def find_nth_digit(n: int) -> int:
length = 1
start = 1
count = 9 * start * length
while n > count:
n -= count
length += 1
start *= 10
count = 9 * start * length
number = start + (n - 1) // length
digit_index = (n - 1) % length
return int(str(number)... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Objective\n\nYou are tasked with implementing a function to find and return the nth digit in the sequence of natural numbers (starting from 1). This assessment will evaluate your understanding of arithmetic manipulations and iterative computations.\n\n#### Problem Statement\n\nImpl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5162,
"level": 1,
"question": "#### Objective\n\nYou are tasked with implementing a function to find and return the nth digit in the sequence of natural numbers (starting from 1). This assessment will evaluate your understanding of arithmetic manipulations and iterative computations... |
import random
import math
def estimate_pi(n):
count = 0
for _ in range(n):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
if x**2 + y**2 <= 1:
count += 1
pi_estimate = 4 * (count / n)
return pi_estimate
# Number of simulations
n = 1000000
estimated_pi = estimate_... | simplelr_Filter | [
{
"content": "Question:\nPlease suggest a Python code snippet that performs a simple Monte Carlo simulation. A Monte Carlo simulation can be used to estimate the value of π (pi) by randomly generating points within a square and determining the ratio of points that fall inside a quarter circle to the total numbe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5163,
"level": 1,
"question": "Please suggest a Python code snippet that performs a simple Monte Carlo simulation. A Monte Carlo simulation can be used to estimate the value of π (pi) by randomly generating points within a square and determining the ratio of points that fall inside ... |
def sum_2d_array(arr):
sum_total = 0
for row in arr:
for num in row:
sum_total += num
return sum_total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a 2D array as input and returns the sum of all the elements in the array. The function should be able to handle both integers and floating point numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5164,
"level": 1,
"question": "Create a function that takes a 2D array as input and returns the sum of all the elements in the array. The function should be able to handle both integers and floating point numbers.",
"split": "train"
} |
def compute_lps_array(string):
if not string:
return []
lps = [0] * len(string)
length = 0 # Length of the previous longest prefix suffix
i = 1
while i < len(string):
if string[i] == string[length]:
length += 1
lps[i] = length
i += 1
... | simplelr_Apps | [
{
"content": "Question:\nYou are tasked with writing a function that computes the Longest Prefix Suffix (LPS) array for a given string. The LPS array is used in the KMP (Knuth-Morris-Pratt) string matching algorithm.\n\nFor a string str[0..n-1], the LPS array is of the same length as the string. An element LPS[... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5165,
"level": 1,
"question": "You are tasked with writing a function that computes the Longest Prefix Suffix (LPS) array for a given string. The LPS array is used in the KMP (Knuth-Morris-Pratt) string matching algorithm.\n\nFor a string str[0..n-1], the LPS array is of the same le... |
def sum_of_positive_integers(array):
return sum(num for num in array if num > 0) | simplelr_Filter | [
{
"content": "Question:\nCan you generate a Python function that takes an array of integers and returns the sum of all positive integers in the array?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5166,
"level": 1,
"question": "Can you generate a Python function that takes an array of integers and returns the sum of all positive integers in the array?",
"split": "train"
} |
def temperature_alert(temperature):
temp = int(temperature)
if temp >= 500:
return 'Extreme Heat Alert!'
else:
return f'Normal Temperature: {temp} degrees'
| simplelr_Taco | [
{
"content": "Question:\nIn a hypothetical galaxy where every planet’s surface temperature must be monitored, your task as a software developer is to design a function that ensures these readings are categorized correctly.\n\nGiven a string `temperature` that represents a planet’s surface temperature reading in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5167,
"level": 1,
"question": "In a hypothetical galaxy where every planet’s surface temperature must be monitored, your task as a software developer is to design a function that ensures these readings are categorized correctly.\n\nGiven a string `temperature` that represents a plan... |
def generate_substrings(input_str: str) -> list:
result = []
seen = set()
for i in range(len(input_str)):
for j in range(i + 1, len(input_str) + 1):
substr = input_str[i:j]
if substr not in seen:
result.append(substr)
seen.add(substr)
retur... | simplelr_Package | [
{
"content": "Question:\nCreate a function `generate_substrings` that takes a string `input_str` and returns a list of all unique substrings of `input_str`. The substrings should be sorted in the order they appear in the original string.\n\n**Function Signature:**\n```python\ndef generate_substrings(input_str: ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5168,
"level": 1,
"question": "Create a function `generate_substrings` that takes a string `input_str` and returns a list of all unique substrings of `input_str`. The substrings should be sorted in the order they appear in the original string.\n\n**Function Signature:**\n```python\n... |
from typing import List
def string_lengths(strings: List[str]) -> List[int]:
return [len(s) for s in strings] | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a Python function that takes a list of strings and returns a list of the lengths of those strings.\n\nFunction Signature:\n```python\ndef string_lengths(strings: List[str]) -> List[int]:\n```\n\nExample:\n```python\nstrings = [\"apple\", \"banana\", \"cherry\"]\nstring_lengths(str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5169,
"level": 1,
"question": "Write a Python function that takes a list of strings and returns a list of the lengths of those strings.\n\nFunction Signature:\n```python\ndef string_lengths(strings: List[str]) -> List[int]:\n```\n\nExample:\n```python\nstrings = [\"apple\", \"banana... |
def decrypt_caesar_cipher(encrypted_text: str, shift: int) -> str:
result = []
for char in encrypted_text:
if char.isupper():
start = ord('A')
elif char.islower():
start = ord('a')
else:
result.append(char)
continue
# Calculate the ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Caesar Cipher Decryption\n\n**Context**: A data leak incident occurred, and to retrieve the encrypted data, you need to decrypt the text encrypted with a Caesar Cipher. Given the encrypted text and the shift value used during the encryption, your task is to write a function to decry... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5170,
"level": 1,
"question": "### Caesar Cipher Decryption\n\n**Context**: A data leak incident occurred, and to retrieve the encrypted data, you need to decrypt the text encrypted with a Caesar Cipher. Given the encrypted text and the shift value used during the encryption, your t... |
def count_overflowing_containers(nums, d, threshold):
count = 0
for num in nums:
if num + d >= threshold:
count += 1
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `nums` where each element represents the number of units of water in a container. Every day, rainwater adds one more unit of water to each container. Given `d` days, return the number of containers that overflow after `d` days. Assume a contai... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5171,
"level": 1,
"question": "You are given a **0-indexed** integer array `nums` where each element represents the number of units of water in a container. Every day, rainwater adds one more unit of water to each container. Given `d` days, return the number of containers that overf... |
def largest_rectangle_area(heights: list[int]) -> int:
if not heights:
return 0
n = len(heights)
for h in heights:
if h < 0:
raise ValueError("No height can be negative")
left = [-1] * n
stack = []
for i in range(n):
while stack and heights[stack[-1]] >= ... | simplelr_Algorithm | [
{
"content": "Question:\n**Problem Statement**:\nYou are given a list of integers where each element represents a building's height. Your task is to compute the largest rectangular area that can be formed within these buildings when visualized as adjacent bars of width 1.\n\n**Function Signature**:\n```python\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5172,
"level": 1,
"question": "**Problem Statement**:\nYou are given a list of integers where each element represents a building's height. Your task is to compute the largest rectangular area that can be formed within these buildings when visualized as adjacent bars of width 1.\n\n*... |
from typing import List
def gnome_sort(arr: List[int]) -> List[int]:
i = 0
n = len(arr)
while i < n:
if i == 0 or arr[i-1] <= arr[i]:
i += 1
else:
arr[i-1], arr[i] = arr[i], arr[i-1]
i -= 1
return arr | simplelr_Data_Structure | [
{
"content": "Question:\n**Scenario**: You are a software engineer at a small start-up, tasked with creating a new feature in the company's data analysis tool. One requirement is to sort certain data sets. Although there are a variety of sorting algorithms, you decide to implement Gnome Sort because of its simp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5173,
"level": 1,
"question": "**Scenario**: You are a software engineer at a small start-up, tasked with creating a new feature in the company's data analysis tool. One requirement is to sort certain data sets. Although there are a variety of sorting algorithms, you decide to imple... |
def pair_vehicle(name):
person_vehicle = {
"Bruce": "Bruce-Wayne's Batmobile",
"Tony": "Tony-Iron Man's Armor",
"Peter": "Peter-Spidey Buggy",
"Clark": "Clark-Kryptonian Ship",
"Diana": "Diana-Invisible Jet",
"Barry": "Barry-Speedster's Car"
}
return person_ve... | simplelr_Apps | [
{
"content": "Question:\nWrite a function, `pair_vehicle`, that takes in a string representing the name of a person and returns the vehicle associated with that person.\n\nThe following pairs of person and their respective vehicle should be included:\n\n* Bruce-Wayne's Batmobile\n* Tony-Iron Man's Armor\n* Pete... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5174,
"level": 1,
"question": "Write a function, `pair_vehicle`, that takes in a string representing the name of a person and returns the vehicle associated with that person.\n\nThe following pairs of person and their respective vehicle should be included:\n\n* Bruce-Wayne's Batmobi... |
def rotate_array(arr, k):
n = len(arr)
if n == 0:
return []
k = k % n
if k == 0:
return list(arr)
return arr[-k:] + arr[:-k]
| simplelr_Taco | [
{
"content": "Question:\nFunction Description: \n\nWrite a function `rotate_array` that takes in an array of integers and an integer k, and returns a new array that is a right rotation of the original array by k steps. A right rotation means that each element of the array is shifted to the right by one position... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5175,
"level": 1,
"question": "Function Description: \n\nWrite a function `rotate_array` that takes in an array of integers and an integer k, and returns a new array that is a right rotation of the original array by k steps. A right rotation means that each element of the array is s... |
def minimum_swaps_to_sort(arr: list) -> int:
sorted_arr = sorted(arr)
n = len(arr)
value_to_index = {v: i for i, v in enumerate(sorted_arr)}
visited = [False] * n
swaps = 0
for i in range(n):
if not visited[i]:
cycle_size = 0
j = i
while not visited[j... | simplelr_Package | [
{
"content": "Question:\nYou are required to implement a function `minimum_swaps_to_sort` that takes in a list of unique integers and returns the minimum number of swaps needed to sort the array in ascending order. \n\nThe approach should be based on the concept of graph cycles and their relationship to permuta... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5176,
"level": 1,
"question": "You are required to implement a function `minimum_swaps_to_sort` that takes in a list of unique integers and returns the minimum number of swaps needed to sort the array in ascending order. \n\nThe approach should be based on the concept of graph cycle... |
def sum_of_squares(arr):
return sum(x ** 2 for x in arr) | simplelr_Filter | [
{
"content": "Question:\n# Create a Python program that takes in an array of integers and returns the sum of squares of the array elements.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5177,
"level": 1,
"question": "# Create a Python program that takes in an array of integers and returns the sum of squares of the array elements.",
"split": "train"
} |
def reverse_list_of_tuples(tuples_list):
return [tuple(t[::-1]) for t in reversed(tuples_list)] | simplelr_Filter | [
{
"content": "Question:\nDevelop a method that reverses a list of tuples, while also considering the elements of each tuple. Your solution still needs to handle the main list and individual tuples' reversals but must retain the correspondence between your reversed list index and the reversed tuple that occupies... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5178,
"level": 1,
"question": "Develop a method that reverses a list of tuples, while also considering the elements of each tuple. Your solution still needs to handle the main list and individual tuples' reversals but must retain the correspondence between your reversed list index a... |
def find_duplicates(lst):
counts = {}
for num in lst:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
added = set()
duplicates = []
for num in lst:
if counts[num] > 1 and num not in added:
duplicates.append(num)
ad... | simplelr_Filter | [
{
"content": "Question:\nCreate a function named \"find_duplicates\" that takes a list parameter \"lst\" and returns a new list containing the elements that appear more than once in the original list, in the order they first appear.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5179,
"level": 1,
"question": "Create a function named \"find_duplicates\" that takes a list parameter \"lst\" and returns a new list containing the elements that appear more than once in the original list, in the order they first appear.",
"split": "train"
} |
def find_max_consecutive_sum(arr, k):
n = len(arr)
if k <= 0 or n < k:
return None
max_sum = sum(arr[:k])
current_sum = max_sum
for i in range(1, n - k + 1):
current_sum = current_sum - arr[i - 1] + arr[i + k - 1]
if current_sum > max_sum:
max_sum = current_sum
... | simplelr_Apps | [
{
"content": "Question:\nWrite a function\n\n```python\nfind_max_consecutive_sum(arr, k)\n```\n\nthat takes a list of integers `arr` and an integer `k`, and returns the maximum sum of any `k` consecutive elements in the array.\n\nFor example:\n\n```python\nfind_max_consecutive_sum([1, 4, 2, 10, 23, 3, 1, 0, 20]... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5180,
"level": 1,
"question": "Write a function\n\n```python\nfind_max_consecutive_sum(arr, k)\n```\n\nthat takes a list of integers `arr` and an integer `k`, and returns the maximum sum of any `k` consecutive elements in the array.\n\nFor example:\n\n```python\nfind_max_consecutive... |
def search_matrix(matrix, target):
for row_index, row in enumerate(matrix):
for col_index, value in enumerate(row):
if value == target:
return [row_index, col_index]
return [-1, -1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to search for a target value in a two-dimensional list, often referred to as a matrix. The function should return the indices `[row, column]` if the target is found, otherwise, return `[-1, -1]`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5181,
"level": 1,
"question": "Write a python function to search for a target value in a two-dimensional list, often referred to as a matrix. The function should return the indices `[row, column]` if the target is found, otherwise, return `[-1, -1]`.",
"split": "train"
} |
def reverse_list(input_list):
reversed_list = []
for i in range(len(input_list)-1, -1, -1):
reversed_list.append(input_list[i])
return reversed_list | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers as input and returns a new list of integers that is the reverse of the input list. The function should not use the built-in reverse method.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5182,
"level": 1,
"question": "Create a function that takes a list of integers as input and returns a new list of integers that is the reverse of the input list. The function should not use the built-in reverse method.",
"split": "train"
} |
def modified_fibonacci(a: int, b: int, n: int) -> int:
if n == 1:
return a
elif n == 2:
return b
else:
first, second = a, b
for _ in range(n - 2):
next_term = first + second
first = second
second = next_term
return second | simplelr_Algorithm | [
{
"content": "Question:\n### Fibonacci Sequence Modification\n\n#### Context:\nThe Fibonacci sequence is a well-known series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. This sequence can be modified by defining different starting values, which will result ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5183,
"level": 1,
"question": "### Fibonacci Sequence Modification\n\n#### Context:\nThe Fibonacci sequence is a well-known series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. This sequence can be modified by defining different ... |
def binary_search(sorted_list, target):
low = 0
high = len(sorted_list) - 1
while low <= high:
mid = (low + high) // 2
if sorted_list[mid] == target:
return mid
elif target < sorted_list[mid]:
high = mid - 1
else:
low = mid + 1
ret... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that implements a binary search on a sorted list to find the index of a given element. If the element is not found, the function should return -1. Ensure the function is efficient and handles edge cases. Demonstrate its correctness with a few test cases.\nAnswer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5184,
"level": 1,
"question": "Create a Python function that implements a binary search on a sorted list to find the index of a given element. If the element is not found, the function should return -1. Ensure the function is efficient and handles edge cases. Demonstrate its correct... |
def bubble_sort(lst):
# Make a copy of the list to avoid modifying the original list
lst = lst.copy()
# Get the length of the list
n = len(lst)
# Iterate through the list n-1 times (since each pass places the next largest element)
for i in range(n - 1):
# Initialize sw... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python program to sort a list of numbers using the bubble sort algorithm. Make sure the program is easy to understand for beginners and includes comments explaining each step.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5185,
"level": 1,
"question": "Create a Python program to sort a list of numbers using the bubble sort algorithm. Make sure the program is easy to understand for beginners and includes comments explaining each step.",
"split": "train"
} |
def multiply_matrix(multiplicand: list, multiplier: list) -> list:
m_rows = len(multiplicand)
m_cols = len(multiplicand[0])
p_cols = len(multiplier[0])
result = []
for i in range(m_rows):
new_row = []
for j in range(p_cols):
sum_val = 0
for k in range(m_c... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Matrix Multiplication Implementation\n\nYou are tasked with implementing the matrix multiplication algorithm. Given two compatible two-dimensional matrices, your function will return their product.\n\n#### Function Signature\n```python\ndef multiply_matrix(multiplicand: li... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5186,
"level": 1,
"question": "### Question: Matrix Multiplication Implementation\n\nYou are tasked with implementing the matrix multiplication algorithm. Given two compatible two-dimensional matrices, your function will return their product.\n\n#### Function Signature\n```python\nd... |
def three_sum(arr):
arr.sort()
n = len(arr)
result = []
for i in range(n - 2):
if i > 0 and arr[i] == arr[i-1]:
continue
a = arr[i]
left = i + 1
right = n - 1
while left < right:
current_sum = arr[left] + arr[right]
target = -a
... | simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers, write a function to find if there exists a triplet (a, b, c) in the array such that a + b + c = 0. The function should return a list of all unique triplets that give the sum of zero. Elements in each triplet should be in ascending order, and the list of tripl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5187,
"level": 1,
"question": "Given an array of integers, write a function to find if there exists a triplet (a, b, c) in the array such that a + b + c = 0. The function should return a list of all unique triplets that give the sum of zero. Elements in each triplet should be in asc... |
import math
def vector_magnitude(vector):
return math.sqrt(sum(x**2 for x in vector))
# Example usage:
# vector = [1.0, 2.0, 3.0]
# print(vector_magnitude(vector)) | simplelr_Filter | [
{
"content": "Question:\nFinish the code snippet below to compute and output a vector's magnitude. The vector will be presented as a list of floating-point numbers, and could be variable in length, i.e., it might not just be a 3-dimensional vector. Ensure your code can handle vectors with varying lengths.\nAnsw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5188,
"level": 1,
"question": "Finish the code snippet below to compute and output a vector's magnitude. The vector will be presented as a list of floating-point numbers, and could be variable in length, i.e., it might not just be a 3-dimensional vector. Ensure your code can handle ... |
def to_uppercase(s):
result = ""
for char in s:
if char.islower():
result += char.upper()
else:
result += char
return result | simplelr_Filter | [
{
"content": "Question:\nIs there a way to convert a string to uppercase in Python by iterating over each character and using an if statement to check if the characters are uppercase or lowercase?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5189,
"level": 1,
"question": "Is there a way to convert a string to uppercase in Python by iterating over each character and using an if statement to check if the characters are uppercase or lowercase?",
"split": "train"
} |
def product_except_self(arr):
n = len(arr)
if n == 0:
return []
prefix = [1] * n
suffix = [1] * n
# Compute prefix products
for i in range(1, n):
prefix[i] = prefix[i-1] * arr[i-1]
# Compute suffix products
for i in range(n-2, -1, -1):
suffix[i] = s... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr`, return an array of the same length where each element at index `i` is replaced with the product of all the elements in `arr` except `arr[i]`. Implement this with a time complexity of `O(n)` and without using the division operation.\n\nFor example, given... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5190,
"level": 1,
"question": "Given an array of integers `arr`, return an array of the same length where each element at index `i` is replaced with the product of all the elements in `arr` except `arr[i]`. Implement this with a time complexity of `O(n)` and without using the divisi... |
def maximize_deliveries(packages, capacity):
if not packages:
return 0
packages_sorted = sorted(packages)
total = 0
count = 0
for package in packages_sorted:
if total + package <= capacity:
total += package
count += 1
else:
break
return... | simplelr_Apps | [
{
"content": "Question:\nYou are tasked with creating an efficient package delivery service. Given a list of packages with their weights and the maximum capacity of the delivery truck, your aim is to maximize the number of package deliveries without exceeding the truck's capacity.\n\nImplement a function `maxim... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5191,
"level": 1,
"question": "You are tasked with creating an efficient package delivery service. Given a list of packages with their weights and the maximum capacity of the delivery truck, your aim is to maximize the number of package deliveries without exceeding the truck's capac... |
def sort_tasks(tasks: list) -> list:
return sorted(tasks, key=lambda x: (-x['priority'], x['name'])) | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nYou are developing a task management system where tasks need to be organized based on their priority. Each task is represented by an object containing its name and priority level. You want to implement a function to sort these tasks in descending order of priority.\n\n### T... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5192,
"level": 1,
"question": "### Context\nYou are developing a task management system where tasks need to be organized based on their priority. Each task is represented by an object containing its name and priority level. You want to implement a function to sort these tasks in des... |
import html
def process_html_strings(strings: list[str], quote: bool = True) -> list[str]:
result = []
for s in strings:
escaped = html.escape(s, quote=quote)
unescaped = html.unescape(escaped)
result.append(unescaped)
return result
| simplelr_Docs | [
{
"content": "Question:\n**Objective**: Demonstrate understanding of HTML manipulation in Python using the `html` module.\n\n### Problem Statement\n\nYou are tasked with creating a function that takes a list of strings and processes each string to make it HTML-safe and then revert it back to its original form. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5193,
"level": 1,
"question": "**Objective**: Demonstrate understanding of HTML manipulation in Python using the `html` module.\n\n### Problem Statement\n\nYou are tasked with creating a function that takes a list of strings and processes each string to make it HTML-safe and then re... |
def balance_parentheses(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
else:
if not stack:
return False
stack.pop()
return len(stack) == 0
| simplelr_Taco | [
{
"content": "Question:\nCreate a function called `balance_parentheses` that takes a string consisting of only the characters '(', ')' as input. The function should return a boolean indicating whether the parentheses in the input string are balanced. A balanced set of parentheses means every opening parenthesis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5194,
"level": 1,
"question": "Create a function called `balance_parentheses` that takes a string consisting of only the characters '(', ')' as input. The function should return a boolean indicating whether the parentheses in the input string are balanced. A balanced set of parenthe... |
def merge_digits(a: int, b: int) -> int:
s = str(a)
t = str(b)
max_len = max(len(s), len(t))
res = []
for i in range(max_len):
if i < len(s):
res.append(s[i])
if i < len(t):
res.append(t[i])
result_str = ''.join(res)
return int(result_str) if result_st... | simplelr_Codeforces | [
{
"content": "Question:\nWrite a function that takes in two integers, a and b, and returns a new integer constructed by alternating the digits of a and b. If one number has more digits than the other, append the remaining digits at the end of the new number.\n\nFor example, if the input integers are 1234 and 56... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5195,
"level": 1,
"question": "Write a function that takes in two integers, a and b, and returns a new integer constructed by alternating the digits of a and b. If one number has more digits than the other, append the remaining digits at the end of the new number.\n\nFor example, if... |
def encrypt_message(message: str) -> str:
# Step 1 and 2: Convert each character to its 8-bit binary representation
binaries = [format(ord(c), '08b') for c in message]
# Step 3: Concatenate all binary strings
concatenated = ''.join(binaries)
# Step 4 and 5: Split into 8-bit segments and co... | simplelr_Taco | [
{
"content": "Question:\nA company is developing a secure messaging platform. One of the requirements is to implement an efficient encryption scheme for text messages by encoding the message using a specific rule. Your task is to write a function that encrypts a given string according to the following steps:\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5196,
"level": 1,
"question": "A company is developing a secure messaging platform. One of the requirements is to implement an efficient encryption scheme for text messages by encoding the message using a specific rule. Your task is to write a function that encrypts a given string a... |
def merge_sorted_arrays(arr1, arr2):
return sorted(arr1 + arr2)
# Example usage:
arr1 = [1, 3, 5]
arr2 = [2, 4, 6]
print(merge_sorted_arrays(arr1, arr2)) # Output: [1, 2, 3, 4, 5, 6] | simplelr_Filter | [
{
"content": "Question:\nGiven two sorted arrays, how can I merge them into a single sorted array in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5197,
"level": 1,
"question": "Given two sorted arrays, how can I merge them into a single sorted array in Python?",
"split": "train"
} |
from typing import List
def modified_ternary_search(left: int, right: int, key: int, arr: List[int]) -> int:
while left <= right:
# Calculate the two midpoints
mid1 = left + (right - left) // 3
mid2 = right - (right - left) // 3
# Check if key is found at mid1 or mid2
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Implement the Modified Ternary Search\n\nYou are required to implement the Ternary Search algorithm. The function should take as input a sorted array of integers, a left index, a right index, and the key to be searched. The function should return the index of the key if fo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5198,
"level": 1,
"question": "### Question: Implement the Modified Ternary Search\n\nYou are required to implement the Ternary Search algorithm. The function should take as input a sorted array of integers, a left index, a right index, and the key to be searched. The function shoul... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib as mpl
def create_custom_palette_plot(data, num_colors=6, lightness=0.5, saturation=0.9, hue_start=0.0, as_cmap=False):
"""
Generates a custom seaborn color palette and applies it to a bar plot.
... | simplelr_Docs | [
{
"content": "Question:\n**Coding Assessment Question:**\n\nSeaborn is a powerful visualization library in Python that allows for easy creation of informative and attractive statistical graphics. One of its features is the ability to generate color palettes to customize the appearance of plots.\n\n### Task:\nWr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5199,
"level": 1,
"question": "**Coding Assessment Question:**\n\nSeaborn is a powerful visualization library in Python that allows for easy creation of informative and attractive statistical graphics. One of its features is the ability to generate color palettes to customize the ap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.