target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
def find_two_sum(nums, target):
num_dict = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_dict:
return [num_dict[complement], i]
num_dict[num] = i
return [] | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that identifies any two distinct numbers in a list whose sum equals a specified target. The function should return the indices of these two numbers. If no such pair exists, the function should return an empty list.\nAnswer:\nLet's think step by step.\n",
"rol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7500,
"level": 1,
"question": "Write a Python function that identifies any two distinct numbers in a list whose sum equals a specified target. The function should return the indices of these two numbers. If no such pair exists, the function should return an empty list.",
"split": ... |
def count_words(s):
return len(s.split()) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as an input and returns the number of words in the string. Assume a word is defined as any sequence of characters separated by spaces. For example, calling the function with the argument \"Hello World\" should return 2, as there are two words in the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7501,
"level": 1,
"question": "Create a function that takes a string as an input and returns the number of words in the string. Assume a word is defined as any sequence of characters separated by spaces. For example, calling the function with the argument \"Hello World\" should retu... |
def enhanced_rabin_karp(word: str, text: str) -> int:
mod = 10**9 + 7
base = 31
if not word:
return 0
m = len(word)
n = len(text)
if m > n:
return None
# Precompute base^(m-1) mod mod
pow_p_m_minus_1 = pow(base, m - 1, mod)
# Compute hash for ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Rabin-Karp Algorithm Enhancement\n\n**Context**:\nYou are tasked with improving a plagiarism detection system that relies on the Rabin-Karp algorithm for string matching. The current implementation is encountering an unexpected number of hash collisions, leading to inefficient perfo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7502,
"level": 1,
"question": "### Rabin-Karp Algorithm Enhancement\n\n**Context**:\nYou are tasked with improving a plagiarism detection system that relies on the Rabin-Karp algorithm for string matching. The current implementation is encountering an unexpected number of hash colli... |
def add_binary(a, b):
result = []
i = len(a) - 1
j = len(b) - 1
carry = 0
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
current_bit = total % 2
carry = total // 2
... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two binary strings as input and returns their binary sum as a string. For example, if the input is \"10\" and \"11\", the function should return \"101\";\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7503,
"level": 1,
"question": "Create a function that takes two binary strings as input and returns their binary sum as a string. For example, if the input is \"10\" and \"11\", the function should return \"101\";",
"split": "train"
} |
def compress(s):
if not s:
return s
compressed = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
compressed.append(current_char + str(count))
current_char = char
count = 1
... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that performs basic string compression using the counts of repeated characters. If the compressed string is not smaller than the original string, it should return the original string. \n\nFor example:\n```python\ncompress(\"aabcccccaaa\") => \"a2b1c5a3\"\ncompress(\"abc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7504,
"level": 1,
"question": "Write a function that performs basic string compression using the counts of repeated characters. If the compressed string is not smaller than the original string, it should return the original string. \n\nFor example:\n```python\ncompress(\"aabcccccaaa... |
def list_to_string(lst, separator=','):
sep = str(separator)
return sep.join(map(str, lst)) | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that converts a list of integers into a comma-separated string, and also allows for a custom separator? For example, if I have a list `[1, 2, 3, 4]`, I should be able to use a comma, a semicolon, or any other character as a separator between the number... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7505,
"level": 1,
"question": "How can I create a Python function that converts a list of integers into a comma-separated string, and also allows for a custom separator? For example, if I have a list `[1, 2, 3, 4]`, I should be able to use a comma, a semicolon, or any other characte... |
def print_divisible_by_2_and_3(a, b):
start = min(a, b)
end = max(a, b)
for number in range(start, end + 1):
if number % 6 == 0:
print(number) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two integers `a` and `b` as input and prints all numbers between `a` and `b` (inclusive) that are divisible by both 2 and 3.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7506,
"level": 1,
"question": "Create a function that takes two integers `a` and `b` as input and prints all numbers between `a` and `b` (inclusive) that are divisible by both 2 and 3.",
"split": "train"
} |
def is_balanced_brackets(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if a given string contains a balanced bracket structure. A string is considered to have a balanced bracket structure if every opening bracket \"(\" has a corresponding closing bracket \")\" and they are properly nested. The function should return True if th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7507,
"level": 1,
"question": "Create a function that checks if a given string contains a balanced bracket structure. A string is considered to have a balanced bracket structure if every opening bracket \"(\" has a corresponding closing bracket \")\" and they are properly nested. Th... |
import numpy as np
import matplotlib.pyplot as plt
def generate_histogram(data, num_bins, xlabel, ylabel, title):
plt.figure(figsize=(8, 6))
hist, bin_edges = np.histogram(data, bins=num_bins)
midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
width = bin_edges[1] - bin_edges[0]
plt.bar(midpoints, hi... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function `generate_histogram` that generates a histogram to visualize the frequency distribution of data values. This function will utilize the following key libraries: Matplotlib and NumPy.\n\n### Function Signature:\n```python\ndef generate_histogram(dat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7508,
"level": 1,
"question": "You are tasked with creating a function `generate_histogram` that generates a histogram to visualize the frequency distribution of data values. This function will utilize the following key libraries: Matplotlib and NumPy.\n\n### Function Signature:\n``... |
def max_vowels(s: str, k: int) -> int:
vowels = {'a', 'e', 'i', 'o', 'u'}
n = len(s)
if k == 0 or n < k:
return 0
is_vowel = [c in vowels for c in s]
current_count = sum(is_vowel[:k])
max_count = current_count
for i in range(1, n - k + 1):
current_count = current_count - is_v... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` and an integer `k`, return the maximal number of vowel characters that appear consecutively in any substring of length `k` in `s`.\n\nFor the purpose of this question, the vowels are defined as `'a', 'e', 'i', 'o', 'u'`.\nAnswer:\nLet's think step by step.\n",
"ro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7509,
"level": 1,
"question": "Given a string `s` and an integer `k`, return the maximal number of vowel characters that appear consecutively in any substring of length `k` in `s`.\n\nFor the purpose of this question, the vowels are defined as `'a', 'e', 'i', 'o', 'u'`.",
"split":... |
from typing import Tuple
def simulate_robot_vacuum(commands: str) -> Tuple[int, int]:
x, y = 0, 0
for move in commands:
if move == 'U':
y += 1
elif move == 'D':
y -= 1
elif move == 'L':
x -= 1
elif move == 'R':
x += 1
return (x... | simplelr_Package | [
{
"content": "Question:\nYou need to write a function `simulate_robot_vacuum` that simulates the operation of a robot vacuum cleaner navigating a room. The function should take in a single string parameter representing a sequence of commands and determine the final position of the robot vacuum on a 2D grid.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7510,
"level": 1,
"question": "You need to write a function `simulate_robot_vacuum` that simulates the operation of a robot vacuum cleaner navigating a room. The function should take in a single string parameter representing a sequence of commands and determine the final position of... |
def find_duplicates(nums):
n = len(nums)
frequency = [0] * (n + 1)
for num in nums:
frequency[num] += 1
duplicates = [i for i in range(1, n + 1) if frequency[i] > 1]
return duplicates | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array `nums` containing `n` integers where each integer is in the range [1, n] inclusive, you need to detect all the integers that appear more than once in the array. Write a function that returns an array of all the duplicate integers in any order.\nAnswer:\nLet's think step b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7511,
"level": 1,
"question": "Given an array `nums` containing `n` integers where each integer is in the range [1, n] inclusive, you need to detect all the integers that appear more than once in the array. Write a function that returns an array of all the duplicate integers in any ... |
def calculate_average_grades(students):
student_averages = {}
for student in students:
student_id = student[0]
grades = student[2]
if not grades:
average = 0.0
else:
average = sum(grades) / len(grades)
rounded_average = round(average, 2)
st... | simplelr_Filter | [
{
"content": "Question:\nI need to create a Python function that takes a list of tuples as input, where each tuple contains three elements: an integer (representing a student ID), a string (representing a student name), and a list of integers (representing the student's grades). The function should calculate th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7512,
"level": 1,
"question": "I need to create a Python function that takes a list of tuples as input, where each tuple contains three elements: an integer (representing a student ID), a string (representing a student name), and a list of integers (representing the student's grades... |
def trap_rainwater(heights):
n = len(heights)
if n < 3:
return 0
left_max = [0] * n
current_max = 0
for i in range(1, n):
current_max = max(current_max, heights[i-1])
left_max[i] = current_max
right_max = [0] * n
current_max = 0
for i in range(n-2, -1, -1):
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers representing the height of walls at various positions along a straight path. Your goal is to trap as much rainwater as possible after it rains. Specifically, you are given an integer array `heights` where `heights[i]` represents the height of a wall at p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7513,
"level": 1,
"question": "You are given a list of integers representing the height of walls at various positions along a straight path. Your goal is to trap as much rainwater as possible after it rains. Specifically, you are given an integer array `heights` where `heights[i]` r... |
def sum_numeric_values(lst):
total = 0
for item in lst:
if type(item) in (int, float):
total += item
return total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the sum of all numbers in a given list. If the list contains any non-numeric values, they should be ignored. How can this be done in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7514,
"level": 1,
"question": "Create a function that calculates the sum of all numbers in a given list. If the list contains any non-numeric values, they should be ignored. How can this be done in Python?",
"split": "train"
} |
from typing import List
def process_file(file_path: str) -> List[int]:
numbers = []
try:
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
try:
num = int(line)
except ValueError:
r... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\nImplement a Python function that reads data from a text file, processes it, and handles various exceptions that may occur during the process. This will demonstrate your understanding of exception handling, custom exceptions, and resource management.\n\n#### Problem State... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7515,
"level": 1,
"question": "#### Objective\nImplement a Python function that reads data from a text file, processes it, and handles various exceptions that may occur during the process. This will demonstrate your understanding of exception handling, custom exceptions, and resourc... |
def maximalSquare(matrix):
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
return 0
m = len(matrix)
n = len(matrix[0])
dp = [[0 for _ in range(n)] for _ in range(m)]
max_side = 0
for i in range(m):
for j in range(n):
if matrix[i][j] == 1:
if ... | simplelr_Algorithm | [
{
"content": "Question:\n### Maximal Square in a Binary Grid\n\n#### Background\nYou are given a binary grid of size `m x n` consisting of only 0's and 1's. Your task is to find the largest square containing only 1's and return its area.\n\n#### Task\nImplement a function `maximalSquare` that finds the largest ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7516,
"level": 1,
"question": "### Maximal Square in a Binary Grid\n\n#### Background\nYou are given a binary grid of size `m x n` consisting of only 0's and 1's. Your task is to find the largest square containing only 1's and return its area.\n\n#### Task\nImplement a function `max... |
def max_items(x, prices):
prices_sorted = sorted(prices)
total_cost = 0
count = 0
for price in prices_sorted:
if total_cost + price <= x:
total_cost += price
count += 1
else:
break
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a non-negative integer `x` representing the amount of money you have and an array `prices` where `prices[i]` is the price of the `i-th` item in a store. Each item can only be purchased once. Return the **maximum** number of different items you can buy with the given amount... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7517,
"level": 1,
"question": "You are given a non-negative integer `x` representing the amount of money you have and an array `prices` where `prices[i]` is the price of the `i-th` item in a store. Each item can only be purchased once. Return the **maximum** number of different item... |
def longest_subarray_sum(nums, target):
prefix_map = {0: -1}
current_sum = 0
max_length = 0
for i in range(len(nums)):
current_sum += nums[i]
target_sum = current_sum - target
if target_sum in prefix_map:
j = prefix_map[target_sum]
current_length = i - j
... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a list of integers and an integer target value. The function should return the lengths of the longest contiguous subarray that sums up to the target value. If no such subarray exists, the function should return 0.\n\n## Examples\n```python\nlongest_subarray_s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7518,
"level": 1,
"question": "Write a function that takes a list of integers and an integer target value. The function should return the lengths of the longest contiguous subarray that sums up to the target value. If no such subarray exists, the function should return 0.\n\n## Exam... |
def levenshtein_distance(str1, str2):
"""
Calculate the Levenshtein distance between two strings.
The Levenshtein distance is a measure of the minimum number of single-character edits
(insertions, deletions or substitutions) required to change one string into the other.
Args:
str1 ... | simplelr_Filter | [
{
"content": "Question:\nWrite a function to calculate the Levenshtein distance between two strings. The function should take two parameters, `str1` and `str2`, and return the distance as an integer. Include a brief explanation of what Levenshtein distance is and how it's useful.\nAnswer:\nLet's think step by s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7519,
"level": 1,
"question": "Write a function to calculate the Levenshtein distance between two strings. The function should take two parameters, `str1` and `str2`, and return the distance as an integer. Include a brief explanation of what Levenshtein distance is and how it's usef... |
def text_to_morse(s):
# Define the Morse code mapping for each letter
morse_code = {
'A': '.-',
'B': '-...',
'C': '-.-.',
'D': '-..',
'E': '.',
'F': '..-.',
'G': '--.',
'H': '....',
'I': '..',
'J': '.---',
'K': '-.-',
... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that can convert a given string to Morse code. The function should be able to handle both uppercase and lowercase letters, and it should ignore any characters that are not letters. For simplicity, you can assume that the input string will only contain letters an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7520,
"level": 1,
"question": "Create a Python function that can convert a given string to Morse code. The function should be able to handle both uppercase and lowercase letters, and it should ignore any characters that are not letters. For simplicity, you can assume that the input ... |
import configparser
import os
def update_config(file_path: str) -> None:
"""
Updates a configuration file according to specified rules.
Args:
file_path (str): Path to the INI configuration file.
Returns:
None
"""
parser = configparser.ConfigParser()
try:
# Rea... | simplelr_Docs | [
{
"content": "Question:\n**Coding Assessment Question**\n\n### Objective\n\nThis question will assess your ability to work with the `configparser` module in Python to read, manipulate, and write INI files.\n\n### Problem Statement\n\nYou are given a configuration file in INI format that contains settings for a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7521,
"level": 1,
"question": "**Coding Assessment Question**\n\n### Objective\n\nThis question will assess your ability to work with the `configparser` module in Python to read, manipulate, and write INI files.\n\n### Problem Statement\n\nYou are given a configuration file in INI f... |
def convert_to_dict(s):
if not s:
return {}
elements = s.split(',')
pairs = []
length = len(elements)
for i in range(0, length - 1, 2):
key = elements[i]
value = elements[i + 1]
pairs.append((key, value))
if length % 2 != 0:
pairs.append((elements[-1], Non... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to convert an delimited string to a python dictionary using the comma as a delimiter. If the string is empty, return an empty dictionary. If the string contains an uneven number of elements (key without a value), the last key should be paired with `None`.\nAnswer:\nLet'... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7522,
"level": 1,
"question": "Write a function to convert an delimited string to a python dictionary using the comma as a delimiter. If the string is empty, return an empty dictionary. If the string contains an uneven number of elements (key without a value), the last key should be... |
import math
def calculateDistance(point1, point2):
x1, y1 = point1
x2, y2 = point2
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that , given two points in a 2D space, calculates the Euclidean distance between them. The function should be named `calculateDistance` and take two tuples representing the coordinates of the points. Each tuple contains the x and y coordinates of a point. The function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7523,
"level": 1,
"question": "Create a function that , given two points in a 2D space, calculates the Euclidean distance between them. The function should be named `calculateDistance` and take two tuples representing the coordinates of the points. Each tuple contains the x and y co... |
import random
def quicksort(arr):
"""
Sorts an array of integers using the Quicksort algorithm.
Parameters:
arr (list): List of integers to be sorted.
Returns:
list: Sorted list of integers.
"""
if len(arr) <= 1:
return arr
# Select a random pivot index to avo... | simplelr_Package | [
{
"content": "Question:\nIn this problem, you are asked to implement a function that uses the Quicksort algorithm to sort a given list of integers. Quicksort is a divide-and-conquer algorithm that works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, accord... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7524,
"level": 1,
"question": "In this problem, you are asked to implement a function that uses the Quicksort algorithm to sort a given list of integers. Quicksort is a divide-and-conquer algorithm that works by selecting a 'pivot' element from the array and partitioning the other e... |
def extract_numbers(s):
return ''.join([c for c in s if c.isdigit()]) | simplelr_Filter | [
{
"content": "Question:\nI have a string that consists of numbers, spaces, and punctuation marks. How can I write an algorithm in Python that removes all the whitespaces and punctuation from the string, and returns only the numbers in it?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7525,
"level": 1,
"question": "I have a string that consists of numbers, spaces, and punctuation marks. How can I write an algorithm in Python that removes all the whitespaces and punctuation from the string, and returns only the numbers in it?",
"split": "train"
} |
def triangle_area(base: float, height: float) -> float:
"""
Calculate the area of a triangle given its base and height.
Parameters
----------
base : float
The base length of the triangle.
height : float
The height of the triangle.
Returns
-------
float
The a... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that calculates the area of a triangle given its base and height. The function should include docstring that follows the numpydoc style guide. The function should also include type hints and a simple test to verify its correctness.\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7526,
"level": 1,
"question": "Create a Python function that calculates the area of a triangle given its base and height. The function should include docstring that follows the numpydoc style guide. The function should also include type hints and a simple test to verify its correctn... |
def safe_division(numerator, denominator):
try:
if not (isinstance(numerator, (int, float)) and isinstance(denominator, (int, float))):
raise ValueError("Both numerator and denominator must be numbers.")
result = numerator / denominator
except ZeroDivisionError:
print("Divisi... | simplelr_Docs | [
{
"content": "Question:\n### Question: Implementing and Handling Exceptions with Cleanup\n\nYou are required to write a function `safe_division` that takes two arguments, `numerator` and `denominator`, and returns the result of dividing `numerator` by `denominator`. \n\nYour function should:\n1. Raise a `ValueE... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7527,
"level": 1,
"question": "### Question: Implementing and Handling Exceptions with Cleanup\n\nYou are required to write a function `safe_division` that takes two arguments, `numerator` and `denominator`, and returns the result of dividing `numerator` by `denominator`. \n\nYour f... |
def longest_increasing_subsequence(a: list[int]) -> int:
if not a:
return 0
count = 1
for i in range(1, len(a)):
if a[i] > a[i-1]:
count += 1
return count
| simplelr_Taco | [
{
"content": "Question:\nXenia loves arrays. She has an array a of length n (1 ≤ n ≤ 100). The array is sorted in non-decreasing order, but it may contain duplicate elements. Xenia wants to know the length of the longest subsequence of elements that are strictly increasing.\n\nWrite a function `longest_increasi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7528,
"level": 1,
"question": "Xenia loves arrays. She has an array a of length n (1 ≤ n ≤ 100). The array is sorted in non-decreasing order, but it may contain duplicate elements. Xenia wants to know the length of the longest subsequence of elements that are strictly increasing.\n\... |
def find_nth_digit(n: int) -> int:
d = 1
count = 9
start = 1
while n > d * count:
n -= d * count
d += 1
count *= 10
start *= 10
number = start + (n - 1) // d
digit_index = (n - 1) % d
return int(str(number)[digit_index]) | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with finding the nth digit of the sequence formed by concatenating all decimal digits in the natural number order: \"123456789101112...\". Write a function `find_nth_digit(n)` that computes this efficiently.\n\n### Requirements\n1. **Function Signature**: `def find_nth_di... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7529,
"level": 1,
"question": "You are tasked with finding the nth digit of the sequence formed by concatenating all decimal digits in the natural number order: \"123456789101112...\". Write a function `find_nth_digit(n)` that computes this efficiently.\n\n### Requirements\n1. **Fun... |
def sum_of_even_numbers(numbers):
return sum(x for x in numbers if x % 2 == 0) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns the sum of all the even numbers in the list. If there are no even numbers, return 0. Write the function using Python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7530,
"level": 1,
"question": "Create a function that takes a list of integers and returns the sum of all the even numbers in the list. If there are no even numbers, return 0. Write the function using Python.",
"split": "train"
} |
def max_consecutive_sum(arr: list[int], k: int) -> int:
current_sum = sum(arr[:k])
max_sum = current_sum
for i in range(k, len(arr)):
current_sum += arr[i] - arr[i - k]
if current_sum > max_sum:
max_sum = current_sum
return max_sum | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given an array of integers `arr` and an integer `k`. Your task is to write a function that computes the maximum sum of `k` consecutive elements in the array.\n\nWrite a function called `max_consecutive_sum` that takes in the array and the integer `k` and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7531,
"level": 1,
"question": "### Problem Statement\n\nYou are given an array of integers `arr` and an integer `k`. Your task is to write a function that computes the maximum sum of `k` consecutive elements in the array.\n\nWrite a function called `max_consecutive_sum` that takes i... |
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result | simplelr_Codeforces | [
{
"content": "Question:\nWrite a function that calculates the factorial of a given positive integer n. The factorial of a number n is the product of all positive integers less than or equal to n.\n\nThe input is a single integer n (1 ≤ n ≤ 12).\n\nOutput the factorial of the given number n.\n\nFor example, the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7532,
"level": 1,
"question": "Write a function that calculates the factorial of a given positive integer n. The factorial of a number n is the product of all positive integers less than or equal to n.\n\nThe input is a single integer n (1 ≤ n ≤ 12).\n\nOutput the factorial of the g... |
def process_data(expression: str, local_vars: dict, global_vars: dict = None) -> str:
# Prepare the global variables dictionary
global_dict = global_vars.copy() if global_vars is not None else {}
# Prepare the local variables dictionary, ensuring we don't modify the original
local_dict = local_vars... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\nDemonstrate your understanding of Python's scope, naming, and exception handling mechanisms.\n\n#### Problem Description\nCreate a function called `process_data` that evaluates a given mathematical expression using Python's `eval()` function, manages variable scope corre... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7533,
"level": 1,
"question": "#### Objective\nDemonstrate your understanding of Python's scope, naming, and exception handling mechanisms.\n\n#### Problem Description\nCreate a function called `process_data` that evaluates a given mathematical expression using Python's `eval()` fun... |
def decimal_to_binary(num):
return bin(num)[2:] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that converts a decimal number `num` to its binary representation as a string. For example, if the input number is 13, the function should return \"1101\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7534,
"level": 1,
"question": "Create a function that converts a decimal number `num` to its binary representation as a string. For example, if the input number is 13, the function should return \"1101\".",
"split": "train"
} |
def num_decodings(s):
n = len(s)
if n == 0:
return 0
dp = [0] * (n + 1)
dp[0] = 1 # Base case: empty string has one way to decode
for i in range(1, n + 1):
current = 0
# Check single digit
if s[i-1] != '0':
current += dp[i-1]
# Check two digi... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` which represents an encoded message where each group of digits corresponds to a letter with '1' -> 'A', '2' -> 'B', ..., '26' -> 'Z', return _the total number of ways to decode the message_. You can assume that the input string contains only numeric characters and is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7535,
"level": 1,
"question": "Given a string `s` which represents an encoded message where each group of digits corresponds to a letter with '1' -> 'A', '2' -> 'B', ..., '26' -> 'Z', return _the total number of ways to decode the message_. You can assume that the input string conta... |
def check_pattern(input_list):
hello = False
world = False
for s in input_list:
hello |= 'hello' in s
world |= 'world' in s
if hello and world:
return True
return hello and world | simplelr_Filter | [
{
"content": "Question:\nThe input is a list of strings. Write a function to check whether the input list contains a specific pattern: the list should contain at least one substring \"hello\" and at least one substring \"world\". Both \"hello\" and \"world\" should be present as substrings in the list of string... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7536,
"level": 1,
"question": "The input is a list of strings. Write a function to check whether the input list contains a specific pattern: the list should contain at least one substring \"hello\" and at least one substring \"world\". Both \"hello\" and \"world\" should be present ... |
def find_logged_in_users(logs):
logs_dict = {}
for log in logs:
parts = log.split(':')
user = parts[0]
action = parts[1]
timestamp = int(parts[2])
if user not in logs_dict:
logs_dict[user] = []
logs_dict[user].append((timestamp, action))
resul... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `logs` where each log is a string formatted as `\"user_id:action_type:timestamp\"`. Each `user_id` is a unique identifier, `action_type` can be either \"login\" or \"logout\", and `timestamp` is an integer representing the time of the action in seconds. Your task... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7537,
"level": 1,
"question": "You are given a list of `logs` where each log is a string formatted as `\"user_id:action_type:timestamp\"`. Each `user_id` is a unique identifier, `action_type` can be either \"login\" or \"logout\", and `timestamp` is an integer representing the time ... |
def find_pairs(numbers, target):
pairs = set()
n = len(numbers)
for i in range(n):
for j in range(i + 1, n):
x = numbers[i]
y = numbers[j]
if x + y == target:
pair = tuple(sorted((x, y)))
pairs.add(pair)
sorted_pairs = sorted(pa... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes two inputs:\n\n 1) a list of integers\n 2) a target integer\n\nThe function should return a list of all unique pairs of numbers that sum up to the target integer. The pairs should be sorted in ascending order based on their first element. If there are m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7538,
"level": 1,
"question": "Write a function that takes two inputs:\n\n 1) a list of integers\n 2) a target integer\n\nThe function should return a list of all unique pairs of numbers that sum up to the target integer. The pairs should be sorted in ascending order based on ... |
def get_even_numbers(numbers):
even_numbers = [num for num in numbers if num % 2 == 0]
return even_numbers | simplelr_Filter | [
{
"content": "Question:\nImplement a function that takes in a list of integers and returns a new list containing only the even numbers from the original list. The function should handle an empty list by returning an empty list. Additionally, the function should be able to handle a list with all odd numbers by r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7539,
"level": 1,
"question": "Implement a function that takes in a list of integers and returns a new list containing only the even numbers from the original list. The function should handle an empty list by returning an empty list. Additionally, the function should be able to hand... |
def evaluate_postfix_expression(expression: str) -> int:
stack = []
tokens = expression.split()
for token in tokens:
if token in '+-*/':
b = stack.pop()
a = stack.pop()
if token == '+':
stack.append(a + b)
elif token == '-':
... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nFor this assessment, you need to demonstrate your understanding of data structures, specifically stacks, and simulate a scenario using stack operations. The problem addresses basic stack operations, and your solution hinge on effectively managing a stack and ensuring the op... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7540,
"level": 1,
"question": "### Context\nFor this assessment, you need to demonstrate your understanding of data structures, specifically stacks, and simulate a scenario using stack operations. The problem addresses basic stack operations, and your solution hinge on effectively m... |
import seaborn as sns
import seaborn.objects as so
import matplotlib as mpl
import matplotlib.pyplot as plt
def create_custom_plot():
diamonds = sns.load_dataset("diamonds")
# Create the main figure with subfigures
f = mpl.figure.Figure(figsize=(10, 6), dpi=100, layout="constrained")
sf1, sf2 = f.... | simplelr_Docs | [
{
"content": "Question:\n**Question**\n\nDesign a function `create_custom_plot` that utilizes the `seaborn.objects.Plot` class and the `matplotlib` library to create a multifaceted and customized plot. Your task is to plot data from the 'diamonds' dataset with the following specifications:\n\n### Specifications... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7541,
"level": 1,
"question": "**Question**\n\nDesign a function `create_custom_plot` that utilizes the `seaborn.objects.Plot` class and the `matplotlib` library to create a multifaceted and customized plot. Your task is to plot data from the 'diamonds' dataset with the following sp... |
def solve(S):
if not S:
return "_"
counts = [0] * 256
for c in S:
counts[ord(c)] += 1
for c in S:
if counts[ord(c)] == 1:
return c
return "_"
| simplelr_Taco | [
{
"content": "Question:\nGiven a string S, find the first non-repeating character in it and return it. If all characters are repeating or the string is empty, return an underscore (\"_\"). Input string may contain both uppercase and lowercase letters.\n\nExample 1:\nInput:\nS = \"swiss\"\nOutput:\nw\nExplanatio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7542,
"level": 1,
"question": "Given a string S, find the first non-repeating character in it and return it. If all characters are repeating or the string is empty, return an underscore (\"_\"). Input string may contain both uppercase and lowercase letters.\n\nExample 1:\nInput:\nS ... |
def string_to_int(s):
s = s.strip()
if not s:
return 0
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
elif s[0] == '+':
s = s[1:]
result = 0
for c in s:
digit = ord(c) - ord('0')
result = result * 10 + digit
return sign * result | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to convert a string to an integer in Python without using the built-in int() function. Consider both positive and negative integers, and also handle leading and trailing spaces.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7543,
"level": 1,
"question": "Write a function to convert a string to an integer in Python without using the built-in int() function. Consider both positive and negative integers, and also handle leading and trailing spaces.",
"split": "train"
} |
from urllib.parse import urlparse, urlunparse, parse_qs
def manipulate_and_validate_urls(url: str) -> dict:
parsed = urlparse(url)
# Extract parsed components into a dictionary
parsed_dict = {
'scheme': parsed.scheme,
'netloc': parsed.netloc,
'path': parsed.path,
'param... | simplelr_Docs | [
{
"content": "Question:\n### URL Manipulation and Validation with `urllib.parse`\n\n**Objective:**\nWrite a Python function to parse, manipulate, and validate URLs using the `urllib.parse` module. Your function should demonstrate your understanding of both fundamental and advanced concepts of URL parsing and co... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7544,
"level": 1,
"question": "### URL Manipulation and Validation with `urllib.parse`\n\n**Objective:**\nWrite a Python function to parse, manipulate, and validate URLs using the `urllib.parse` module. Your function should demonstrate your understanding of both fundamental and adva... |
def nested_dict_search(dict_obj: dict, key: str) -> any:
if key in dict_obj:
return dict_obj[key]
for value in dict_obj.values():
if isinstance(value, dict):
result = nested_dict_search(value, key)
if result is not None:
return result
return None | simplelr_Package | [
{
"content": "Question:\nWrite a Python function `nested_dict_search` that takes in two inputs: `dict_obj`, which is a nested dictionary, and `key`, which is a string representing the key to search for. The function should return the value associated with the first occurrence of the given key in the nested dict... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7545,
"level": 1,
"question": "Write a Python function `nested_dict_search` that takes in two inputs: `dict_obj`, which is a nested dictionary, and `key`, which is a string representing the key to search for. The function should return the value associated with the first occurrence ... |
def average_amount(transactions: list, start_time: int, end_time: int) -> float:
total = 0.0
count = 0
for timestamp, amount in transactions:
if start_time <= timestamp <= end_time:
total += amount
count += 1
return total / count if count != 0 else 0.0 | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\n\nYou are given a list of transactions represented by a list of lists. Each transaction contains an epoch timestamp and an amount. Write a function `average_amount(transactions: list, start_time: int, end_time: int) -> float` that calculates the average transacti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7546,
"level": 1,
"question": "### Problem Statement:\n\nYou are given a list of transactions represented by a list of lists. Each transaction contains an epoch timestamp and an amount. Write a function `average_amount(transactions: list, start_time: int, end_time: int) -> float` th... |
def is_valid_huffman_encoding(encoded_string: str, huffman_tree: dict) -> bool:
code_to_char = {v: k for k, v in huffman_tree.items()}
code_lengths = {len(code) for code in code_to_char}
i = 0
n = len(encoded_string)
while i < n:
found = False
for l in code_lengths:
... | simplelr_Algorithm | [
{
"content": "Question:\nYou need to write a function to verify if a given string is a valid Huffman encoded string based on a provided binary Huffman tree.\n\n### Input:\n- A string `encoded_string` consisting of `0`s and `1`s.\n- A dictionary `huffman_tree` where keys are characters and values are their corre... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7547,
"level": 1,
"question": "You need to write a function to verify if a given string is a valid Huffman encoded string based on a provided binary Huffman tree.\n\n### Input:\n- A string `encoded_string` consisting of `0`s and `1`s.\n- A dictionary `huffman_tree` where keys are ch... |
def reverse_list(lst):
reversed_lst = []
for i in range(len(lst)-1, -1, -1):
reversed_lst.append(lst[i])
return reversed_lst | simplelr_Evol | [
{
"content": "Question:\nGiven a list of integers, write a function to reverse the list without using built-in reverse functions. Return the reversed list.\n\n```python\ndef reverse_list(lst):\n # Your code here\n \n# Example usage:\n# Input: [1, 2, 3, 4, 5]\n# Output: [5, 4, 3, 2, 1]\n```\nAnswer:\nLet's... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7548,
"level": 1,
"question": "Given a list of integers, write a function to reverse the list without using built-in reverse functions. Return the reversed list.\n\n```python\ndef reverse_list(lst):\n # Your code here\n \n# Example usage:\n# Input: [1, 2, 3, 4, 5]\n# Output: [... |
def get_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0] | simplelr_Filter | [
{
"content": "Question:\nThis is a fun coding challenge!\n\nCan you write a Python function that takes a list of integers as input and returns a new list containing only the even numbers from the input list?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7549,
"level": 1,
"question": "This is a fun coding challenge!\n\nCan you write a Python function that takes a list of integers as input and returns a new list containing only the even numbers from the input list?",
"split": "train"
} |
from typing import List, Tuple
def range_pow_sum(powers: List[int], queries: List[Tuple[int, int]]) -> List[int]:
# Compute the prefix sum array
prefix = [0]
for num in powers:
prefix.append(prefix[-1] + num)
# Process each query and collect results
result = []
for l, r in queries:... | simplelr_Apps | [
{
"content": "Question:\nHelp Captain Marvel by summing her powers in an efficient algorithm. Captain Marvel has a list of powers that she uses while fighting the villains in different battles. She frequently checks the sum of her powers over a given range of indices to strategize her next move.\n\nYou are to w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7550,
"level": 1,
"question": "Help Captain Marvel by summing her powers in an efficient algorithm. Captain Marvel has a list of powers that she uses while fighting the villains in different battles. She frequently checks the sum of her powers over a given range of indices to strate... |
from collections import defaultdict
import re
def analyze_log_file(log_file_path: str) -> dict[str, int]:
ip_counts = defaultdict(int)
ip_pattern = re.compile(r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
try:
with open(log_file_path, 'r') as log_file:
for line in log_file:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Log File Analyzer\n\nYou are tasked to develop a simple log file analyzer that processes server log entries to extract information regarding the number of requests made by each IP address. \n\n### Requirements:\n1. **Input**: A string representing the path to the log file.\n2. **Out... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7551,
"level": 1,
"question": "### Log File Analyzer\n\nYou are tasked to develop a simple log file analyzer that processes server log entries to extract information regarding the number of requests made by each IP address. \n\n### Requirements:\n1. **Input**: A string representing ... |
def can_complete_circuit(fuel, cost):
n = len(fuel)
total_fuel = sum(fuel)
total_cost = sum(cost)
if total_fuel < total_cost:
return -1
current = 0
min_fuel = 0
start = 0
for i in range(n):
current += fuel[i] - cost[i]
if current < min_fuel:
... | simplelr_Taco | [
{
"content": "Question:\nA car race simulation is being held on a circular track with `n` checkpoints. Each checkpoint has a pitstop with a certain amount of fuel and requires a specific amount of fuel to reach the next checkpoint. You are given two equal-length arrays `fuel` and `cost`, where `fuel[i]` represe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7552,
"level": 1,
"question": "A car race simulation is being held on a circular track with `n` checkpoints. Each checkpoint has a pitstop with a certain amount of fuel and requires a specific amount of fuel to reach the next checkpoint. You are given two equal-length arrays `fuel` ... |
def sum_two_numbers(a, b):
return a + b | simplelr_Filter | [
{
"content": "Question:\nI need to write a Python function that takes two integers as input and returns their sum. How can I do that?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7553,
"level": 1,
"question": "I need to write a Python function that takes two integers as input and returns their sum. How can I do that?",
"split": "train"
} |
def calculate_score(submissions):
if not submissions:
return 0
total = 0
all_correct = True
all_under_10 = True
for correct, time in submissions:
if correct:
if time < 10:
total += 15
elif 10 <= time <= 20:
total += 10... | simplelr_Taco | [
{
"content": "Question:\nYou've been assigned to create the scoring function for a Coding Marathon Challenge!\n\nScoring specifications:\n\n* 0 points - any incorrect answer\n* 5 points - correct answer that took more than 20 minutes\n* 10 points - correct answer that took between 10 and 20 minutes\n* 15 points... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7554,
"level": 1,
"question": "You've been assigned to create the scoring function for a Coding Marathon Challenge!\n\nScoring specifications:\n\n* 0 points - any incorrect answer\n* 5 points - correct answer that took more than 20 minutes\n* 10 points - correct answer that took bet... |
def encode_run_length(s):
if not s:
return ""
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(f"{current_char}{count}")
current_char = char
count = 1
resul... | simplelr_Apps | [
{
"content": "Question:\n# Task\n\nWrite a function `encode_run_length` that takes a string and returns its run-length encoding. Run-length encoding is a simple form of data compression where consecutive data elements are replaced with just one data value and a count.\n\nFor example, the string `\"aaabbccc\"` w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7555,
"level": 1,
"question": "# Task\n\nWrite a function `encode_run_length` that takes a string and returns its run-length encoding. Run-length encoding is a simple form of data compression where consecutive data elements are replaced with just one data value and a count.\n\nFor e... |
def element_frequencies(lst):
freq_dict = {}
for item in lst:
if item in freq_dict:
freq_dict[item] += 1
else:
freq_dict[item] = 1
return freq_dict | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to detect the frequency of each unique element in a list. You should return a dictionary where keys are the unique elements and values are their corresponding frequencies.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7556,
"level": 1,
"question": "Write a python function to detect the frequency of each unique element in a list. You should return a dictionary where keys are the unique elements and values are their corresponding frequencies.",
"split": "train"
} |
def min_steps_to_1337_hangman(s):
count = 0
for char in s:
if char in {'a', 'e', 'o'}:
count += 1
return count | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the minimum number of steps required to convert a string to its 1337-hangman form. In 1337-hangman, every 'a' is replaced by '4', 'e' is replaced by '3', and 'o' is replaced by '0'.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7557,
"level": 1,
"question": "Write a python function to find the minimum number of steps required to convert a string to its 1337-hangman form. In 1337-hangman, every 'a' is replaced by '4', 'e' is replaced by '3', and 'o' is replaced by '0'.",
"split": "train"
} |
def even_before_odd(nums):
evens = []
odds = []
for num in nums:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens + odds | simplelr_Filter | [
{
"content": "Question:\nGiven a list of integers, write a function in Python to sort the list such that all even numbers come before all odd numbers, while maintaining the relative order of the even and odd numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7558,
"level": 1,
"question": "Given a list of integers, write a function in Python to sort the list such that all even numbers come before all odd numbers, while maintaining the relative order of the even and odd numbers.",
"split": "train"
} |
def generate_identifiers(submissions):
counts = {}
result = []
for username in submissions:
current = counts.get(username, 0)
result.append(f"{username}-{current}")
counts[username] = current + 1
return result
| simplelr_Taco | [
{
"content": "Question:\nYou are organizing a competition where each participant needs to submit a username with a unique identifier. The format of the identifier is `X-y`, where `X` is a unique username, and `y` is a non-negative integer that increments for each subsequent submission by the same user. For the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7559,
"level": 1,
"question": "You are organizing a competition where each participant needs to submit a username with a unique identifier. The format of the identifier is `X-y`, where `X` is a unique username, and `y` is a non-negative integer that increments for each subsequent su... |
def min_moves_to_equal_elements(arr):
arr.sort()
mid = len(arr) // 2
median = arr[mid]
return sum(abs(x - median) for x in arr) | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `arr`, determine the minimum number of moves required to make all elements in the array equal. In one move, you can increment or decrement any element of the array by 1. Return the minimum number of moves needed to make all elements the same.\n\nFor example, for t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7560,
"level": 1,
"question": "Given an integer array `arr`, determine the minimum number of moves required to make all elements in the array equal. In one move, you can increment or decrement any element of the array by 1. Return the minimum number of moves needed to make all eleme... |
def max_subarray_sum(arr):
if not arr:
return 0 # Return 0 for empty array, or adjust as needed
max_sum = current_sum = arr[0]
for num in arr[1:]:
current_sum = max(num, current_sum + num)
if current_sum > max_sum:
max_sum = current_sum
return max_sum | simplelr_Filter | [
{
"content": "Question:\nHow can I find the maximum sum of a subarray within a given 1D array using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7561,
"level": 1,
"question": "How can I find the maximum sum of a subarray within a given 1D array using Python?",
"split": "train"
} |
def binary_to_decimal(binary_str, range_digits):
# Check if the binary string is valid
if not all(char in {'0', '1'} for char in binary_str):
return "Invalid binary number"
# Check if range is valid
if range_digits < 0:
return 0
# Determine the length to consider
length... | simplelr_Filter | [
{
"content": "Question:\nWe are tasked with making a program that contains a function to convert a binary number into decimal and the function should take exactly one parameter which marks the valid range of the desired digits for the conversion. So a binary number of \"101010\" with a range of 2 would only con... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7562,
"level": 1,
"question": "We are tasked with making a program that contains a function to convert a binary number into decimal and the function should take exactly one parameter which marks the valid range of the desired digits for the conversion. So a binary number of \"101010... |
def set_difference(A, B):
return A - B
# Test cases
# Test Case 1
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(set_difference(A, B)) # Expected Output: {1, 2}
# Test Case 2
A = {2, 3, 4}
B = {1, 2, 3, 4, 5}
print(set_difference(A, B)) # Expected Output: set()
# Test Case 3
A = set()
B = {1, 2, 3}
print(set_differen... | simplelr_Filter | [
{
"content": "Question:\nGiven two sets of numbers, set A and set B. Write a python function that takes these two sets as parameters and returns a set that represents the difference between set A and set B, i.e., it should return elements that are in set A but not in set B. Also, ensure it can handle large sets... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7563,
"level": 1,
"question": "Given two sets of numbers, set A and set B. Write a python function that takes these two sets as parameters and returns a set that represents the difference between set A and set B, i.e., it should return elements that are in set A but not in set B. Al... |
def find_nth_digit(n: int) -> int:
digits = 1
count = 9
start = 1
while n > digits * count:
n -= digits * count
digits += 1
count *= 10
start *= 10
number = start + (n - 1) // digits
digit_index = (n - 1) % digits
return int(str(number)[digit_index]) | simplelr_Data_Structure | [
{
"content": "Question:\n**Problem Description:**\n\nWrite a function `find_nth_digit(n)` that finds the nth digit of an infinite sequence formed by concatenating all positive integers sequentially: 1234567891011121314...\n\n### Input:\n* An integer `n` (1 ≤ n ≤ 10^9), representing the position in the infinite ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7564,
"level": 1,
"question": "**Problem Description:**\n\nWrite a function `find_nth_digit(n)` that finds the nth digit of an infinite sequence formed by concatenating all positive integers sequentially: 1234567891011121314...\n\n### Input:\n* An integer `n` (1 ≤ n ≤ 10^9), represe... |
def feeder_schedule_check(expected_times, actual_times):
if len(expected_times) != len(actual_times):
return "Feeder needs adjustment!"
for expected, actual in zip(expected_times, actual_times):
if expected != actual:
return "Feeder needs adjustment!"
return "Feeder working perfe... | simplelr_Apps | [
{
"content": "Question:\n### Cat Feeder\n\nYou are the proud owner of several cats and you have just purchased an automatic cat feeder. This feeder follows a strict schedule and dispenses food at predefined times throughout the day.\n\nYour objective is to ensure that the feeder is dispensing food at the correc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7565,
"level": 1,
"question": "### Cat Feeder\n\nYou are the proud owner of several cats and you have just purchased an automatic cat feeder. This feeder follows a strict schedule and dispenses food at predefined times throughout the day.\n\nYour objective is to ensure that the feed... |
def add(a, b):
return a + b | simplelr_Filter | [
{
"content": "Question:\nThis is an example of a function:\n\n```python\ndef square(x):\n return x * x\n```\n\nLet's break it down:\n\n* **`def`:** This keyword indicates you're defining a new function.\n\n* **`square`:** This is the name you've chosen for your function. It's best to choose descriptive names t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7566,
"level": 1,
"question": "This is an example of a function:\n\n```python\ndef square(x):\n return x * x\n```\n\nLet's break it down:\n\n* **`def`:** This keyword indicates you're defining a new function.\n\n* **`square`:** This is the name you've chosen for your function. It's... |
def is_match(s: str, p: str) -> bool:
n = len(s)
m = len(p)
dp = [[False] * (m + 1) for _ in range(n + 1)]
dp[0][0] = True # Empty string matches empty pattern
for i in range(n + 1):
for j in range(m + 1):
if i == 0 and j == 0:
continue # Already handled
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Regular Expression Matching Using Dynamic Programming\n\n#### Problem Description\nYou are asked to implement a function that determines if a given string matches a pattern. The pattern may contain special characters:\n- `.` which matches any single character.\n- `*` which matches z... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7567,
"level": 1,
"question": "### Regular Expression Matching Using Dynamic Programming\n\n#### Problem Description\nYou are asked to implement a function that determines if a given string matches a pattern. The pattern may contain special characters:\n- `.` which matches any singl... |
from typing import List
def rotate_list(nums: List[int], k: int) -> List[int]:
if not nums:
return []
len_nums = len(nums)
effective_k = k % len_nums
if effective_k == 0:
return list(nums)
return nums[-effective_k:] + nums[:-effective_k] | simplelr_Algorithm | [
{
"content": "Question:\n### List Number Rotation Challenge\n\nUnderstanding and manipulating lists is a fundamental skill in programming. For this challenge, you will write a function to perform a rotation operation on a list.\n\n### Problem Statement\nImplement a function `rotate_list(nums: List[int], k: int)... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7568,
"level": 1,
"question": "### List Number Rotation Challenge\n\nUnderstanding and manipulating lists is a fundamental skill in programming. For this challenge, you will write a function to perform a rotation operation on a list.\n\n### Problem Statement\nImplement a function `r... |
def find_first_greater_element(arr):
for i in range(1, len(arr)):
if arr[i] > arr[i-1]:
return i
return -1 | simplelr_Filter | [
{
"content": "Question:\nLet's say we have an array of integers like [1,2,3,4,5]. What would be the algorithm to find the first element that is greater than the previous one in the array and return its index. If no such element exists, return -1.\n\nHere is an example:\nInput: [1,2,3,4,5]\nOutput: 1\nExplanatio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7569,
"level": 1,
"question": "Let's say we have an array of integers like [1,2,3,4,5]. What would be the algorithm to find the first element that is greater than the previous one in the array and return its index. If no such element exists, return -1.\n\nHere is an example:\nInput:... |
def first_non_repeating_char(s):
# Create a dictionary to store the frequency of each character
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
# Loop through the string to find the first non-repeating character
for char in ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the first non-repeating character in a given string, or return -1 if there is no such character.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7570,
"level": 1,
"question": "Write a python function to find the first non-repeating character in a given string, or return -1 if there is no such character.",
"split": "train"
} |
from collections import Counter
def sum_of_unique(nums: list[int]) -> int:
counts = Counter(nums)
total = 0
for num in counts:
if counts[num] == 1:
total += num
return total | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of All Unique Numbers in a List\n\n#### Context:\nYou have been assigned the task of processing lists of integers to identify and sum all unique elements (elements that appear exactly once) in each list. This can be useful in various scenarios, such as data analysis or inventory... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7571,
"level": 1,
"question": "### Sum of All Unique Numbers in a List\n\n#### Context:\nYou have been assigned the task of processing lists of integers to identify and sum all unique elements (elements that appear exactly once) in each list. This can be useful in various scenarios,... |
def remove_duplicates(input_list):
seen = set()
result = []
for item in input_list:
if item not in seen:
result.append(item)
seen.add(item)
return result | simplelr_Filter | [
{
"content": "Question:\nExercise: Write a function called `remove_duplicates` which takes a list as input and returns a new list with duplicate elements removed, preserving the original order of elements.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7572,
"level": 1,
"question": "Exercise: Write a function called `remove_duplicates` which takes a list as input and returns a new list with duplicate elements removed, preserving the original order of elements.",
"split": "train"
} |
def intersect(a, b):
# Convert b to a set for O(1) membership checks
b_set = set(b)
# Collect elements in a that are also in b_set
return [value for value in a if value in b_set]
a = {'apple', 'banana', 'cherry'}
b = {'banana', 'cherry', 'date'}
print(intersect(a, b)) # Output: ['banana', 'cherry'] | simplelr_Filter | [
{
"content": "Question:\ndef intersect(a, b):\n return [value for value in a if value in b]\n\n\na = {'apple', 'banana', 'cherry'}\nb = {'banana', 'cherry', 'date'}\n\nprint(intersect(a, b))\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7573,
"level": 1,
"question": "def intersect(a, b):\n return [value for value in a if value in b]\n\n\na = {'apple', 'banana', 'cherry'}\nb = {'banana', 'cherry', 'date'}\n\nprint(intersect(a, b))",
"split": "train"
} |
def prime_factors(n):
factors = []
if n < 2:
return factors
while n % 2 == 0:
factors.append(2)
n = n // 2
i = 3
while i * i <= n:
while n % i == 0:
factors.append(i)
n = n // i
i += 2
if n > 2:
factors.append(n)
return ... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the prime factors of a given number. The function should return a list of prime factors.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7574,
"level": 1,
"question": "Write a Python function to find the prime factors of a given number. The function should return a list of prime factors.",
"split": "train"
} |
def calculate_inventory(candies, wrappers, stems):
return {"packages": wrappers, "fruit": stems} | simplelr_Apps | [
{
"content": "Question:\nInventor Anna has developed a new recipe that combines packaged candies and fruits. Each package of candies contains exactly 4 candies and 1 wrapper, each fruit contains exactly 1 fruit and 1 stem. She has invited a large group of friends to taste her new recipe at her home, so she has ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7575,
"level": 1,
"question": "Inventor Anna has developed a new recipe that combines packaged candies and fruits. Each package of candies contains exactly 4 candies and 1 wrapper, each fruit contains exactly 1 fruit and 1 stem. She has invited a large group of friends to taste her ... |
def int_to_binary(n):
return bin(n) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes an integer as input and prints its binary representation. The binary representation should be displayed as a string prefixed with '0b' to indicate that it is a binary number. For example, if the input is 10, the output should be '0b1010'.\nAnswer:\nLet... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7576,
"level": 1,
"question": "Write a Python function that takes an integer as input and prints its binary representation. The binary representation should be displayed as a string prefixed with '0b' to indicate that it is a binary number. For example, if the input is 10, the outpu... |
def evaluate_expression(expression: str) -> int:
tokens = []
i = 0
n = len(expression)
# Read the first number
num_str = ''
while i < n and expression[i].isdigit():
num_str += expression[i]
i += 1
tokens.append(int(num_str))
# Read subsequent operators and numbe... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are tasked with implementing a function that evaluates an arithmetic expression represented as a string. The expression contains only non-negative integers, addition (+), and subtraction (-) operators. \n\n### Requirements\n\nImplement a function `evaluate_e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7577,
"level": 1,
"question": "### Problem Statement\n\nYou are tasked with implementing a function that evaluates an arithmetic expression represented as a string. The expression contains only non-negative integers, addition (+), and subtraction (-) operators. \n\n### Requirements\... |
def climbStairs(n: int) -> int:
if n <= 2:
return n
a, b = 1, 2 # Represents ways[n-2], ways[n-1]
for _ in range(3, n + 1):
a, b = b, a + b
return b | simplelr_Filter | [
{
"content": "Question:\n### Introduction to My Problem\nI am trying to figure out how to solve a typical dynamic programming problem using Python. The problem is asking me to count the number of ways to climb `n` steps where you can either climb 1 or 2 steps at a time. \n\n### My Current Solution\n```python\nd... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7578,
"level": 1,
"question": "### Introduction to My Problem\nI am trying to figure out how to solve a typical dynamic programming problem using Python. The problem is asking me to count the number of ways to climb `n` steps where you can either climb 1 or 2 steps at a time. \n\n##... |
import pandas as pd
def convert_and_calculate(data, date_columns):
# Convert the specified columns to datetime
data[date_columns] = data[date_columns].apply(pd.to_datetime)
# Collect all dates to find the earliest and latest
all_dates = pd.concat([data[col] for col in date_columns])
# Cal... | simplelr_Package | [
{
"content": "Question:\nWrite a function that takes a pandas DataFrame containing date columns in string format and converts these columns to datetime objects. The function should then create a new column that calculates the difference in days between the earliest and latest date in the DataFrame. The returned... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7579,
"level": 1,
"question": "Write a function that takes a pandas DataFrame containing date columns in string format and converts these columns to datetime objects. The function should then create a new column that calculates the difference in days between the earliest and latest ... |
def has_pair_with_sum(nums, k):
if len(nums) < 2:
return False
left = 0
right = len(nums) - 1
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == k:
return True
elif current_sum < k:
left += 1
else:
righ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` sorted in non-decreasing order. Determine if there exists a pair of distinct elements in the array whose sum equals a given target `k`. Return `true` if such a pair exists, otherwise return `false`.\nAnswer:\nLet's think step by step.\n",
"role"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7580,
"level": 1,
"question": "You are given an integer array `nums` sorted in non-decreasing order. Determine if there exists a pair of distinct elements in the array whose sum equals a given target `k`. Return `true` if such a pair exists, otherwise return `false`.",
"split": "t... |
def find_in_serialized(serialized_tree: str, target: int) -> bool:
tokens = serialized_tree.split()
for token in tokens:
if token == '#':
continue
if int(token) == target:
return True
return False | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given classes and functions to serialize and deserialize a binary tree. Serialization converts the tree to a string in a pre-order traversal way, and deserialization converts that string back into the tree structure. Your task is to write a function `find_in_serialized` that sea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7581,
"level": 1,
"question": "You are given classes and functions to serialize and deserialize a binary tree. Serialization converts the tree to a string in a pre-order traversal way, and deserialization converts that string back into the tree structure. Your task is to write a fun... |
def max_consecutive_ones(n):
if n == 0:
return 0
max_count = 0
current_count = 0
n = abs(n)
while n > 0:
if n & 1:
current_count += 1
if current_count > max_count:
max_count = current_count
else:
current_count = 0
n ... | simplelr_Filter | [
{
"content": "Question:\nWrite a code to find the maximum number of consecutive 1's in the binary representation of a given integer\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7582,
"level": 1,
"question": "Write a code to find the maximum number of consecutive 1's in the binary representation of a given integer",
"split": "train"
} |
def sum_of_squares_difference(n: int) -> int:
if type(n) is not int:
raise TypeError("n must be an integer")
if n < 1:
raise ValueError("n must be a positive integer")
return (n * (n + 1) * (n - 1) * (3 * n + 2)) // 12 | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of Squares Difference\n\n#### Background\nThe sum of the squares of the first n natural numbers is given by:\n\n\\[ S1 = \\sum_{i=1}^n i^2 \\]\n\nThe square of the sum of the first n natural numbers is given by:\n\n\\[ S2 = \\left( \\sum_{i=1}^n i \\right)^2 \\]\n\nThe differenc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7583,
"level": 1,
"question": "### Sum of Squares Difference\n\n#### Background\nThe sum of the squares of the first n natural numbers is given by:\n\n\\[ S1 = \\sum_{i=1}^n i^2 \\]\n\nThe square of the sum of the first n natural numbers is given by:\n\n\\[ S2 = \\left( \\sum_{i=1}^... |
def is_multiple_of_11(num: str) -> bool:
reversed_num = num[::-1]
sum_odd = 0
sum_even = 0
for i, c in enumerate(reversed_num):
digit = int(c)
if i % 2 == 0:
sum_odd += digit
else:
sum_even += digit
return (sum_odd - sum_even) % 11 == 0 | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a large integer represented as a string `num`, which consists only of digits. We want to determine if this large number is a multiple of 11. For context, a number is divisible by 11 if the difference between the sum of its digits at odd positions and the sum of its digits ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7584,
"level": 1,
"question": "You are given a large integer represented as a string `num`, which consists only of digits. We want to determine if this large number is a multiple of 11. For context, a number is divisible by 11 if the difference between the sum of its digits at odd p... |
def smallest_missing_positive(nums):
positive_set = set(num for num in nums if num > 0)
current = 1
while current in positive_set:
current += 1
return current | simplelr_Filter | [
{
"content": "Question:\nHere's a problem I'm trying to solve:\n\n**Problem:** You are given a list of integers. Find the smallest positive integer that is not present in the list.\n\n**Example:**\n\n```\nInput: [1, 2, 0]\nOutput: 3\n\nInput: [3, 4, -1, 1]\nOutput: 2\n\nInput: [7, 8, 9, 11, 12]\nOutput: 1\n```\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7585,
"level": 1,
"question": "Here's a problem I'm trying to solve:\n\n**Problem:** You are given a list of integers. Find the smallest positive integer that is not present in the list.\n\n**Example:**\n\n```\nInput: [1, 2, 0]\nOutput: 3\n\nInput: [3, 4, -1, 1]\nOutput: 2\n\nInput:... |
def fibonacci(n):
"""
Generates the Fibonacci sequence up to the nth term.
Args:
n (int): The number of terms in the sequence.
Returns:
list: A list containing the first n Fibonacci numbers.
"""
if n <= 0:
return []
elif n == 1:
return [0]
elif n... | simplelr_Filter | [
{
"content": "Question:\nCan you generate a Python function to calculate the Fibonacci sequence up to the nth term?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7586,
"level": 1,
"question": "Can you generate a Python function to calculate the Fibonacci sequence up to the nth term?",
"split": "train"
} |
def reversefibonacci(n):
if n == 0:
return []
fibs = []
a, b = 0, 1
for _ in range(n):
fibs.append(a)
a, b = b, a + b
return fibs[::-1] | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nYou are part of a puzzle-loving developer group, and you enjoy crafting creative problem-solving activities. Your group wants to use a conceptually simple but logically challenging algorithm to demonstrate the importance of understanding looping constructs and conditionals ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7587,
"level": 1,
"question": "### Context\nYou are part of a puzzle-loving developer group, and you enjoy crafting creative problem-solving activities. Your group wants to use a conceptually simple but logically challenging algorithm to demonstrate the importance of understanding l... |
from typing import List
def decode_intervals(intervals: List[str]) -> List[str]:
parsed = []
for interval in intervals:
s, e = interval.split('-')
parsed.append((int(s), int(e)))
if not parsed:
return []
# Sort intervals based on the start value
parsed.sort(key=lam... | simplelr_Taco | [
{
"content": "Question:\nWrite a function `decode_intervals` that takes a list of strings representing intervals and returns the merged list of intervals. Each string in the input list is of the form `'start-end'`, where `start` and `end` are integers representing the interval (inclusive). The function should m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7588,
"level": 1,
"question": "Write a function `decode_intervals` that takes a list of strings representing intervals and returns the merged list of intervals. Each string in the input list is of the form `'start-end'`, where `start` and `end` are integers representing the interval... |
import pwd
def get_user_info(parameter):
if isinstance(parameter, int):
try:
pwd_entry = pwd.getpwuid(parameter)
except:
return None
elif isinstance(parameter, str):
try:
pwd_entry = pwd.getpwnam(parameter)
except:
return None
... | simplelr_Docs | [
{
"content": "Question:\n**Question: Unix User Password Database Query**\n\nUsing the `pwd` module, write a function `get_user_info(parameter)` that takes a single parameter, which can be either an integer (numeric user ID) or a string (user name). Depending on the type and validity of the input, the function s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7589,
"level": 1,
"question": "**Question: Unix User Password Database Query**\n\nUsing the `pwd` module, write a function `get_user_info(parameter)` that takes a single parameter, which can be either an integer (numeric user ID) or a string (user name). Depending on the type and va... |
from collections import defaultdict
def favorite_genres(user_map, color_map):
result = defaultdict(list)
for user, color in color_map:
if user in user_map:
for genre in user_map[user]:
result[genre].append(color)
return dict(result) | simplelr_Filter | [
{
"content": "Question:\nHere is a Python solution for \"Favorite Genres\" problem, where given an object that describes each user's favorite genres and an array of tuples, each tuple containing user ID and a color associated with that user, we need to get the color (associated with each user) for each genre:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7590,
"level": 1,
"question": "Here is a Python solution for \"Favorite Genres\" problem, where given an object that describes each user's favorite genres and an array of tuples, each tuple containing user ID and a color associated with that user, we need to get the color (associate... |
def find_min_max(lst):
return (min(lst), max(lst)) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the minimum and maximum values in a given list of integers. The function should take a list of integers as an argument and return a tuple containing the minimum and maximum values. For example, if the input list is [4, 1, 7, 3, 9, 5], the function should ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7591,
"level": 1,
"question": "Write a Python function to find the minimum and maximum values in a given list of integers. The function should take a list of integers as an argument and return a tuple containing the minimum and maximum values. For example, if the input list is [4, 1... |
def remove_bit(num: int, i: int) -> int:
if i < 0:
return num
bl = num.bit_length()
if i >= bl:
return num
higher = (num >> (i + 1)) << i
lower = num & ((1 << i) - 1)
return higher | lower | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are working on optimizing a low-level system algorithm where control over individual bits in a binary representation is crucial. You have a function `remove_bit(num, i)` which allows you to remove the bit at a specified position `i` from the binary representation of th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7592,
"level": 1,
"question": "### Scenario\nYou are working on optimizing a low-level system algorithm where control over individual bits in a binary representation is crucial. You have a function `remove_bit(num, i)` which allows you to remove the bit at a specified position `i` f... |
def binary_to_decimal(binary_string):
return int(binary_string, 2) | simplelr_Filter | [
{
"content": "Question:\nI need to create a function that takes a binary string and returns the decimal equivalent. How can I do this in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7593,
"level": 1,
"question": "I need to create a function that takes a binary string and returns the decimal equivalent. How can I do this in Python?",
"split": "train"
} |
def filter_by_letter(strings, letter):
result = []
start = letter.lower()
for s in strings:
if not s:
continue
if s[0].lower() == start:
result.append(s)
return result
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of strings and a starting letter. The function should return a new list containing only the strings from the original list that start with the specified letter. The comparison should be case-insensitive.\n\n```python\nstrings = ['apple', 'Banana', 'apr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7594,
"level": 1,
"question": "Write a function that takes a list of strings and a starting letter. The function should return a new list containing only the strings from the original list that start with the specified letter. The comparison should be case-insensitive.\n\n```python\... |
def add(a, b):
return a + b | simplelr_Filter | [
{
"content": "Question:\nI need to create a Python function that can add two integers and return the result. Can you provide a simple example of such a function?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7595,
"level": 1,
"question": "I need to create a Python function that can add two integers and return the result. Can you provide a simple example of such a function?",
"split": "train"
} |
import sysconfig
def print_and_verify_sysconfig(required_paths, required_vars):
"""
Prints detailed configuration information including current platform,
Python version, and installation paths. Also verifies if the specified
paths and configuration variables exist and meet certain criteria.
Args:... | simplelr_Docs | [
{
"content": "Question:\n**Coding Assessment Question**\n\n**Objective**: Assess the ability to work with Python's \"sysconfig\" module to retrieve and manipulate configuration information.\n\n**Problem Statement**:\n\nYou are tasked with creating a function that prints out detailed configuration information fo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7596,
"level": 1,
"question": "**Coding Assessment Question**\n\n**Objective**: Assess the ability to work with Python's \"sysconfig\" module to retrieve and manipulate configuration information.\n\n**Problem Statement**:\n\nYou are tasked with creating a function that prints out de... |
def char_frequency(s):
frequency = {}
for char in s:
frequency[char] = frequency.get(char, 0) + 1
return frequency | simplelr_Filter | [
{
"content": "Question:\nDevelop a Python function that generates a dictionary with the unique characters from a provided string as keys and their corresponding frequency of appearance as values.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7597,
"level": 1,
"question": "Develop a Python function that generates a dictionary with the unique characters from a provided string as keys and their corresponding frequency of appearance as values.",
"split": "train"
} |
def plus_one(digits):
new_digits = list(digits)
carry = 1 # We're adding 1 to the number, starting with the least significant digit
for i in reversed(range(len(new_digits))):
total = new_digits[i] + carry
if total == 10:
new_digits[i] = 0
carry = 1
else:... | simplelr_Data_Structure | [
{
"content": "Question:\n### Plus-One Algorithm Implementation\n\nYou are provided with an array of non-negative integers representing a non-negative number in big-endian format. Each element in the array corresponds to a digit, with the most significant digit at the head of the array.\n\nYour task is to implem... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7598,
"level": 1,
"question": "### Plus-One Algorithm Implementation\n\nYou are provided with an array of non-negative integers representing a non-negative number in big-endian format. Each element in the array corresponds to a digit, with the most significant digit at the head of t... |
def min_moves_to_equal_points(points):
points.sort()
n = len(points)
mid = n // 2
median = points[mid]
return sum(abs(p - median) for p in points) | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `points` representing the coordinates of points on a number line, return the **minimum number of moves** required to make all the points equal. A move involves incrementing or decrementing a point by 1. Each move changes a single point by one unit at a time.\nAnsw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7599,
"level": 1,
"question": "Given an integer array `points` representing the coordinates of points on a number line, return the **minimum number of moves** required to make all the points equal. A move involves incrementing or decrementing a point by 1. Each move changes a single... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.