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 analyze_string(s):
uppercase = 0
lowercase = 0
digits = 0
for char in s:
if char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1
elif char.isdigit():
digits += 1
return [uppercase, lowercase, digits]
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a string and returns a list `[U, L, D]`, where `U` is the number of uppercase letters in the string, `L` is the number of lowercase letters, and `D` is the number of digits.\n\nFor example, `analyze_string(\"HelloWorld123\")` should return `[2, 8, 3]`\n\n~~~i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6600,
"level": 1,
"question": "Write a function that takes a string and returns a list `[U, L, D]`, where `U` is the number of uppercase letters in the string, `L` is the number of lowercase letters, and `D` is the number of digits.\n\nFor example, `analyze_string(\"HelloWorld123\")... |
def find_pairs(list1, list2):
result = []
for i in range(len(list1)):
for j in range(len(list2)):
if list1[i] <= list2[j]:
result.append((i, j))
return result
# Example usage
list1 = [1, 2, 3]
list2 = [2, 3, 4]
pairs = find_pairs(list1, list2)
print("Pairs of indices tha... | simplelr_Filter | [
{
"content": "Question:\nI would like to have a Python solution for the following problem:\nWrite a function to find all pairs of indices (i, j) from two lists that satisfy a certain condition. The condition is that the element at index i from the first list should be less than or equal to the element at index ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6601,
"level": 1,
"question": "I would like to have a Python solution for the following problem:\nWrite a function to find all pairs of indices (i, j) from two lists that satisfy a certain condition. The condition is that the element at index i from the first list should be less tha... |
def validate_triangle(a, b, c):
if a <= 0 or b <= 0 or c <= 0:
print("This is not a triangle")
return
sides = sorted([a, b, c])
if sides[0] + sides[1] > sides[2]:
print("This is a triangle")
else:
print("This is not a triangle") | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that will print \"This is not a triangle\" if the three lengths of a triangle are not valid. Otherwise, it will print \"This is a triangle\" if they are valid.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6602,
"level": 1,
"question": "Create a function that will print \"This is not a triangle\" if the three lengths of a triangle are not valid. Otherwise, it will print \"This is a triangle\" if they are valid.",
"split": "train"
} |
def convert_tuesday_to_wednesday(s):
return s.replace("Tuesday", "Wednesday") | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert Tuesdays into Wednesdays in a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6603,
"level": 1,
"question": "Write a python function to convert Tuesdays into Wednesdays in a string.",
"split": "train"
} |
def reverse_array(arr):
left = 0
right = len(arr) - 1
while left < right:
# Swap elements without using a temporary variable
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr | simplelr_Filter | [
{
"content": "Question:\nReverse the elements of a given array without using any additional data structures. The solution should have a time complexity of O(n) and should only use constant space. The array should be reversed in-place.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6604,
"level": 1,
"question": "Reverse the elements of a given array without using any additional data structures. The solution should have a time complexity of O(n) and should only use constant space. The array should be reversed in-place.",
"split": "train"
} |
import bisect
from typing import List
def count_unique_elements_in_range(arr: List[int], L: int, R: int) -> int:
left = bisect.bisect_left(arr, L)
right = bisect.bisect_right(arr, R) - 1
if left > right:
return 0
count = 0
previous = None
for num in arr[left:right + 1]:
if num !... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nYou are building an application that processes and analyzes various statistical data. One of the features requires analyzing an array of integers to perform a specific operation frequently. For this purpose, you need to implement a function that, given a sorted array, finds... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6605,
"level": 1,
"question": "### Context\nYou are building an application that processes and analyzes various statistical data. One of the features requires analyzing an array of integers to perform a specific operation frequently. For this purpose, you need to implement a functio... |
def concatenate_non_empty(*args):
strings = []
for arg in args:
s = str(arg)
if s:
strings.append(s)
return ''.join(strings) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that can accept any number of arguments. Each argument is a potential string. The function must return a string that is the concatenation of all non-empty arguments. If no non-empty arguments are provided, return an empty string.\nAnswer:\nLet's think step by step.\n",... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6606,
"level": 1,
"question": "Create a function that can accept any number of arguments. Each argument is a potential string. The function must return a string that is the concatenation of all non-empty arguments. If no non-empty arguments are provided, return an empty string.",
... |
from datetime import datetime as dt, timedelta
from typing import List
def calculate_next_working_day(start_date: str, num_days: int, public_holidays: List[str]) -> str:
if num_days == 0:
return start_date
current = dt.strptime(start_date, "%Y-%m-%d").date() + timedelta(days=1)
holidays = set(publi... | simplelr_Docs | [
{
"content": "Question:\n### Coding Assessment: Enhanced Date-Time Calculator\n\n**Objective**: Implement a function that calculates the next N working days from a given date, considering weekends and public holidays.\n\n**Problem Statement**:\nYou are required to write a Python function `calculate_next_working... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6607,
"level": 1,
"question": "### Coding Assessment: Enhanced Date-Time Calculator\n\n**Objective**: Implement a function that calculates the next N working days from a given date, considering weekends and public holidays.\n\n**Problem Statement**:\nYou are required to write a Pyth... |
def is_armstrong_number(n):
if n < 0:
return False
s = str(n)
d = len(s)
if d == 1:
return True
total = 0
for char in s:
digit = int(char)
total += digit ** d
return total == n | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that identifies if a given number is an Armstrong number (also known as a narcissistic number). An Armstrong number is an n-digit number that is equal to the sum of its digits each raised to the power of n. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6608,
"level": 1,
"question": "Create a function that identifies if a given number is an Armstrong number (also known as a narcissistic number). An Armstrong number is an n-digit number that is equal to the sum of its digits each raised to the power of n. For example, 153 is an Arms... |
def buildings_with_sunlight(buildings):
result = []
current_max = -1
for i in range(len(buildings)):
if buildings[i] > current_max:
result.append(i + 1)
current_max = buildings[i]
return result
| simplelr_Taco | [
{
"content": "Question:\nYou are given a list of integers representing the heights of buildings. Each building starts with an index from 1. The sun rises from the left side of the buildings (i.e., from index 1 towards the last index). Assume the buildings are standing in a straight row.\n\nWrite a function to d... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6609,
"level": 1,
"question": "You are given a list of integers representing the heights of buildings. Each building starts with an index from 1. The sun rises from the left side of the buildings (i.e., from index 1 towards the last index). Assume the buildings are standing in a str... |
def list_to_binary_string(lst):
return ''.join(bin(num)[2:] for num in lst)
# Example usage:
numbers = [1, 2, 3]
binary_str = list_to_binary_string(numbers)
print(binary_str) # Output: '11011' | simplelr_Filter | [
{
"content": "Question:\nHow would you convert a list of integers into a binary string in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6610,
"level": 1,
"question": "How would you convert a list of integers into a binary string in Python?",
"split": "train"
} |
def reverse_words(s):
words = s.split()
words.reverse()
return ' '.join(words) | simplelr_Filter | [
{
"content": "Question:\nA. Define a function called `reverse_words` that takes a single argument, a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6611,
"level": 1,
"question": "A. Define a function called `reverse_words` that takes a single argument, a string.",
"split": "train"
} |
def longest_unique_substring(s):
char_index = {}
max_length = 0
left = 0
for right in range(len(s)):
char = s[right]
if char in char_index and char_index[char] >= left:
left = char_index[char] + 1
char_index[char] = right
current_length = right - left + 1
... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts a string as an input and returns the length of the longest substring containing all distinct characters. For example, the string \"abcabcbb\" should return 3 because the longest substring with all distinct characters is \"abc\".\nAnswer:\nLet's think step ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6612,
"level": 1,
"question": "Create a function that accepts a string as an input and returns the length of the longest substring containing all distinct characters. For example, the string \"abcabcbb\" should return 3 because the longest substring with all distinct characters is \... |
def custom_sort(nums: list[int]) -> list[int]:
"""
Given a list of integers, return a new list with the integers sorted in ascending order.
This function implements the Insertion Sort algorithm.
"""
if not nums:
return []
sorted_list = nums.copy()
for i in range(1, len(sorted_list)):... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge\n\n#### Context/Scenario\nYou are tasked with creating a function that processes a list of integers and returns a list of the same integers sorted in ascending order but without using the built-in Python functions for sorting. This exercise is to test your ability t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6613,
"level": 1,
"question": "### Coding Challenge\n\n#### Context/Scenario\nYou are tasked with creating a function that processes a list of integers and returns a list of the same integers sorted in ascending order but without using the built-in Python functions for sorting. This... |
def sum_transactions(transactions):
total = 0
for transaction in transactions:
total += transaction.get('amount', 0)
return total | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that calculates the sum of all the values in a list of dictionaries. Each dictionary in the list represents a transaction and has a key 'amount' which holds the transaction amount. The function should also handle the case where the list might be empty or the 'amo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6614,
"level": 1,
"question": "Write a Python function that calculates the sum of all the values in a list of dictionaries. Each dictionary in the list represents a transaction and has a key 'amount' which holds the transaction amount. The function should also handle the case where ... |
def add_binary(a: str, b: str) -> str:
carry = 0
result = []
i = len(a) - 1
j = len(b) - 1
while i >= 0 or j >= 0 or carry > 0:
bit_a = int(a[i]) if i >= 0 else 0
bit_b = int(b[j]) if j >= 0 else 0
total = bit_a + bit_b + carry
carry = total // 2
result_bit = ... | simplelr_Filter | [
{
"content": "Question:\nThis task requires you to write a Python function that adds two binary numbers represented as strings. The output should also be in the form of a string. Here are the key rules:\n\n- The inputs are non-negative.\n- The input bits are represented as '0' or '1'.\n- The operation should be... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6615,
"level": 1,
"question": "This task requires you to write a Python function that adds two binary numbers represented as strings. The output should also be in the form of a string. Here are the key rules:\n\n- The inputs are non-negative.\n- The input bits are represented as '0'... |
def sort_numbers(numbers):
# Using Python's built-in sorted() function which implements Timsort algorithm
return sorted(numbers) | simplelr_Filter | [
{
"content": "Question:\nGiven a list of numbers, write a function in Python to sort the list in increasing order. The function should be able to handle an unsorted list of integers and return the sorted list. Make sure to include a brief explanation or comment in your code about the method you are using for so... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6616,
"level": 1,
"question": "Given a list of numbers, write a function in Python to sort the list in increasing order. The function should be able to handle an unsorted list of integers and return the sorted list. Make sure to include a brief explanation or comment in your code ab... |
def n_largest_elements(lst, n):
if not lst or n <= 0:
return []
n = min(n, len(lst))
sorted_lst = sorted(lst)
return sorted_lst[-n:] | simplelr_Filter | [
{
"content": "Question:\nHow can I write a Python script that finds the n largest elements in a list and returns them in ascending order?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6617,
"level": 1,
"question": "How can I write a Python script that finds the n largest elements in a list and returns them in ascending order?",
"split": "train"
} |
import cProfile
import pstats
import os
import tempfile
def profile_and_analyze(func, args, kwargs, sort_by='cumulative', top_n=10):
# Profile the function
profiler = cProfile.Profile()
profiler.enable()
func(*args, **kwargs)
profiler.disable()
# Save profiling data to a temporary file
wit... | simplelr_Docs | [
{
"content": "Question:\n### Profiling and Analyzing Function Performance\n\n**Objective:**\nYou are tasked with implementing a function that profiles the execution of a specified function, saves the profiling results to a file, processes these results using `pstats.Stats`, and provides a formatted output with ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6618,
"level": 1,
"question": "### Profiling and Analyzing Function Performance\n\n**Objective:**\nYou are tasked with implementing a function that profiles the execution of a specified function, saves the profiling results to a file, processes these results using `pstats.Stats`, an... |
def remove_consecutive_duplicates(input_list):
if not input_list:
return []
result = [input_list[0]]
for s in input_list[1:]:
if s != result[-1]:
result.append(s)
return result
| simplelr_Taco | [
{
"content": "Question:\nImplement a function `remove_consecutive_duplicates` that takes a list of strings and removes consecutive duplicate entries. The function should return a new list with only the first instance of each sequence of identical elements.\n\nHere are some examples:\n\n```python\nremove_consecu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6619,
"level": 1,
"question": "Implement a function `remove_consecutive_duplicates` that takes a list of strings and removes consecutive duplicate entries. The function should return a new list with only the first instance of each sequence of identical elements.\n\nHere are some exa... |
def reverse_bits(n):
# Treat n as a 32-bit unsigned integer
n = n & 0xFFFFFFFF
# Convert to 32-bit binary string
binary = bin(n)[2:].zfill(32)
reversed_binary = binary[::-1]
return int(reversed_binary, 2) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse bits of an integer number and return it as an unsigned integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6620,
"level": 1,
"question": "Write a python function to reverse bits of an integer number and return it as an unsigned integer.",
"split": "train"
} |
def coordinates_to_svg_path(coordinates):
if not coordinates:
return ""
# Initialize the path with the "Move To" command
path = f"M {coordinates[0][0]} {coordinates[0][1]}"
# Append "Line To" commands for the remaining points
for x, y in coordinates[1:]:
path += f" L {x} {y... | simplelr_Package | [
{
"content": "Question:\nDevelop a function to translate a sequence of numerical coordinates into a well-formed SVG path. Your task is to write a Python function named `coordinates_to_svg_path` that takes a list of tuples, where each tuple represents a point (x, y) in 2D space, and outputs a string correspondin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6621,
"level": 1,
"question": "Develop a function to translate a sequence of numerical coordinates into a well-formed SVG path. Your task is to write a Python function named `coordinates_to_svg_path` that takes a list of tuples, where each tuple represents a point (x, y) in 2D space... |
from typing import List, Tuple
def transform_string(s: str, operations: List[Tuple[str, ...]]) -> str:
transformed = s
for op in operations:
if op[0] == "reverse":
start = op[1]
end = op[2]
# Slice the substring, reverse it, and reconstruct
substring = tr... | simplelr_Algorithm | [
{
"content": "Question:\n### String Transformation Challenge\n\n**Context**:\nYou are tasked with building a system that can transform a string by performing multiple predefined operations. Each operation is either reversing a substring, deleting a substring, or replacing all occurrences of a substring with ano... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6622,
"level": 1,
"question": "### String Transformation Challenge\n\n**Context**:\nYou are tasked with building a system that can transform a string by performing multiple predefined operations. Each operation is either reversing a substring, deleting a substring, or replacing all ... |
import re
from collections import Counter
from typing import List
def extract_keywords(text: str) -> List[str]:
stopwords = {"a", "is", "the", "this", "and", "on", "in", "at", "of", "for", "to", "with", "only"}
# Convert text to lowercase
text_lower = text.lower()
# Extract words using regex,... | simplelr_Algorithm | [
{
"content": "Question:\n### Text Parsing and Keyword Extraction\n\n#### Objective:\nYou are required to implement a function that processes a given text to identify and extract keywords. The function should take a single input parameter, the text, and return a list of unique keywords from the text, sorted in a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6623,
"level": 1,
"question": "### Text Parsing and Keyword Extraction\n\n#### Objective:\nYou are required to implement a function that processes a given text to identify and extract keywords. The function should take a single input parameter, the text, and return a list of unique ... |
def parse_string(s):
return s.split() | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to parse a string into words, considering punctuation as part of the word. The function should return a list of words including punctuation.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6624,
"level": 1,
"question": "Write a function to parse a string into words, considering punctuation as part of the word. The function should return a list of words including punctuation.",
"split": "train"
} |
def remove_duplicates(nums):
return len(set(nums)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove all duplicates from a list `nums` of integers and return the length of the new list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6625,
"level": 1,
"question": "Write a python function to remove all duplicates from a list `nums` of integers and return the length of the new list.",
"split": "train"
} |
def calculate_overlap_area(rect1: dict, rect2: dict) -> int:
# Calculate x overlap
x1 = rect1['x']
x1_end = x1 + rect1['width']
x2 = rect2['x']
x2_end = x2 + rect2['width']
x_start = max(x1, x2)
x_end = min(x1_end, x2_end)
x_overlap = max(0, x_end - x_start)
# Calculate y overlap
... | simplelr_Package | [
{
"content": "Question:\nDesign a function that calculates the overlap area of two rectangles on a 2D plane. Each rectangle is represented by a dictionary with keys \"x\", \"y\", \"width\", and \"height\", where (x, y) is the coordinate of the bottom-left corner of the rectangle. \n\nThe function should be name... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6626,
"level": 1,
"question": "Design a function that calculates the overlap area of two rectangles on a 2D plane. Each rectangle is represented by a dictionary with keys \"x\", \"y\", \"width\", and \"height\", where (x, y) is the coordinate of the bottom-left corner of the rectang... |
import zlib
def verify_compression_integrity(data: bytes, compression_level: int = -1, checksum_type: str = 'adler32') -> bool:
# Validate compression level
valid_levels = {-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
if compression_level not in valid_levels:
return False
# Validate checksum type
... | simplelr_Docs | [
{
"content": "Question:\n**Objective**: Write a Python function that compresses and then decompresses a given piece of data and verifies the integrity of the decompressed data using checksums.\n\n**Function Signature**:\n```python\ndef verify_compression_integrity(data: bytes, compression_level: int = -1, check... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6627,
"level": 1,
"question": "**Objective**: Write a Python function that compresses and then decompresses a given piece of data and verifies the integrity of the decompressed data using checksums.\n\n**Function Signature**:\n```python\ndef verify_compression_integrity(data: bytes,... |
def factorial(n):
if n < 0:
return "Error: Factorial is not defined for negative numbers."
result = 1
for i in range(1, n + 1):
result *= i
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the factorial of a non-negative integer. If the input is negative, the function should return an error message as the factorial is not defined for negative numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6628,
"level": 1,
"question": "Create a function that calculates the factorial of a non-negative integer. If the input is negative, the function should return an error message as the factorial is not defined for negative numbers.",
"split": "train"
} |
def count_dict_pairs(d):
return len(d) if d is not None else 0 | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes a dictionary as an argument and returns the number of key-value pairs in the dictionary. Additionally, the function should handle the case where the dictionary might be `None` or empty, returning 0 in such cases. Ensure your function is efficient an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6629,
"level": 1,
"question": "Write a function in Python that takes a dictionary as an argument and returns the number of key-value pairs in the dictionary. Additionally, the function should handle the case where the dictionary might be `None` or empty, returning 0 in such cases. E... |
import os
def count_files_with_extension(root_dir, extension):
count = 0
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.endswith(extension):
count += 1
return count
# Replace '/path/to/your/directory' with the actual path containing dir1, dir2, a... | simplelr_Filter | [
{
"content": "Question:\nYou have a list of files in different directories. You need to write a Python program that counts the number of files with a specific extension, such as \".txt\". \n\nHere's an example of the directories structure:\n```\n- dir1\n - file1.txt\n - file2.log\n- dir2\n - file3.txt\n - f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6630,
"level": 1,
"question": "You have a list of files in different directories. You need to write a Python program that counts the number of files with a specific extension, such as \".txt\". \n\nHere's an example of the directories structure:\n```\n- dir1\n - file1.txt\n - file... |
from datetime import datetime, timezone, timedelta
def process_datetime_records(events):
output = []
for event in events:
year = event['year']
month = event['month']
day = event['day']
hour = event['hour']
minute = event['minute']
second = event['second']
... | simplelr_Docs | [
{
"content": "Question:\nIn this assessment, you will be working with Python's `datetime` module to create and manipulate date and time objects. Your task is to implement a function that meets the following requirements:\n\n### Function Name\n`process_datetime_records`\n\n### Input\nA list of dictionaries, wher... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6631,
"level": 1,
"question": "In this assessment, you will be working with Python's `datetime` module to create and manipulate date and time objects. Your task is to implement a function that meets the following requirements:\n\n### Function Name\n`process_datetime_records`\n\n### ... |
def majority_element(arr):
candidate = None
count = 0
for num in arr:
if count == 0:
candidate = num
count = 1
else:
if num == candidate:
count += 1
else:
count -= 1
return candidate
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `majority_element(arr)` that takes a list `arr` of size `n` which is guaranteed to have a majority element. A majority element in a list of size `n` is an element that appears more than n/2 times. \n\nThe function should return the majority element.\n\nTo illustrate the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6632,
"level": 1,
"question": "Write a function `majority_element(arr)` that takes a list `arr` of size `n` which is guaranteed to have a majority element. A majority element in a list of size `n` is an element that appears more than n/2 times. \n\nThe function should return the maj... |
def find_pairs(lst, target):
result = []
added = set()
n = len(lst)
for i in range(n):
for j in range(i + 1, n):
a, b = lst[i], lst[j]
if a + b == target:
pair = tuple(sorted((a, b)))
if pair not in added:
result.append(... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of integers and a target integer as inputs. The function should return tuples of pairs of integers from the list which add up to the target integer. The order of pairs in the result should follow the order they appear in the input list. Each pair shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6633,
"level": 1,
"question": "Write a function that takes a list of integers and a target integer as inputs. The function should return tuples of pairs of integers from the list which add up to the target integer. The order of pairs in the result should follow the order they appear... |
def integer_to_binary(n):
if n == 0:
return "0"
remainders = []
while n > 0:
rem = n % 2
remainders.append(rem)
n = n // 2
remainders.reverse()
return ''.join(map(str, remainders)) | simplelr_Filter | [
{
"content": "Question:\nConvert a given positive integer to its binary representation without using any inbuilt functions or libraries for conversion. Also, the function should handle edge cases, for example, zero and very large numbers efficiently.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6634,
"level": 1,
"question": "Convert a given positive integer to its binary representation without using any inbuilt functions or libraries for conversion. Also, the function should handle edge cases, for example, zero and very large numbers efficiently.",
"split": "train"
} |
def check_tic_tac_toe_winner(board: list) -> str:
# Generate all possible winning lines
lines = []
# Add rows
lines.extend(board)
# Add columns
for col in range(3):
column = [board[0][col], board[1][col], board[2][col]]
lines.append(column)
# Add diagonals
... | simplelr_Apps | [
{
"content": "Question:\n## Tic-Tac-Toe Checker\n\nTic-Tac-Toe is played on a 3x3 grid by two players who take turns marking spaces with 'X' or 'O'. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row wins the game.\n\nYou will receive a 3x3 list of lists represent... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6635,
"level": 1,
"question": "## Tic-Tac-Toe Checker\n\nTic-Tac-Toe is played on a 3x3 grid by two players who take turns marking spaces with 'X' or 'O'. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row wins the game.\n\nYou will re... |
import numpy as np
def map_strings_to_array(arr, labels):
"""
Maps a list of strings to the last axis of a 2D NumPy array, replacing numeric values with corresponding labels.
Values not corresponding to valid indices are replaced with 'NaN'.
Args:
arr (numpy.ndarray): A 2D NumPy array of numer... | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function that takes a NumPy 2D array and a list of strings. This function should map the list of strings to the last axis of the 2D array, replacing the numeric values in the array with the corresponding string labels. Ensure that if the numeric values in the array do no... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6636,
"level": 1,
"question": "Design a Python function that takes a NumPy 2D array and a list of strings. This function should map the list of strings to the last axis of the 2D array, replacing the numeric values in the array with the corresponding string labels. Ensure that if th... |
from collections import defaultdict
def count_subarrays_with_sum_k(A, k):
prefix_sum = 0
count = 0
prefix_counts = defaultdict(int)
prefix_counts[0] = 1 # To handle cases where a subarray sums to k starting from the beginning
for num in A:
prefix_sum += num
# Check if there ex... | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers `A` and an integer `k`, find the count of all unique subarrays of `A` that have an exact sum of `k`. A subarray is defined as a contiguous segment of the array.\n\nExample 1:\nInput: `A = [1, 2, 3], k = 3`\nOutput: `2`\nExplanation: The subarrays with sum 3 ar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6637,
"level": 1,
"question": "Given an array of integers `A` and an integer `k`, find the count of all unique subarrays of `A` that have an exact sum of `k`. A subarray is defined as a contiguous segment of the array.\n\nExample 1:\nInput: `A = [1, 2, 3], k = 3`\nOutput: `2`\nExpla... |
def reverse_string(s):
if not isinstance(s, str):
raise TypeError("Input must be a string.")
char_list = list(s)
char_list.reverse()
return ''.join(char_list) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse a string in Python without using the slicing method. Additionally, handle cases where the input might not be a string by raising an appropriate exception.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6638,
"level": 1,
"question": "Write a function to reverse a string in Python without using the slicing method. Additionally, handle cases where the input might not be a string by raising an appropriate exception.",
"split": "train"
} |
def reverse_sentence(sentence: str) -> str:
words = sentence.split()
reversed_words = []
for i in range(len(words)-1, -1, -1):
reversed_words.append(words[i])
return ' '.join(reversed_words) | simplelr_Data_Structure | [
{
"content": "Question:\n### Reverse Words in a Sentence\n\n#### Problem Description\nYou are tasked with implementing a function that reverses the order of words in a given sentence. Words are sequences of characters separated by spaces. You must preserve the internal order of characters in each word while rev... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6639,
"level": 1,
"question": "### Reverse Words in a Sentence\n\n#### Problem Description\nYou are tasked with implementing a function that reverses the order of words in a given sentence. Words are sequences of characters separated by spaces. You must preserve the internal order o... |
import pandas as pd
from typing import List
def recommend_products(purchase_history_file: str, product_id: int, n_recommendations: int = 5) -> List[int]:
# Load the purchase history data
df = pd.read_csv(purchase_history_file)
# Find all users who purchased the specified product
target_users = df[... | simplelr_Package | [
{
"content": "Question:\nYou have been hired to build a recommendation system for an e-commerce website. Your task is to develop a function that suggests related products based on previous purchase patterns using the `pandas` and `numpy` libraries.\n\nWrite a function `recommend_products(purchase_history_file: ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6640,
"level": 1,
"question": "You have been hired to build a recommendation system for an e-commerce website. Your task is to develop a function that suggests related products based on previous purchase patterns using the `pandas` and `numpy` libraries.\n\nWrite a function `recomme... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
def decision_tree_complexity_curve(X_train, y_train, X_test, y_test, max_depth_start, max_depth_end):
train_accuracies = []
test_accuracies = []
depths = []
for depth in range(max_depth_start, max_de... | simplelr_Package | [
{
"content": "Question:\nYou are given a dataset split into a training set (`X_train`, `y_train`) and a testing set (`X_test`, `y_test`). The task is to use a Decision Tree algorithm to classify data and evaluate the model's performance by varying the maximum depth of the tree. \n\nWrite a function `decision_tr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6641,
"level": 1,
"question": "You are given a dataset split into a training set (`X_train`, `y_train`) and a testing set (`X_test`, `y_test`). The task is to use a Decision Tree algorithm to classify data and evaluate the model's performance by varying the maximum depth of the tree... |
def top_k_scores(nums, k):
return [sum(sorted(scores, reverse=True)[:k]) for scores in nums] | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers `nums` representing the scores of players in a game. A leaderboard is maintained where each player can only have their **top k scores** counted towards their total score. If a player has fewer than `k` scores, all of their scores are counted. You need to... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6642,
"level": 1,
"question": "You are given a list of integers `nums` representing the scores of players in a game. A leaderboard is maintained where each player can only have their **top k scores** counted towards their total score. If a player has fewer than `k` scores, all of th... |
import configparser
def manage_config_file(file_path, section, option, fallback=None):
config = configparser.ConfigParser()
config.read(file_path)
# Read the option value, using fallback if it does not exist
value = config.get(section, option, fallback=fallback)
print(value)
# Check if the se... | simplelr_Docs | [
{
"content": "Question:\n### Configuration File Management Task\n\n**Objective:**\nYou need to use the `configparser` module to create a utility that can manage configuration settings stored in an INI file format. \n\n**Task:**\nImplement a function `manage_config_file(file_path, section, option, fallback=None)... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6643,
"level": 1,
"question": "### Configuration File Management Task\n\n**Objective:**\nYou need to use the `configparser` module to create a utility that can manage configuration settings stored in an INI file format. \n\n**Task:**\nImplement a function `manage_config_file(file_pa... |
def is_rotation(str1, str2):
if len(str1) != len(str2):
return False
temp = str1 + str1
return str2 in temp
# Example usage:
str1 = "waterbottle"
str2 = "erbottlewat"
result = is_rotation(str1, str2)
print(f"Is '{str2}' a rotation of '{str1}'? {result}") | simplelr_Filter | [
{
"content": "Question:\nThe\n\n**Problem:**\n\nYou are given two strings, `str1` and `str2`.\n\nYou need to determine if `str2` is a rotation of `str1`.\n\nFor example:\n\n* `\"waterbottle\"` is a rotation of `\"erbottlewat\"`.\n* `\"foo\"` is a rotation of `\"oof\"`.\n\n**Constraints:**\n\n* Both strings are ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6644,
"level": 1,
"question": "The\n\n**Problem:**\n\nYou are given two strings, `str1` and `str2`.\n\nYou need to determine if `str2` is a rotation of `str1`.\n\nFor example:\n\n* `\"waterbottle\"` is a rotation of `\"erbottlewat\"`.\n* `\"foo\"` is a rotation of `\"oof\"`.\n\n**Co... |
def divide_and_format(n):
n_abs = abs(n)
half = n_abs // 2
remainder = n_abs % 2
if remainder == 0:
return half
else:
return f"{half}.5" | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts an integer as a parameter and returns the same integer divided by 2. If the division results in a non-integer, append \".5\" to the integer part of the result and return it as a string. If the input integer is negative, return the absolute value of the int... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6645,
"level": 1,
"question": "Create a function that accepts an integer as a parameter and returns the same integer divided by 2. If the division results in a non-integer, append \".5\" to the integer part of the result and return it as a string. If the input integer is negative, r... |
def character_count(s):
counts = {}
for char in s:
if char != ' ':
counts[char] = counts.get(char, 0) + 1
return counts | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and returns the count of each character in the string, excluding spaces. The function should also handle lowercase and uppercase letters as distinct characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6646,
"level": 1,
"question": "Create a function that takes a string as input and returns the count of each character in the string, excluding spaces. The function should also handle lowercase and uppercase letters as distinct characters.",
"split": "train"
} |
def merge_and_sort_lists(list1, list2):
result = []
i = j = 0
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
# Add the remaining elements of list1 or lis... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes an existing list and a new list as input and returns a new list with elements from the two lists sorted in ascending order. Assume both lists are sorted in ascending order beforehand.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6647,
"level": 1,
"question": "Write a Python function that takes an existing list and a new list as input and returns a new list with elements from the two lists sorted in ascending order. Assume both lists are sorted in ascending order beforehand.",
"split": "train"
} |
def find_most_common_substrings(string_list, k):
if k <= 0 or not string_list:
return []
substring_counts = {}
for s in string_list:
n = len(s)
if n >= k:
for i in range(n - k + 1):
substring = s[i:i+k]
if substring in substring_c... | simplelr_Filter | [
{
"content": "Question:\nI need to create a Python function that finds the most common values in a list of strings, but I want to consider substrings of a specific length (`k`). For example, if `k=3`, and the list is `[\"hello\", \"world\", \"helium\", \"helper\"]`, the substrings of length 3 should be consider... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6648,
"level": 1,
"question": "I need to create a Python function that finds the most common values in a list of strings, but I want to consider substrings of a specific length (`k`). For example, if `k=3`, and the list is `[\"hello\", \"world\", \"helium\", \"helper\"]`, the substr... |
def unique_paths(n, m):
a = n + m - 2
b = min(n - 1, m - 1)
result = 1
for i in range(1, b + 1):
result = result * (a - b + i) // i
return result | simplelr_Codeforces | [
{
"content": "Question:\nGiven a grid of size `n x m`, you need to return the number of unique paths from the top-left corner to the bottom-right corner. You can only move either down or right at any point in time.\n\nWrite a function `unique_paths(n, m)` that takes in two integers `n` and `m` and returns an in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6649,
"level": 1,
"question": "Given a grid of size `n x m`, you need to return the number of unique paths from the top-left corner to the bottom-right corner. You can only move either down or right at any point in time.\n\nWrite a function `unique_paths(n, m)` that takes in two int... |
import cmath
def solve_quadratic(a, b, c):
discriminant = b**2 - 4 * a * c
sqrt_discriminant = cmath.sqrt(discriminant)
root1 = (-b + sqrt_discriminant) / (2 * a)
root2 = (-b - sqrt_discriminant) / (2 * a)
return (root1, root2) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to solve a quadratic equation ax^2 + bx + c = 0. The function should return both roots, even if they are complex. Use the cmath module to handle complex numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6650,
"level": 1,
"question": "Write a Python function to solve a quadratic equation ax^2 + bx + c = 0. The function should return both roots, even if they are complex. Use the cmath module to handle complex numbers.",
"split": "train"
} |
def reverse_string(s):
reversed_str = ""
for i in range(len(s)-1, -1, -1):
reversed_str += s[i]
return reversed_str | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the reverse of a string. The function should avoid using the slicing method. You should implement your solution using iteration.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6651,
"level": 1,
"question": "Write a python function to find the reverse of a string. The function should avoid using the slicing method. You should implement your solution using iteration.",
"split": "train"
} |
def separate_weights(s):
weights = list(map(int, s.split()))
apples = []
oranges = []
for i in range(len(weights)):
if i % 2 == 0:
apples.append(weights[i])
else:
oranges.append(weights[i])
return apples, oranges
| simplelr_Taco | [
{
"content": "Question:\nYou are given a string of numbers that represent the combined weights of apples and oranges at a market. The weights are formatted as alternating segments of whole numbers, with each segment representing the weight of an apple (a) followed by the weight of an orange (o). Your task is to... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6652,
"level": 1,
"question": "You are given a string of numbers that represent the combined weights of apples and oranges at a market. The weights are formatted as alternating segments of whole numbers, with each segment representing the weight of an apple (a) followed by the weigh... |
from typing import List
def shell_sort(arr: List[int]) -> List[int]:
'''
Sort the array using Shell Sort algorithm.
Parameters:
- arr (List[int]): The list of integers to be sorted.
Returns:
- List[int]: The sorted list of integers.
'''
n = len(arr)
if n == 0:
ret... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Problem Statement\nYou are given an array of integers that need to be sorted using the Shell Sort algorithm. Implement the Shell Sort function to sort the provided array in ascending order.\n\n#### Function Signature\n```python\ndef shell_sort(arr: List[int]) -> List[int]:\n '''... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6653,
"level": 1,
"question": "#### Problem Statement\nYou are given an array of integers that need to be sorted using the Shell Sort algorithm. Implement the Shell Sort function to sort the provided array in ascending order.\n\n#### Function Signature\n```python\ndef shell_sort(arr... |
def first_occurrence_excluding_spaces(s, char):
for i in range(len(s)):
if s[i] == ' ':
continue
if s[i] == char:
return i
return -1 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the first occurrence of a given character in a string, excluding any spaces.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6654,
"level": 1,
"question": "Write a python function to find the first occurrence of a given character in a string, excluding any spaces.",
"split": "train"
} |
def bubble_sort(lst):
# Create a copy of the input list to avoid modifying the original list
numbers = lst.copy()
n = len(numbers)
# The outer loop runs for each element in the list minus one
# This is because each pass through the list places the next largest element in its correct position
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that takes a list of integers as input and returns a new list with the integers sorted in ascending order. Use the bubble sort algorithm for this task. The program should be able to handle a list of any length. Ensure your code is well-commented to explain the ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6655,
"level": 1,
"question": "Write a Python program that takes a list of integers as input and returns a new list with the integers sorted in ascending order. Use the bubble sort algorithm for this task. The program should be able to handle a list of any length. Ensure your code i... |
def product_except_self(nums):
n = len(nums)
if n == 0:
return []
prefix = [1] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] * nums[i]
suffix = [1] * (n + 1)
for i in range(n - 1, -1, -1):
suffix[i] = suffix[i + 1] * nums[i]
result = []
for... | simplelr_Evol | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a new list where each element is the product of all other elements in the original list except the one at the current position. Ensure your solution is optimized for time complexity and can handle lists of up to 100,000 integer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6656,
"level": 1,
"question": "Create a function that takes a list of integers and returns a new list where each element is the product of all other elements in the original list except the one at the current position. Ensure your solution is optimized for time complexity and can ha... |
from collections import defaultdict
def find_itinerary(tickets):
# Build the adjacency list
adj = defaultdict(list)
for frm, to in tickets:
adj[frm].append(to)
# Sort the adjacency lists in reverse lexicographical order
for city in adj:
adj[city].sort(reverse=True)
# U... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of flight tickets represented by pairs of departure and arrival airports `[from, to]`. Use these tickets to construct an itinerary in order such that you visit all given airports and return to the starting airport. Each ticket is represented as a one-way flight from... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6657,
"level": 1,
"question": "You are given a list of flight tickets represented by pairs of departure and arrival airports `[from, to]`. Use these tickets to construct an itinerary in order such that you visit all given airports and return to the starting airport. Each ticket is r... |
import os
import re
def count_words_in_files(file_paths):
word_counts = {}
for path in file_paths:
name = os.path.basename(path)
with open(path, 'r') as f:
content = f.read()
words = re.findall(r'\b\w+\b', content)
word_counts[name] = len(words)
return wo... | simplelr_Package | [
{
"content": "Question:\nYou are required to implement a function called `count_words_in_files` that takes a list of file paths as an argument and returns a dictionary where the keys are the file names and the values are the number of words in each file. For this task, you will need to use Python's `os` and `re... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6658,
"level": 1,
"question": "You are required to implement a function called `count_words_in_files` that takes a list of file paths as an argument and returns a dictionary where the keys are the file names and the values are the number of words in each file. For this task, you wil... |
from typing import List
def cycle_sort(arr: List[int]) -> List[int]:
if not arr:
return []
arr = arr.copy()
n = len(arr)
# Create a sorted version of the array
sorted_arr = sorted(arr)
# Create a dictionary to map each value to its position in the sorted array
# Since... | simplelr_Data_Structure | [
{
"content": "Question:\n### Cycle Sort Implementation and Application\n\n#### Introduction\nCycle Sort is a comparison sorting algorithm that aims to minimize the number of write operations. This is particularly useful in scenarios where writing to memory is a costly operation.\n\n#### Task\nYou are required t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6659,
"level": 1,
"question": "### Cycle Sort Implementation and Application\n\n#### Introduction\nCycle Sort is a comparison sorting algorithm that aims to minimize the number of write operations. This is particularly useful in scenarios where writing to memory is a costly operatio... |
def replace_space(my_str, sep, rep):
# First, replace all spaces with the separator
temp = my_str.replace(' ', sep)
# Then, replace all occurrences of the separator with the replacement
return temp.replace(sep, rep) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function `replace_space()` that takes in three parameters: a string `my_str`, a separator `sep`, and a replacement `rep`. The function should return a new string where every occurrence of the separator is replaced with the replacement string, and all spaces in `my_str` a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6660,
"level": 1,
"question": "Create a Python function `replace_space()` that takes in three parameters: a string `my_str`, a separator `sep`, and a replacement `rep`. The function should return a new string where every occurrence of the separator is replaced with the replacement s... |
import xml.etree.ElementTree as ET
def process_books(xml_data: str, new_book_details: dict, update_title: str, new_price: str, cutoff_year: int):
# Parse the XML string into an ElementTree object
root = ET.fromstring(xml_data)
# Remove books published before the cutoff year
for book in list(root):... | simplelr_Docs | [
{
"content": "Question:\n## XML Data Processor\n\nYou are given a simple XML document containing information about several books. Your task is to write a Python script using the `xml.etree.ElementTree` module to perform the following operations:\n\n1. Parse the provided XML document from a string.\n2. Modify th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6661,
"level": 1,
"question": "## XML Data Processor\n\nYou are given a simple XML document containing information about several books. Your task is to write a Python script using the `xml.etree.ElementTree` module to perform the following operations:\n\n1. Parse the provided XML do... |
import ast
from typing import Any
def dynamic_code_executor(code: str) -> Any:
# Try to parse the code as an expression
try:
tree = ast.parse(code, mode='eval')
except SyntaxError:
# If parsing as expression fails, parse as module
pass
else:
# Successfully parsed as an e... | simplelr_Docs | [
{
"content": "Question:\n### Question\n\n**Dynamic Python Code Execution and Parsing**\n\nThis question is designed to assess your understanding of Python's capabilities and syntax for dynamically executing code. You are required to implement a function that reads a multi-line string input containing Python cod... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6662,
"level": 1,
"question": "### Question\n\n**Dynamic Python Code Execution and Parsing**\n\nThis question is designed to assess your understanding of Python's capabilities and syntax for dynamically executing code. You are required to implement a function that reads a multi-line... |
def isPerfectSquare(n):
if n < 0:
return False
if n == 0 or n == 1:
return True
low = 1
high = n
while low <= high:
mid = (low + high) // 2
mid_sq = mid * mid
if mid_sq == n:
return True
elif mid_sq < n:
low = mid + 1
el... | simplelr_Taco | [
{
"content": "Question:\nGiven a positive integer n, write a function to determine if n is a perfect square without using any built-in square root functions. \n\nA perfect square is an integer that is the square of an integer (e.g., 1, 4, 9, 16, 25, ...).\n\nExample 1:\n\nn = 16\n\nResult: True\n\n\n\nExample 2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6663,
"level": 1,
"question": "Given a positive integer n, write a function to determine if n is a perfect square without using any built-in square root functions. \n\nA perfect square is an integer that is the square of an integer (e.g., 1, 4, 9, 16, 25, ...).\n\nExample 1:\n\nn = ... |
def format_total_time(seconds_list):
total = sum(seconds_list)
hours = total // 3600
minutes = (total // 60) % 60
seconds = total % 60
return f"{hours:02d}:{minutes:02d}:{seconds:02d}" | simplelr_Filter | [
{
"content": "Question:\nGiven a Python code snippet, write a function that takes a list of time durations in seconds as input and returns the total time in a formatted string \"hh:mm:ss\". The function should correctly handle cases where the total time exceeds 24 hours.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6664,
"level": 1,
"question": "Given a Python code snippet, write a function that takes a list of time durations in seconds as input and returns the total time in a formatted string \"hh:mm:ss\". The function should correctly handle cases where the total time exceeds 24 hours.",
"... |
def can_return_to_origin(s: str) -> bool:
e = s.count('E')
s_count = s.count('S')
return (e % 2 == 0) and (s_count % 2 == 0) | simplelr_Filter | [
{
"content": "Question:\nA string s is given as input. \n Each character in s is either 'E' (representing a move East) or 'S' (representing a move South).\n Imagine the movements are made on a grid starting at the origin (0,0).\n\nGoal: Determine if it's possible to reach the origin (0,0) again after following ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6665,
"level": 1,
"question": "A string s is given as input. \n Each character in s is either 'E' (representing a move East) or 'S' (representing a move South).\n Imagine the movements are made on a grid starting at the origin (0,0).\n\nGoal: Determine if it's possible to reach the ... |
from datetime import date
def longest_login_streak(login_dates):
if not login_dates:
return 0
# Convert each date string to a date object and remove duplicates
unique_dates = set()
for d in login_dates:
dt = date.fromisoformat(d)
unique_dates.add(dt)
# Convert to a... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario:\nYou are part of a development team tasked with creating a new social media application. One of the essential features is to track user engagement by analyzing the usage patterns within the application. To start with, you need to calculate the longest streak of consecutive... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6666,
"level": 1,
"question": "### Scenario:\nYou are part of a development team tasked with creating a new social media application. One of the essential features is to track user engagement by analyzing the usage patterns within the application. To start with, you need to calculat... |
def findPairs(arr, target):
pairs = set()
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
if arr[i] + arr[j] == target:
pair = tuple(sorted((arr[i], arr[j])))
pairs.add(pair)
return sorted(pairs)
| simplelr_Taco | [
{
"content": "Question:\n### Task\n\nYou are given a list of integers. Your task is to create a function that finds all the unique pairs of numbers in the list that add up to a given target sum.\n\n### What do we need to do?\n\nWrite a function `findPairs(arr, target)` that takes in two arguments:\n- `arr`: a l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6667,
"level": 1,
"question": "### Task\n\nYou are given a list of integers. Your task is to create a function that finds all the unique pairs of numbers in the list that add up to a given target sum.\n\n### What do we need to do?\n\nWrite a function `findPairs(arr, target)` that ta... |
import re
def is_palindrome(s):
# Remove all non-alphanumeric characters and convert to lowercase
cleaned = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
# Check if the cleaned string is equal to its reverse
return cleaned == cleaned[::-1]
# Test cases
print(is_palindrome("Madam, I'm Adam")) # Expecte... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to check if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, \"Madam, I'm Adam\" is a palindrome. The ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6668,
"level": 1,
"question": "Write a Python function to check if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, \"Mada... |
def sum_even_in_range(a, b):
lower = min(a, b)
upper = max(a, b)
# Determine the first even number >= lower
if lower % 2 == 0:
first = lower
else:
first = lower + 1
# Determine the last even number <= upper
if upper % 2 == 0:
last = upper
else:
l... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that computes the sum of all the even numbers in a given range [a, b], inclusive. The function should handle both positive and negative integers and ensure it works for any order of input for a and b (i.e., a may be less than, equal to, or greater than b). For example:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6669,
"level": 1,
"question": "Write a function that computes the sum of all the even numbers in a given range [a, b], inclusive. The function should handle both positive and negative integers and ensure it works for any order of input for a and b (i.e., a may be less than, equal to... |
def calculate_total_cost(cart):
total = 0
for item in cart:
total += item['price'] * item['quantity']
return total | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code to calculate the total cost of items in a shopping cart? Given a list of items where each item is represented as a dictionary with keys 'name', 'price', and 'quantity', the function should return the total cost.\nAnswer:\nLet's think step by step.\n",
"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6670,
"level": 1,
"question": "Can you provide a Python code to calculate the total cost of items in a shopping cart? Given a list of items where each item is represented as a dictionary with keys 'name', 'price', and 'quantity', the function should return the total cost.",
"split... |
def convert_seconds(total_seconds):
hours = total_seconds // 3600
remaining_seconds = total_seconds % 3600
minutes = remaining_seconds // 60
seconds = remaining_seconds % 60
return (hours, minutes, seconds) | simplelr_Filter | [
{
"content": "Question:\nI need to write a Python function that converts a given number of seconds into hours, minutes, and seconds. The function should return a tuple in the format (hours, minutes, seconds). Can you provide the code for this function and explain how it works?\nAnswer:\nLet's think step by step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6671,
"level": 1,
"question": "I need to write a Python function that converts a given number of seconds into hours, minutes, and seconds. The function should return a tuple in the format (hours, minutes, seconds). Can you provide the code for this function and explain how it works?... |
def find_smallest_missing_positive(nums):
positives = set()
for num in nums:
if num > 0:
positives.add(num)
i = 1
while True:
if i not in positives:
return i
i += 1 | simplelr_Filter | [
{
"content": "Question:\nCan you write a Python function to find the smallest positive integer that does not appear in a given list of integers? The function should be efficient and handle any list of integers, including negative numbers and duplicates.\nAnswer:\nLet's think step by step.\n",
"role": "user"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6672,
"level": 1,
"question": "Can you write a Python function to find the smallest positive integer that does not appear in a given list of integers? The function should be efficient and handle any list of integers, including negative numbers and duplicates.",
"split": "train"
} |
from collections import defaultdict
def first_unique(lst):
counts = defaultdict(int)
for num in lst:
counts[num] += 1
for num in lst:
if counts[num] == 1:
return num
return None
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns the first unique integer in the list. If there are no unique integers, return `None`. An integer is considered unique if it appears exactly once in the list.\n\n## Examples\n\n```python\nfirst_unique([2, 3, 3, 2, 6, 7, 7]) ==> ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6673,
"level": 1,
"question": "Write a function that takes a list of integers and returns the first unique integer in the list. If there are no unique integers, return `None`. An integer is considered unique if it appears exactly once in the list.\n\n## Examples\n\n```python\nfirst_... |
def longest_common_subsequence(s1, s2):
m = len(s1)
n = len(s2)
# Create a DP table with (m+1) rows and (n+1) columns
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Fill the DP table
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i-1] == s2[j-1]:
... | simplelr_Evol | [
{
"content": "Question:\nCreate a function that determines the longest common subsequence (LCS) between two given strings. The LCS is defined as the longest sequence that can be derived from both strings without reordering any characters. Your function should return the length of the LCS and the LCS itself. \n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6674,
"level": 1,
"question": "Create a function that determines the longest common subsequence (LCS) between two given strings. The LCS is defined as the longest sequence that can be derived from both strings without reordering any characters. Your function should return the length... |
def multiply_by_2(d):
return {key: d[key] * 2 for key in d} | simplelr_Filter | [
{
"content": "Question:\nI have written a function that takes a dictionary as an input and returns a dictionary with the same keys but with the corresponding values multiplied by 2. The function is as follows:\n```\ndef multiply_by_2(d):\n for key in d:\n d[key] *= 2\n return d\n```\nHowever, the i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6675,
"level": 1,
"question": "I have written a function that takes a dictionary as an input and returns a dictionary with the same keys but with the corresponding values multiplied by 2. The function is as follows:\n```\ndef multiply_by_2(d):\n for key in d:\n d[key] *= 2... |
def can_pass_ball(n):
return "YES" if n >= 3 else "NO" | simplelr_Apps | [
{
"content": "Question:\nA group of colleagues are planning a team-building activity and have decided to play a game involving passing a ball around in a circle. The rules are as follows: the ball starts with one person, and they pass it to another person in the circle. Each person can only pass the ball to the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6676,
"level": 1,
"question": "A group of colleagues are planning a team-building activity and have decided to play a game involving passing a ball around in a circle. The rules are as follows: the ball starts with one person, and they pass it to another person in the circle. Each p... |
def max_length_subarray(arr, k):
if k < 0:
return 0
max_length = 0
current_sum = 0
left = 0
for right in range(len(arr)):
current_sum += arr[right]
while current_sum > k and left <= right:
current_sum -= arr[left]
left += 1
if current_sum <= k ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` where each element `arr[i]` represents the number of items at position `i`. You are also given an integer `k`. Your task is to find the maximum number of consecutive positions you can choose, starting from any index, such that the sum of items in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6677,
"level": 1,
"question": "You are given an array of integers `arr` where each element `arr[i]` represents the number of items at position `i`. You are also given an integer `k`. Your task is to find the maximum number of consecutive positions you can choose, starting from any i... |
def valid_brackets_sequence(s: str) -> bool:
stack = []
bracket_map = {')': '(', '}': '{', ']': '['}
for char in s:
if char in bracket_map.values():
stack.append(char)
else:
if not stack:
return False
top = stack.pop()
if top !=... | simplelr_Package | [
{
"content": "Question:\n---\nIn this task, you will implement a function `valid_brackets_sequence` that determines whether a sequence of brackets is valid. The sequence is considered valid if it meets the following criteria:\n\n1. Every opening bracket has a corresponding closing bracket.\n2. The brackets are ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6678,
"level": 1,
"question": "---\nIn this task, you will implement a function `valid_brackets_sequence` that determines whether a sequence of brackets is valid. The sequence is considered valid if it meets the following criteria:\n\n1. Every opening bracket has a corresponding clo... |
def manage_storage(n, grid, commands):
output = []
for cmd in commands:
parts = cmd.split()
if parts[0] == 'MOVE':
x = int(parts[1])
y = int(parts[2])
a = int(parts[3])
b = int(parts[4])
if grid[x][y] != 0 and grid[a][b] == 0:
... | simplelr_Code_Contests | [
{
"content": "Question:\nA warehouse stores a variety of items in a custom storage system. The system records the position of each item on a two-dimensional grid where each cell may contain one item or be empty. Each item has a unique ID and value associated with it.\n\nYou need to implement a function to manag... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6679,
"level": 1,
"question": "A warehouse stores a variety of items in a custom storage system. The system records the position of each item on a two-dimensional grid where each cell may contain one item or be empty. Each item has a unique ID and value associated with it.\n\nYou ne... |
def jaccard_index(set1: list, set2: list) -> float:
set_a = set(set1)
set_b = set(set2)
intersection = set_a & set_b
union = set_a | set_b
len_intersection = len(intersection)
len_union = len(union)
if len_union == 0:
return 1.0
else:
return len_intersection / len_union | simplelr_Package | [
{
"content": "Question:\nIn this problem, you will write a function to compute the intersection and union of two sets and then determine the Jaccard Index of these sets. This task aims to make you familiar with set operations and the calculation of the Jaccard Index, a metric used for measuring the similarity b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6680,
"level": 1,
"question": "In this problem, you will write a function to compute the intersection and union of two sets and then determine the Jaccard Index of these sets. This task aims to make you familiar with set operations and the calculation of the Jaccard Index, a metric ... |
def filter_by_substring(lst, substr):
if not substr:
return list(lst)
return [s for s in lst if substr in s] | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes a list of strings and a string as arguments and returns a new list containing only the strings from the original list that contain the given string as a substring. If the given string is empty, the function should return the original list. If the or... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6681,
"level": 1,
"question": "Write a function in Python that takes a list of strings and a string as arguments and returns a new list containing only the strings from the original list that contain the given string as a substring. If the given string is empty, the function should ... |
def min_increments_to_make_unique(nums):
nums.sort()
total = 0
for i in range(1, len(nums)):
if nums[i] <= nums[i-1]:
diff = nums[i-1] + 1 - nums[i]
total += diff
nums[i] = nums[i-1] + 1
return total | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array `nums` of length `n`, where each element is an integer. You are allowed to **increment** any element of the array by 1 any number of times. Your goal is to make all the elements of the array **pairwise distinct** (no two elements should be equal). Return _the mi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6682,
"level": 1,
"question": "You are given an array `nums` of length `n`, where each element is an integer. You are allowed to **increment** any element of the array by 1 any number of times. Your goal is to make all the elements of the array **pairwise distinct** (no two element... |
def rearrange_list(lst):
negatives = []
non_negatives = []
for num in lst:
if num < 0:
negatives.append(num)
else:
non_negatives.append(num)
lst[:] = negatives + non_negatives | simplelr_Evol | [
{
"content": "Question:\nYou are given a list of integers. The task is to re-arrange the list so that all negative integers appear before all positive integers, while maintaining the relative order of the negative integers and positive integers. The function should not return a new list, but rather modify the o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6683,
"level": 1,
"question": "You are given a list of integers. The task is to re-arrange the list so that all negative integers appear before all positive integers, while maintaining the relative order of the negative integers and positive integers. The function should not return ... |
def is_palindromic_filename(filename: str) -> bool:
if not isinstance(filename, str):
raise TypeError("Input must be a string")
cleaned = ''.join([c.lower() for c in filename if c.isalnum()])
return cleaned == cleaned[::-1] | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are tasked with designing a memory-efficient file system that includes a method for recognizing palindromic file names. A palindromic file name is a string that reads the same forward and backward. This functionality is vital for organizing and quickly retri... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6684,
"level": 1,
"question": "### Problem Statement\n\nYou are tasked with designing a memory-efficient file system that includes a method for recognizing palindromic file names. A palindromic file name is a string that reads the same forward and backward. This functionality is vit... |
from datetime import datetime
def sort_dates(date_list):
date_objs = [datetime.strptime(d, "%d-%m-%Y").date() for d in date_list]
sorted_dates = sorted(date_objs)
return [d.strftime("%d-%m-%Y") for d in sorted_dates] | simplelr_Package | [
{
"content": "Question:\nDefine a function that takes a list of strings representing dates in \"dd-mm-yyyy\" format and returns a list of the same dates sorted in chronological order. Your function should correctly handle edge cases such as leap years and varying month lengths. \n\nYou should write self-contain... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6685,
"level": 1,
"question": "Define a function that takes a list of strings representing dates in \"dd-mm-yyyy\" format and returns a list of the same dates sorted in chronological order. Your function should correctly handle edge cases such as leap years and varying month lengths... |
def sum_of_evens(lst):
"""
This function calculates the sum of all even numbers in a given list of integers.
Args:
lst (list): A list of integers.
Returns:
int: The sum of all even integers in the list. If the list is empty, it returns 0.
"""
total = 0
for number in... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the sum of all even numbers in a given list of integers. If the list is empty, the function should return 0. Make sure to include a docstring explaining the function's behavior.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6686,
"level": 1,
"question": "Create a function that calculates the sum of all even numbers in a given list of integers. If the list is empty, the function should return 0. Make sure to include a docstring explaining the function's behavior.",
"split": "train"
} |
def majority_element(arr: list[int]) -> int:
"""
Find the majority element in the list.
Args:
arr (list[int]): The input list of integers.
Returns:
int: The majority element.
Examples:
>>> majority_element([3, 2, 3])
3
>>> majority_element([2, 2, 1, 1, 1, 2... | simplelr_Algorithm | [
{
"content": "Question:\n### Majority Element Finder\n\nYou need to implement a function that finds the majority element in a list. A majority element in a list `arr` of size `n` is an element that appears more than `n // 2` times. Assume that the input list always contains a majority element.\n\n**Function Sig... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6687,
"level": 1,
"question": "### Majority Element Finder\n\nYou need to implement a function that finds the majority element in a list. A majority element in a list `arr` of size `n` is an element that appears more than `n // 2` times. Assume that the input list always contains a ... |
def find_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that finds all the even numbers in a given list of integers and returns a new list containing only the even numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6688,
"level": 1,
"question": "Create a function that finds all the even numbers in a given list of integers and returns a new list containing only the even numbers.",
"split": "train"
} |
def fizzbuzz_variant(n, rules):
res = [''] * (n + 1)
for divisor, string in rules:
for i in range(divisor, n + 1, divisor):
res[i] += string
output = []
for i in range(1, n + 1):
if res[i]:
output.append(res[i])
else:
output.append(i)
retur... | simplelr_Data_Structure | [
{
"content": "Question:\n### FizzBuzz Variants\n\n#### Context:\nFizzBuzz is a popular problem used to teach and assess understanding of basic programming principles. You are asked to extend this basic problem in a manner that requires more advanced handling.\n\n#### Problem:\nWrite a function `fizzbuzz_variant... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6689,
"level": 1,
"question": "### FizzBuzz Variants\n\n#### Context:\nFizzBuzz is a popular problem used to teach and assess understanding of basic programming principles. You are asked to extend this basic problem in a manner that requires more advanced handling.\n\n#### Problem:\... |
from typing import List, Tuple
def simulate_growth(initial_states: List[Tuple[int, float]], growth_rate: float, days: int) -> List[float]:
result = []
for water_level, height in initial_states:
total_growth = water_level * growth_rate * days
final_height = height + total_growth
result.a... | simplelr_Taco | [
{
"content": "Question:\nYour friend is an aspiring gardener and is trying to maintain a health chart for their plants. Each plant has the following attributes: `water_level` (measured in units) and `height` (measured in centimeters). Every day, each plant grows based on the water_level it has. The growth rate ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6690,
"level": 1,
"question": "Your friend is an aspiring gardener and is trying to maintain a health chart for their plants. Each plant has the following attributes: `water_level` (measured in units) and `height` (measured in centimeters). Every day, each plant grows based on the w... |
def first_non_repeating_character(s):
if not s:
return 'No unique character found'
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
for char in s:
if freq[char] == 1:
return char
return 'No unique chara... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the first non-repeating character in a given string. If no such character exists, return 'No unique character found'.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6691,
"level": 1,
"question": "Write a function to find the first non-repeating character in a given string. If no such character exists, return 'No unique character found'.",
"split": "train"
} |
def subtract_sum_of_natural_numbers(n, m):
sum_m = m * (m + 1) // 2
return n - sum_m | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer n and subtracts the sum of first m natural numbers from it, where m is also an integer passed as an argument. For example, if n=10 and m=2, the number to be subtracted is the sum of first 2 natural numbers, which is 1+2=3. After subtracting, the f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6692,
"level": 1,
"question": "Create a function that takes an integer n and subtracts the sum of first m natural numbers from it, where m is also an integer passed as an argument. For example, if n=10 and m=2, the number to be subtracted is the sum of first 2 natural numbers, which... |
def invert_case(s):
return s.swapcase() | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string and returns a new string with each character's case inverted. For instance, \"Python\" should become \"pYTHON\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6693,
"level": 1,
"question": "Create a function that takes a string and returns a new string with each character's case inverted. For instance, \"Python\" should become \"pYTHON\".",
"split": "train"
} |
from collections import Counter
def most_frequent_elements(numbers, k):
if k == 0:
return []
counts = Counter(numbers)
items = list(counts.items())
items.sort(key=lambda x: (-x[1], x[0]))
unique_count = len(items)
take = min(k, unique_count)
return [x[0] for x in items[:take]] | simplelr_Evol | [
{
"content": "Question:\nCreate a function in Python that takes a list of integers and an integer value k, and returns the k most frequent elements in the list. If there is a tie for the k-th place in terms of frequency, return the smallest elements first. Implement your solution with a time complexity better t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6694,
"level": 1,
"question": "Create a function in Python that takes a list of integers and an integer value k, and returns the k most frequent elements in the list. If there is a tie for the k-th place in terms of frequency, return the smallest elements first. Implement your solut... |
def create_user(name, account_number, account_password):
return {
'name': name,
'account_number': account_number,
'account_password': account_password
} | simplelr_Filter | [
{
"content": "Question:\nThis function will create a new user with the attributes 'name', 'account_number', and 'account_password'. The function will return the user's details in a dictionary. \n```python\ndef create_user(name, account_number, account_password):\n # declare initial variables\n user = {}\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6695,
"level": 1,
"question": "This function will create a new user with the attributes 'name', 'account_number', and 'account_password'. The function will return the user's details in a dictionary. \n```python\ndef create_user(name, account_number, account_password):\n # declare... |
def day_of_week(s):
year = int(s.split('-')[0])
month = int(s.split('-')[1])
day = int(s.split('-')[2])
if month < 3:
month += 12
year -= 1
q = day
m = month
J = year // 100
K = year % 100
h = (q + (13 * (m + 1) // 5) + K + (K // 4) + (J // 4) + 5 * J) ... | simplelr_Leetcode | [
{
"content": "Question:\nWrite a function that takes a string `s` representing a date in the format \"YYYY-MM-DD\" and returns the day of the week for that date. The day should be one of \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", or \"Sunday\". You may assume that the input ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6696,
"level": 1,
"question": "Write a function that takes a string `s` representing a date in the format \"YYYY-MM-DD\" and returns the day of the week for that date. The day should be one of \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", or \"Sunda... |
def maxNonOverlappingTasks(tasks):
# Sort tasks by end time, then by priority descending
sorted_tasks = sorted(tasks, key=lambda x: (x[1], -x[2]))
last_end = -1
count = 0
for task in sorted_tasks:
if task[0] >= last_end:
count += 1
last_end = task[1]
return count | simplelr_Codeforces | [
{
"content": "Question:\nImagine you are working on a system that schedules tasks to be executed on a single processor. Each task has a unique start time, a unique end time, and a priority. The processor can only execute one task at a time, and higher priority tasks should be preferred in case of overlapping ta... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6697,
"level": 1,
"question": "Imagine you are working on a system that schedules tasks to be executed on a single processor. Each task has a unique start time, a unique end time, and a priority. The processor can only execute one task at a time, and higher priority tasks should be ... |
import zipfile
import os
def process_zip_file(zip_path: str, extract_file_name: str, extract_to_dir: str, file_to_add: str) -> None:
# Step 1: List the contents of the ZIP file
try:
with zipfile.ZipFile(zip_path, 'r') as z:
contents = z.namelist()
print(contents)
except File... | simplelr_Docs | [
{
"content": "Question:\n## Coding Assessment Question\n\n### Problem Statement\nYour task is to implement a function `process_zip_file` that takes a path to a ZIP file and performs the following operations:\n\n1. **List the contents**: Print a list of all the files in the ZIP archive.\n2. **Extract a specified... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6698,
"level": 1,
"question": "## Coding Assessment Question\n\n### Problem Statement\nYour task is to implement a function `process_zip_file` that takes a path to a ZIP file and performs the following operations:\n\n1. **List the contents**: Print a list of all the files in the ZIP... |
def array_to_string(arr):
return ','.join(str(x) for x in arr) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to convert an array of integers to a string, where each integer is separated by a comma. For example, the array `[1, 2, 3]` should be converted to the string `\"1,2,3\"`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6699,
"level": 1,
"question": "Write a function to convert an array of integers to a string, where each integer is separated by a comma. For example, the array `[1, 2, 3]` should be converted to the string `\"1,2,3\"`.",
"split": "train"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.