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 invert_matrix(mat):
n = len(mat)
aug = []
# Create the augmented matrix with identity on the right
for i in range(n):
row = mat[i].copy()
identity = [0.0] * n
identity[i] = 1.0
row += identity
aug.append(row)
for i in range(n):
# Find the pivo... | simplelr_Data_Structure | [
{
"content": "Question:\n### Matrix Inverse Computation\n\n#### Problem Description:\nGiven a non-singular matrix `mat` of size `n x n`, computes its inverse. The inverse matrix `A^-1` is such that when multiplied by the original matrix `A`, the result is the identity matrix. Implement a function `invert_matrix... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4200,
"level": 1,
"question": "### Matrix Inverse Computation\n\n#### Problem Description:\nGiven a non-singular matrix `mat` of size `n x n`, computes its inverse. The inverse matrix `A^-1` is such that when multiplied by the original matrix `A`, the result is the identity matrix. ... |
from typing import List, Tuple
def manage_document_set(operations: List[Tuple[str, int]]) -> List[bool]:
document_set = set()
results = []
for op_type, doc_id in operations:
if op_type == "add":
document_set.add(doc_id)
elif op_type == "check":
results.append(doc_id ... | simplelr_Algorithm | [
{
"content": "Question:\n### Context:\nYou are working on a system to manage documents and their revisions. The system needs a feature to check if a set of documents contains any duplicates after a series of operations. Each document can be represented by a unique ID and the operations can either add a new docu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4201,
"level": 1,
"question": "### Context:\nYou are working on a system to manage documents and their revisions. The system needs a feature to check if a set of documents contains any duplicates after a series of operations. Each document can be represented by a unique ID and the o... |
def highest_rated_movie(movie_ratings):
if not movie_ratings:
return None
return max(movie_ratings.items(), key=lambda x: x[1])[0] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a dictionary with movie titles as keys and ratings as values, and returns the movie with the highest rating from the dictionary.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4202,
"level": 1,
"question": "Create a function that takes a dictionary with movie titles as keys and ratings as values, and returns the movie with the highest rating from the dictionary.",
"split": "train"
} |
def has_pair_sum(arr, target):
seen = set()
for num in arr:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes an array of integers and a target sum and returns a boolean indicating whether there are two distinct elements in the array that add up to the target sum.\n\nInput:\n\n- An integer N representing the number of elements in the array (1 <= N <= 100000).\n- An a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4203,
"level": 1,
"question": "Write a function that takes an array of integers and a target sum and returns a boolean indicating whether there are two distinct elements in the array that add up to the target sum.\n\nInput:\n\n- An integer N representing the number of elements in th... |
def max_subarray_sum(arr):
if not arr:
return 0
current_max = max_so_far = arr[0]
for num in arr[1:]:
current_max = max(num, current_max + num)
max_so_far = max(max_so_far, current_max)
return max_so_far | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program to find the maximum sum of a contiguous subarray within a one-dimensional array of integers. The array can contain both positive and negative integers. If the array is empty, the function should return 0. If the array contains all negative numbers, the function sh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4204,
"level": 1,
"question": "Write a Python program to find the maximum sum of a contiguous subarray within a one-dimensional array of integers. The array can contain both positive and negative integers. If the array is empty, the function should return 0. If the array contains al... |
import csv
import argparse
def count_distinct_ips(filename, min_comm, ip_field):
ip_counts = {}
with open(filename, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
ip = row[ip_field]
if ip in ip_counts:
ip_counts[ip] += 1
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python script that reads a CSV file containing network traffic data and identifies the number of distinct IP addresses that have communicated more than a specified number of times. The CSV file has the following structure: `timestamp,id,in_ip,in_port,out_ip,out_port,packet_size,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4205,
"level": 1,
"question": "Write a Python script that reads a CSV file containing network traffic data and identifies the number of distinct IP addresses that have communicated more than a specified number of times. The CSV file has the following structure: `timestamp,id,in_ip,i... |
def is_palindrome(s):
cleaned_str = ''.join([c for c in s if c.isalnum()]).lower()
return cleaned_str == cleaned_str[::-1] | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code snippet that checks for a palindrome in a given string, ignoring punctuation and case sensitivity?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4206,
"level": 1,
"question": "Can you provide a Python code snippet that checks for a palindrome in a given string, ignoring punctuation and case sensitivity?",
"split": "train"
} |
import os
def find_latest_file(directory, filename):
"""
Searches for a specific filename in the given directory and its subdirectories.
Returns the full path to the file with the latest modification time if found;
otherwise, returns None.
Args:
directory (str): The path to the directo... | simplelr_Filter | [
{
"content": "Question:\nPlease construct a Python function that requires two input parameters: one for the path to a specific directory and another for a particular filename. The function's task is to search for all files with the given filename within the specified directory and its subdirectories. Should it ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4207,
"level": 1,
"question": "Please construct a Python function that requires two input parameters: one for the path to a specific directory and another for a particular filename. The function's task is to search for all files with the given filename within the specified directory... |
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return [] | simplelr_Filter | [
{
"content": "Question:\nYou're given an array of integers `nums` and an integer `target`. Your task is to discover if there exist two numbers in `nums` that add up to `target`. You are allowed to return the indices of the two numbers.\n\n**Your task is to implement an efficient solution with a time complexity ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4208,
"level": 1,
"question": "You're given an array of integers `nums` and an integer `target`. Your task is to discover if there exist two numbers in `nums` that add up to `target`. You are allowed to return the indices of the two numbers.\n\n**Your task is to implement an efficie... |
def hex_to_rgb(hex_color):
hex_color = hex_color.lstrip('#')
if len(hex_color) == 3:
hex_color = ''.join([c * 2 for c in hex_color])
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
return (r, g, b) | simplelr_Filter | [
{
"content": "Question:\nI'm looking for a way to convert a hexadecimal color code to its corresponding RGB values. Can you provide a simple Python function to do this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4209,
"level": 1,
"question": "I'm looking for a way to convert a hexadecimal color code to its corresponding RGB values. Can you provide a simple Python function to do this?",
"split": "train"
} |
def findBuildingsWithOceanView(nums):
max_so_far = 0
result = []
for i in range(len(nums) - 1, -1, -1):
if nums[i] > max_so_far:
result.append(i)
max_so_far = nums[i]
return result[::-1] | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** array of integers `nums`. Each integer in `nums` represents the height of a building. An ocean is to the right of the array (beyond the last element). A building has an \"ocean view\" if all buildings to its right have a smaller height.\n\nReturn _an intege... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4210,
"level": 1,
"question": "You are given a **0-indexed** array of integers `nums`. Each integer in `nums` represents the height of a building. An ocean is to the right of the array (beyond the last element). A building has an \"ocean view\" if all buildings to its right have a s... |
from typing import List, Dict, Tuple
from http import HTTPStatus
def get_status_details(codes: List[int]) -> Dict[int, Tuple[str, str]]:
status_dict = {}
for code in codes:
status = HTTPStatus(code)
status_dict[code] = (status.phrase, status.description)
return status_dict
| simplelr_Docs | [
{
"content": "Question:\n#### Objective\nYour task is to implement a function that takes a list of integer HTTP status codes and returns a dictionary where the keys are the integer status codes and the values are tuples containing the status code's phrase and description.\n\nYou must utilize the `http.HTTPStatu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4211,
"level": 1,
"question": "#### Objective\nYour task is to implement a function that takes a list of integer HTTP status codes and returns a dictionary where the keys are the integer status codes and the values are tuples containing the status code's phrase and description.\n\nY... |
def move_zeros(array: list) -> list:
non_zeros = []
zero_count = 0
for x in array:
if type(x) is int and x == 0:
zero_count += 1
else:
non_zeros.append(x)
non_zeros.extend([0] * zero_count)
return non_zeros | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Move Zeros to the End\n\nYou are given an array which contains various types of elements including integers, strings, booleans, etc. You need to write a function that moves all of the zeros to the end of the array while preserving the order of the non-zero elements.\n\n**F... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4212,
"level": 1,
"question": "### Question: Move Zeros to the End\n\nYou are given an array which contains various types of elements including integers, strings, booleans, etc. You need to write a function that moves all of the zeros to the end of the array while preserving the ord... |
def count_fruits(basket):
fruit_counts = {}
for fruit in basket:
lower_fruit = fruit.lower()
if lower_fruit in fruit_counts:
fruit_counts[lower_fruit] += 1
else:
fruit_counts[lower_fruit] = 1
return fruit_counts
| simplelr_Taco | [
{
"content": "Question:\nYour task is to write a function, `count_fruits(basket)`, that takes a list of strings representing different fruits in a basket and returns a dictionary with each fruit as a key and the number of times it appears in the list as the corresponding value. The comparison should be case-ins... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4213,
"level": 1,
"question": "Your task is to write a function, `count_fruits(basket)`, that takes a list of strings representing different fruits in a basket and returns a dictionary with each fruit as a key and the number of times it appears in the list as the corresponding value... |
def square_integers(nums):
return list(map(lambda x: x ** 2, nums)) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns a new list containing the squares of the integers from the original list. Use the map function to achieve this.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4214,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns a new list containing the squares of the integers from the original list. Use the map function to achieve this.",
"split": "train"
} |
def sieve_of_eratosthenes(n):
"""Generate prime numbers up to a given number n."""
if n < 2:
return []
primes = [True] * (n + 1)
primes[0], primes[1] = False, False
for num in range(2, int(n ** 0.5) + 1):
if primes[num]:
for multiple in range(num * num, n + 1, num):
... | simplelr_Filter | [
{
"content": "Question:\ndef sieve_of_eratosthenes(n):\n \"\"\"Function to generate prime numbers up to a given number n.\"\"\"\n primes = [True] * (n + 1)\n primes[0] = primes[1] = False\n\n for num in range(2, int(n**0.5) + 1):\n if primes[num]:\n for multiple in range(num * num,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4215,
"level": 1,
"question": "def sieve_of_eratosthenes(n):\n \"\"\"Function to generate prime numbers up to a given number n.\"\"\"\n primes = [True] * (n + 1)\n primes[0] = primes[1] = False\n\n for num in range(2, int(n**0.5) + 1):\n if primes[num]:\n ... |
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_pos = (n - 1) % digits
return int(str(number)[digit_pos]) | simplelr_Data_Structure | [
{
"content": "Question:\n**Objective**: Write a function to accurately locate and return the nth digit in an infinitely long sequence of concatenated positive integers.\n\n#### Description\n\nGiven a positive integer n, the task is to find the nth digit of the sequence formed by concatenating all positive integ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4216,
"level": 1,
"question": "**Objective**: Write a function to accurately locate and return the nth digit in an infinitely long sequence of concatenated positive integers.\n\n#### Description\n\nGiven a positive integer n, the task is to find the nth digit of the sequence formed ... |
def find_pairs(arr, target):
pairs = set()
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
a, b = arr[i], arr[j]
if a + b == target:
pair = tuple(sorted((a, b)))
pairs.add(pair)
sorted_pairs = sorted(pairs)
return sorted_pairs... | simplelr_Taco | [
{
"content": "Question:\nYou are given an array of integers and a target sum. Your task is to write a function that returns the array of all unique pairs of numbers that add up to the target sum. Each pair should be returned as a tuple and the pairs should be sorted in ascending order. Note that the elements wi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4217,
"level": 1,
"question": "You are given an array of integers and a target sum. Your task is to write a function that returns the array of all unique pairs of numbers that add up to the target sum. Each pair should be returned as a tuple and the pairs should be sorted in ascendi... |
import numpy as np
def generate_random_matrix(rows, cols):
return np.random.rand(rows, cols) | simplelr_Filter | [
{
"content": "Question:\nI want to generate a random matrix of size (3, 4) and then create a load and store it into an object. I am assuming this is using Python. \n\nHere is some incomplete code:\n\n```\nimport numpy as np\n\ndef generate_random_matrix(rows, cols):\n # YOUR CODE HERE\n pass\n\ndef creat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4218,
"level": 1,
"question": "I want to generate a random matrix of size (3, 4) and then create a load and store it into an object. I am assuming this is using Python. \n\nHere is some incomplete code:\n\n```\nimport numpy as np\n\ndef generate_random_matrix(rows, cols):\n # YO... |
def count_non_overlapping_subsequences(events):
if not events:
return 0
count = 1
for i in range(1, len(events)):
if events[i] != events[i-1]:
count += 1
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of events represented by a string `events` of length `n`, where each character represents a type of event occurring at a specific time unit. There are three types of events: 'A', 'B', and 'C'. You need to process these events and determine the maximum number of non-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4219,
"level": 1,
"question": "You are given a list of events represented by a string `events` of length `n`, where each character represents a type of event occurring at a specific time unit. There are three types of events: 'A', 'B', and 'C'. You need to process these events and d... |
def remove_occurrences(lst, num):
return [x for x in lst if x != num] | simplelr_Evol | [
{
"content": "Question:\nWrite a function in Python that takes a list of integers and a single integer. The function should return a new list with all occurrences of the given integer removed.\n\n```python\ndef remove_occurrences(lst, num):\n # code to remove all occurrences of 'num' from 'lst'\n pass\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4220,
"level": 1,
"question": "Write a function in Python that takes a list of integers and a single integer. The function should return a new list with all occurrences of the given integer removed.\n\n```python\ndef remove_occurrences(lst, num):\n # code to remove all occurrence... |
def remove_duplicates(nums):
if not nums:
return 0
slow = 0
for fast in range(len(nums)):
duplicate = False
for j in range(slow):
if nums[fast] == nums[j]:
duplicate = True
break
if not duplicate:
nums[slow] = nums[fast]... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to remove all duplicates from an array in-place, ensuring each element appears only once, and return the new length of the array after removal. The function should not use any extra space.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4221,
"level": 1,
"question": "Write a function to remove all duplicates from an array in-place, ensuring each element appears only once, and return the new length of the array after removal. The function should not use any extra space.",
"split": "train"
} |
def is_palindrome_sequence(lst):
cleaned = []
for element in lst:
s = str(element)
for char in s:
if char.isalnum():
cleaned.append(char.lower())
cleaned_str = ''.join(cleaned)
return cleaned_str == cleaned_str[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if a given list of numbers is a palindrome. A palindrome is a sequence that reads the same backward as forward. The function should ignore spaces, punctuation, and capitalization.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4222,
"level": 1,
"question": "Create a function that checks if a given list of numbers is a palindrome. A palindrome is a sequence that reads the same backward as forward. The function should ignore spaces, punctuation, and capitalization.",
"split": "train"
} |
def to_custom_binary(n):
return f'0b{bin(n)[2:]}00' | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a number as an input and returns a string that represents the number in binary, with the prefix '0b' and the suffix '00' added to the binary string. For example, if the input is 5, the function should return '0b10100'. If the input is 10, the function should... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4223,
"level": 1,
"question": "Create a function that takes a number as an input and returns a string that represents the number in binary, with the prefix '0b' and the suffix '00' added to the binary string. For example, if the input is 5, the function should return '0b10100'. If t... |
def total_cost(cart):
return sum(price * quantity for price, quantity in cart) | simplelr_Filter | [
{
"content": "Question:\nCan you help me write a Python function to calculate the total cost of items in a shopping cart? Each item in the cart has a price and a quantity. The function should take a list of tuples as input, where each tuple contains the price and quantity of an item. For example, the input coul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4224,
"level": 1,
"question": "Can you help me write a Python function to calculate the total cost of items in a shopping cart? Each item in the cart has a price and a quantity. The function should take a list of tuples as input, where each tuple contains the price and quantity of a... |
import os
def directory_files(file_paths):
dir_files = {}
for path in file_paths:
dir_name = os.path.dirname(path)
if dir_name != '' and dir_name != '/':
dir_name += '/'
file_name = os.path.basename(path)
if dir_name not in dir_files:
dir_files[dir_name] ... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a list of strings representing file paths and returns a dictionary where the keys are the directory paths and the values are lists of files found in those directories. The file paths will always be complete paths and you may assume that directory paths in the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4225,
"level": 1,
"question": "Write a function that takes a list of strings representing file paths and returns a dictionary where the keys are the directory paths and the values are lists of files found in those directories. The file paths will always be complete paths and you may... |
def check_parentheses_validity(expression: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in expression:
if char in ['(', '{', '[']:
stack.append(char)
else:
if not stack:
return False
top = stack.pop()
... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with verifying the validity of a sequence of parentheses in a given expression. The expression contains only the characters '(', ')', '{', '}', '[' and ']'. Your goal is to implement a function `check_parentheses_validity(expression: str) -> bool` which returns `True` if ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4226,
"level": 1,
"question": "You are tasked with verifying the validity of a sequence of parentheses in a given expression. The expression contains only the characters '(', ')', '{', '}', '[' and ']'. Your goal is to implement a function `check_parentheses_validity(expression: str... |
from typing import List, Tuple
def can_attend_all_meetings(intervals: List[Tuple[int, int]]) -> bool:
if not intervals:
return True
# Sort the intervals based on start time
sorted_intervals = sorted(intervals, key=lambda x: x[0])
# Check each consecutive pair for overlap
for i in ... | simplelr_Apps | [
{
"content": "Question:\n## Task\n\nGiven a list of meeting time intervals `intervals`, where each interval is represented as a tuple `(start, end)` denoting the start time and end time of the meeting, determine if a person could attend all meetings without any overlap.\n\nWrite a function `can_attend_all_meeti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4227,
"level": 1,
"question": "## Task\n\nGiven a list of meeting time intervals `intervals`, where each interval is represented as a tuple `(start, end)` denoting the start time and end time of the meeting, determine if a person could attend all meetings without any overlap.\n\nWri... |
def character_frequency(s):
char_count = {}
s_lower = s.lower()
for char in s_lower:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns a dictionary where the keys are the unique characters from the string and the values are the frequency count of each character. The function should ignore the case and consider 'A' and 'a' to be the same character.\nAnswer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4228,
"level": 1,
"question": "Write a Python function that takes a string as input and returns a dictionary where the keys are the unique characters from the string and the values are the frequency count of each character. The function should ignore the case and consider 'A' and 'a... |
def find_duplicate(nums):
seen = set()
for num in nums:
if num in seen:
return num
seen.add(num)
return None | simplelr_Filter | [
{
"content": "Question:\nI have been trying to solve this problem for hours, and I just can't seem to get it. Here is the problem: \n\nWrite a function called `find_duplicate` that takes a list of integers as input and returns the duplicate element if it exists. If no duplicate element is found, return `None`.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4229,
"level": 1,
"question": "I have been trying to solve this problem for hours, and I just can't seem to get it. Here is the problem: \n\nWrite a function called `find_duplicate` that takes a list of integers as input and returns the duplicate element if it exists. If no duplicat... |
def length_of_longest_substring_two_distinct(s):
char_count = {}
left = 0
max_len = 0
for right in range(len(s)):
char = s[right]
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
while len(char_count) > 2:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s`, return the length of the longest substring that contains at most two distinct characters. The test cases are generated so that the answer will fit in a **32-bit** integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4230,
"level": 1,
"question": "Given a string `s`, return the length of the longest substring that contains at most two distinct characters. The test cases are generated so that the answer will fit in a **32-bit** integer.",
"split": "train"
} |
def organize_zero(arr):
if not arr:
return []
non_zero = [x for x in arr if x != 0]
zero_count = arr.count(0)
return non_zero + [0] * zero_count | simplelr_Filter | [
{
"content": "Question:\ncreate a function that called organize zero, the function will receive an array parameter of integer and move all of the zero values to the end of the array while maintaining the relative order of the non-zero elements. If the function receive empty array the function will return an emp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4231,
"level": 1,
"question": "create a function that called organize zero, the function will receive an array parameter of integer and move all of the zero values to the end of the array while maintaining the relative order of the non-zero elements. If the function receive empty ar... |
def max_occupancy(events):
current = 0
max_p = 0
for event in events:
if event == 'E':
current += 1
else:
current -= 1
if current > max_p:
max_p = current
return max_p | simplelr_Codeforces | [
{
"content": "Question:\nTwo detectives, Alice and Bob, are investigating a series of robbery cases. As part of their investigation, they have a collection of security camera footage that they want to analyze. Each footage captures a number of people coming in and out of a building at different times. \n\nThe f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4232,
"level": 1,
"question": "Two detectives, Alice and Bob, are investigating a series of robbery cases. As part of their investigation, they have a collection of security camera footage that they want to analyze. Each footage captures a number of people coming in and out of a bui... |
#!/usr/bin/env python3.10
import os
import site
import importlib.util
def main():
try:
# Handle PYTHONCUSTOMSTARTUP
startup_file = os.getenv('PYTHONCUSTOMSTARTUP')
if startup_file is not None:
try:
with open(startup_file, 'r') as f:
exec(f.re... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\nWrite a Python script that demonstrates your understanding of making the script executable, handling errors, using environment variables, and implementing a Python startup customization.\n\n#### Problem Statement\n\nYou are required to create a Python script `custom_scri... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4233,
"level": 1,
"question": "#### Objective\nWrite a Python script that demonstrates your understanding of making the script executable, handling errors, using environment variables, and implementing a Python startup customization.\n\n#### Problem Statement\n\nYou are required to ... |
def is_strict_palindrome(s: str) -> bool:
"""
Determines if the given string is a valid palindrome considering only alphanumeric characters and ignoring cases, while treating `!` as a palindrome-breaking character.
Parameters:
s (str): The input string to check.
Returns:
bool: `True` i... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are required to implement a function that checks if a given string is a valid palindrome considering only alphanumeric characters and ignoring cases, while also supporting the exclamation mark `!` as a palindrome-breaking character. If the exclamation mark i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4234,
"level": 1,
"question": "### Problem Statement\n\nYou are required to implement a function that checks if a given string is a valid palindrome considering only alphanumeric characters and ignoring cases, while also supporting the exclamation mark `!` as a palindrome-breaking c... |
def min_intervals_to_cover_peaks(prices):
if len(prices) < 3:
return 0
count = 0
for i in range(1, len(prices) - 1):
if prices[i-1] < prices[i] and prices[i] > prices[i+1]:
count += 1
return count | simplelr_Leetcode | [
{
"content": "Question:\nGiven a **0-indexed** array `prices` where `prices[i]` is the price of a stock on the `i-th` day, find the **minimum** number of non-overlapping intervals you need to select such that each interval contains one local peak. A local peak is defined as `prices[i]` where `prices[i-1] < pric... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4235,
"level": 1,
"question": "Given a **0-indexed** array `prices` where `prices[i]` is the price of a stock on the `i-th` day, find the **minimum** number of non-overlapping intervals you need to select such that each interval contains one local peak. A local peak is defined as `p... |
import json
def filter_photos(input_file, output_file, keyword):
# Load the photos from the input JSON file
try:
with open(input_file, 'r') as file:
photos = json.load(file)
except FileNotFoundError:
print(f"File {input_file} not found.")
return
except json.JSONDecod... | simplelr_Filter | [
{
"content": "Question:\nImagine you have a JSON file that describes photos in a gallery. Each photo has attributes such as `title`, `url`, and `description`. Your task is to write a Python script that reads this JSON file, filters photos based on a keyword present in the `title` or `description`, and saves the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4236,
"level": 1,
"question": "Imagine you have a JSON file that describes photos in a gallery. Each photo has attributes such as `title`, `url`, and `description`. Your task is to write a Python script that reads this JSON file, filters photos based on a keyword present in the `tit... |
from typing import List
def pigeonhole_sort(arr: List[int]) -> List[int]:
if not arr:
return []
min_val = min(arr)
max_val = max(arr)
range_size = max_val - min_val + 1
pigeonholes = [0] * range_size
for num in arr:
pigeonholes[num - min_val] += 1
result = []
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Pigeonhole Sort Function Implementation\n\n#### Context\nPigeonhole sort is a non-comparison based sorting algorithm suitable for sorting lists where the number of elements and the range of possible keys are approximately the same. It works by finding the range of input elements, cr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4237,
"level": 1,
"question": "### Pigeonhole Sort Function Implementation\n\n#### Context\nPigeonhole sort is a non-comparison based sorting algorithm suitable for sorting lists where the number of elements and the range of possible keys are approximately the same. It works by find... |
def element_frequency(arr):
freq_dict = {}
for num in arr:
if num in freq_dict:
freq_dict[num] += 1
else:
freq_dict[num] = 1
return freq_dict | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Array Element Frequency Counter\n\nYou're given an array of integers where some elements appear more than once and some appear only once. Your task is to write a function that counts the frequency of each element in the array and returns a dictionary where keys are the ele... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4238,
"level": 1,
"question": "### Question: Array Element Frequency Counter\n\nYou're given an array of integers where some elements appear more than once and some appear only once. Your task is to write a function that counts the frequency of each element in the array and returns ... |
import random
def generate_predictions(chain, start_state, num_predictions):
current_state = start_state
predictions = []
for _ in range(num_predictions):
transitions = chain[current_state]
next_states = list(transitions.keys())
probabilities = list(transitions.values())
nex... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Context\nYou are a software developer working on a predictive text feature for a chat application. Given a user’s previous message, you aim to suggest the next word they are likely to type based on historical data of word sequences. You will utilize a Markov Chain to model this beh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4239,
"level": 1,
"question": "#### Context\nYou are a software developer working on a predictive text feature for a chat application. Given a user’s previous message, you aim to suggest the next word they are likely to type based on historical data of word sequences. You will utili... |
def count_total_characters(s):
return len(s) | simplelr_Filter | [
{
"content": "Question:\nCan you generate a Python function that calculates the total number of characters in a given string, including spaces and punctuation?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4240,
"level": 1,
"question": "Can you generate a Python function that calculates the total number of characters in a given string, including spaces and punctuation?",
"split": "train"
} |
def compress_string(s: str) -> str:
if not s:
return s
current_char = s[0]
count = 1
compressed = []
for char in s[1:]:
if char == current_char:
count += 1
else:
compressed.append(current_char + str(count))
current_char = char
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge: String Compression\n\nYou are working on a text editor software that optimizes storage by employing a basic form of text compression. Your task is to implement a function that compresses a given string using the following rules:\n\n- Consecutive characters are repl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4241,
"level": 1,
"question": "### Coding Challenge: String Compression\n\nYou are working on a text editor software that optimizes storage by employing a basic form of text compression. Your task is to implement a function that compresses a given string using the following rules:\n... |
def filter_and_sort(numbers):
return sorted([num for num in numbers if 10 < num < 20], reverse=True) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers as input and returns a new list containing only the numbers that are greater than 10 and less than 20. The function should sort the numbers in the new list in descending order.\nAnswer:\nLet's think step by step.\n",
"role": "use... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4242,
"level": 1,
"question": "Write a Python function that takes a list of integers as input and returns a new list containing only the numbers that are greater than 10 and less than 20. The function should sort the numbers in the new list in descending order.",
"split": "train"
... |
def is_palindrome(s):
# Normalize the string by converting to lowercase and removing non-alphanumeric characters
processed = ''.join([c for c in s.lower() if c.isalnum()])
# Check if the processed string is a palindrome
return processed == processed[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if a given string is a plaindrome. A palindrome is a word, phrase, number, or other sequences of characters which reads the same backward as forward, ignoring spaces, punctuation, and capitalization.\nAnswer:\nLet's think step by step.\n",
"role": "user... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4243,
"level": 1,
"question": "Create a function that checks if a given string is a plaindrome. A palindrome is a word, phrase, number, or other sequences of characters which reads the same backward as forward, ignoring spaces, punctuation, and capitalization.",
"split": "train"
} |
def maxLuxurySum(N, lux):
current_sum = 0
max_sum = 0
for num in lux:
current_sum += num
if current_sum > max_sum:
max_sum = current_sum
if current_sum < 0:
current_sum = 0
return max_sum
| simplelr_Taco | [
{
"content": "Question:\nConsider a luxury cruise ship with N rooms arranged in a row. Each room has a certain number of luxurious amenities which contribute to its overall luxury level. You are given an array lux[], where lux[i] represents the luxury level of the i-th room. Passengers can select any number of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4244,
"level": 1,
"question": "Consider a luxury cruise ship with N rooms arranged in a row. Each room has a certain number of luxurious amenities which contribute to its overall luxury level. You are given an array lux[], where lux[i] represents the luxury level of the i-th room. P... |
def analyze_numbers(numbers):
if not numbers:
return {
'total_count': 0,
'sum': 0,
'mean': None,
'median': None,
'max': None,
'min': None
}
total_count = len(numbers)
total_sum = sum(numbers)
mean = total_sum / tota... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function that extracts and computes various properties of a given list of numbers. The goal is to become familiar with list manipulation and basic statistical computations using Python.\n\nName the function `analyze_numbers`.\n\nRequirements:\n1. The funct... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4245,
"level": 1,
"question": "You are tasked with creating a function that extracts and computes various properties of a given list of numbers. The goal is to become familiar with list manipulation and basic statistical computations using Python.\n\nName the function `analyze_numbe... |
def process_string(s):
# Remove all spaces from the string
no_space = s.replace(' ', '')
# Count the number of digits in the original string
digit_count = sum(1 for char in s if char.isdigit())
return (no_space, digit_count) | simplelr_Evol | [
{
"content": "Question:\nImplement a function in your preferred programming language that takes a string as input and returns a tuple. The first element of the tuple should be the input string with all spaces removed, and the second element should be an integer representing the count of digits ('0'-'9') in the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4246,
"level": 1,
"question": "Implement a function in your preferred programming language that takes a string as input and returns a tuple. The first element of the tuple should be the input string with all spaces removed, and the second element should be an integer representing th... |
from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, ProxyHandler, build_opener
from urllib.parse import urlparse
from urllib.error import HTTPError, URLError
def fetch_url(url: str, auth: dict = None, proxy: dict = None) -> str:
"""
Fetches the content of a given URL with optional... | simplelr_Docs | [
{
"content": "Question:\n### Task\n\nYou are required to write a Python function that performs several URL-related tasks using the `urllib.request` module. The function should:\n\n1. **Fetch Content**: Fetches the content of a given URL.\n2. **Handle Redirects**: Properly handle HTTP redirects.\n3. **Use Authen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4247,
"level": 1,
"question": "### Task\n\nYou are required to write a Python function that performs several URL-related tasks using the `urllib.request` module. The function should:\n\n1. **Fetch Content**: Fetches the content of a given URL.\n2. **Handle Redirects**: Properly hand... |
def hex_list_to_decimal(hex_list):
total = 0
for s in hex_list:
total += int(s, 16)
return total | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to convert a list of hexadecimal numbers to a single decimal number. The function should take a list of strings, where each string represents a hexadecimal number, and return a single decimal number. The hexadecimal numbers can be positive or negative.\nAnswer:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4248,
"level": 1,
"question": "Write a Python function to convert a list of hexadecimal numbers to a single decimal number. The function should take a list of strings, where each string represents a hexadecimal number, and return a single decimal number. The hexadecimal numbers can ... |
def split_string(s, k):
substrings = []
for i in range(0, len(s), k):
substrings.append(s[i:i+k])
return substrings | simplelr_Leetcode | [
{
"content": "Question:\nGiven a **0-indexed** string `s` and an integer `k`, split the string into as many substrings as possible, each of length `k`. Return _an array of these substrings_. If the string cannot be exactly divided into substrings of length `k`, then the last substring should contain the remaini... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4249,
"level": 1,
"question": "Given a **0-indexed** string `s` and an integer `k`, split the string into as many substrings as possible, each of length `k`. Return _an array of these substrings_. If the string cannot be exactly divided into substrings of length `k`, then the last s... |
def transform_list_to_string(nums):
return ",".join([f"({num})" for num in nums]) | simplelr_Filter | [
{
"content": "Question:\nI need to create a Python function that can transform a list of integers into a string, with each number in the string enclosed in parentheses and separated by commas. For example, the list `[1, 2, 3]` should be transformed into the string `\"(1),(2),(3)\"`. How can I achieve this?\nAns... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4250,
"level": 1,
"question": "I need to create a Python function that can transform a list of integers into a string, with each number in the string enclosed in parentheses and separated by commas. For example, the list `[1, 2, 3]` should be transformed into the string `\"(1),(2),(... |
from typing import List
def rotate_array(arr: List[int], k: int) -> List[int]:
n = len(arr)
if n == 0:
return []
k = k % n
if k == 0:
return arr.copy()
return arr[-k:] + arr[:-k] | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nDesign and implement the `rotate_array` function which rotates the elements of an array to the right by `k` steps. The rotation means that each element of the array is shifted to the right by `k` positions, and the elements that overflow are wrapped around to th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4251,
"level": 1,
"question": "### Problem Statement\n\nDesign and implement the `rotate_array` function which rotates the elements of an array to the right by `k` steps. The rotation means that each element of the array is shifted to the right by `k` positions, and the elements tha... |
def collatz_sequence_length(n: int) -> int:
if not hasattr(collatz_sequence_length, 'memo'):
collatz_sequence_length.memo = {1: 0}
memo = collatz_sequence_length.memo
current = n
path = []
while current not in memo:
path.append(current)
if current % 2 == 0:
curre... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem: Collatz Sequence Length\n\nYou are participating in a coding apprenticeship at a software firm, and one of the tasks you are given is based on the Collatz conjecture. Your objective is to write a Python function that calculates the length of the Collatz sequence for a given... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4252,
"level": 1,
"question": "### Problem: Collatz Sequence Length\n\nYou are participating in a coding apprenticeship at a software firm, and one of the tasks you are given is based on the Collatz conjecture. Your objective is to write a Python function that calculates the length ... |
def square_numbers(input_sequence):
return [num ** 2 for num in input_sequence] | simplelr_Filter | [
{
"content": "Question:\nThis is the problem:\n\nYou have a sequence of numbers, like this:\n\n```\n1, 2, 3, 4, 5\n```\n\nYou need to write a Python function that takes this sequence as input and returns a new sequence where each number is squared.\n\n**For example:**\n\n```python\ninput_sequence = [1, 2, 3, 4,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4253,
"level": 1,
"question": "This is the problem:\n\nYou have a sequence of numbers, like this:\n\n```\n1, 2, 3, 4, 5\n```\n\nYou need to write a Python function that takes this sequence as input and returns a new sequence where each number is squared.\n\n**For example:**\n\n```py... |
from typing import List, Tuple
def sort_tuples(arr: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
return sorted(arr, key=lambda x: (x[0], -x[1])) | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\nYou are tasked with writing a Python function that demonstrates an understanding of sorting algorithms and their optimization when dealing with large datasets. Specifically, you will create a function that sorts a list of integer tuples based on a speci... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4254,
"level": 1,
"question": "### Coding Assessment Question\n\nYou are tasked with writing a Python function that demonstrates an understanding of sorting algorithms and their optimization when dealing with large datasets. Specifically, you will create a function that sorts a list... |
def cycle_sort(arr: list) -> list:
sorted_arr = sorted(arr)
n = len(arr)
for i in range(n):
if arr[i] == sorted_arr[i]:
continue
# Find the position j where arr[j] is the target value
target = sorted_arr[i]
j = i
while arr[j] != target:
j += 1
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Cycle Sort Implementation Question\n\n**Scenario**: You work as a software developer at a company dealing with embedded systems where the number of write cycles to the memory is restricted. Your task is to implement a Cycle Sort algorithm to minimize the number of write operations.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4255,
"level": 1,
"question": "### Cycle Sort Implementation Question\n\n**Scenario**: You work as a software developer at a company dealing with embedded systems where the number of write cycles to the memory is restricted. Your task is to implement a Cycle Sort algorithm to minimi... |
def unique_paths(m, n):
a = m + n - 2
b = min(m-1, n-1)
result = 1
for i in range(1, b + 1):
result = result * (a - b + i) // i
return result | simplelr_Leetcode | [
{
"content": "Question:\nA robot is positioned at a 2D grid starting from the top-left corner (0, 0). The grid is of size `m x n`. The robot can move either left, right, up, or down, but it cannot visit the same cell more than once.\n\nYour task is to write a function that determines the number of distinct path... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4256,
"level": 1,
"question": "A robot is positioned at a 2D grid starting from the top-left corner (0, 0). The grid is of size `m x n`. The robot can move either left, right, up, or down, but it cannot visit the same cell more than once.\n\nYour task is to write a function that det... |
def find_max_sum_subarray(arr):
if not arr:
return 0 # or handle empty array as needed
max_so_far = arr[0]
curr_max = arr[0]
for i in range(1, len(arr)):
curr_max = max(arr[i], curr_max + arr[i])
max_so_far = max(max_so_far, curr_max)
return max_so_far | simplelr_Filter | [
{
"content": "Question:\nThis is what I have so far:\n\n```python\ndef find_max_sum_subarray(arr):\n max_so_far = arr[0]\n curr_max = arr[0]\n for i in range(1, len(arr)):\n curr_max = max(arr[i], curr_max + arr[i])\n max_so_far = max(max_so_far, curr_max)\n return max_so_far\nAnswer:\nLet's think ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4257,
"level": 1,
"question": "This is what I have so far:\n\n```python\ndef find_max_sum_subarray(arr):\n max_so_far = arr[0]\n curr_max = arr[0]\n for i in range(1, len(arr)):\n curr_max = max(arr[i], curr_max + arr[i])\n max_so_far = max(max_so_far, curr_max)\n return m... |
def smallest_missing_positive(arr):
s = set(arr)
i = 1
while True:
if i not in s:
return i
i += 1 | simplelr_Code_Contests | [
{
"content": "Question:\nYou are given an array of integers. Your task is to find the smallest positive integer that is missing from the array.\n\nFor example:\nIf the input array is [1, 2, 0], the smallest missing positive integer is 3.\nIf the input array is [3, 4, -1, 1], the smallest missing positive intege... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4258,
"level": 1,
"question": "You are given an array of integers. Your task is to find the smallest positive integer that is missing from the array.\n\nFor example:\nIf the input array is [1, 2, 0], the smallest missing positive integer is 3.\nIf the input array is [3, 4, -1, 1], t... |
from collections import Counter
def common_elements(list1, list2):
counter1 = Counter(list1)
counter2 = Counter(list2)
common = counter1 & counter2
return list(common.elements()) | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function that takes in two lists of integers, `list1` and `list2`, and returns a new list. This new list should contain only the integers that are present in both input lists, and each element in the resulting list should appear as many times as it appears in both lists.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4259,
"level": 1,
"question": "Design a Python function that takes in two lists of integers, `list1` and `list2`, and returns a new list. This new list should contain only the integers that are present in both input lists, and each element in the resulting list should appear as many... |
import re
def is_hex_color_code(s):
return bool(re.fullmatch(r'^#[A-Fa-f0-9]{6}$', s)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to check if a string is a valid hexadecimal color code. A valid hexadecimal color code starts with a '#' symbol and is followed by exactly six hexadecimal digits (0-9, A-F, a-f).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4260,
"level": 1,
"question": "Write a python function to check if a string is a valid hexadecimal color code. A valid hexadecimal color code starts with a '#' symbol and is followed by exactly six hexadecimal digits (0-9, A-F, a-f).",
"split": "train"
} |
def reverse_string(s):
return s[::-1] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that reverses the characters of a string. For example, reversing the string 'hello' should return 'olleh'. The function should also handle edge cases such as empty strings and strings with only one character.\nAnswer:\nLet's think step by step.\n",
"role": "u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4261,
"level": 1,
"question": "Write a Python function that reverses the characters of a string. For example, reversing the string 'hello' should return 'olleh'. The function should also handle edge cases such as empty strings and strings with only one character.",
"split": "train... |
def list_depth(lst):
if not isinstance(lst, list):
return 0
if len(lst) == 0:
return 1
max_depth = 0
for element in lst:
if isinstance(element, list):
current_depth = list_depth(element)
if current_depth > max_depth:
max_depth = current_dep... | simplelr_Apps | [
{
"content": "Question:\nDesign a function `list_depth :: Any -> int` that determines the depth of a nested list. The depth of a list is defined as the maximum depth of any nested list plus one. An empty list has a depth of 1.\n\nFor example:\n```python\nlist_depth([]) # must be 1\nlist_depth([1, 2, 3]) # must ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4262,
"level": 1,
"question": "Design a function `list_depth :: Any -> int` that determines the depth of a nested list. The depth of a list is defined as the maximum depth of any nested list plus one. An empty list has a depth of 1.\n\nFor example:\n```python\nlist_depth([]) # must ... |
import configparser
def parse_config(file_path: str) -> dict:
config = configparser.ConfigParser()
config.read(file_path)
data = {}
for section_name in config.sections():
section_dict = {}
for key in config[section_name]:
if section_name == 'Features':
v... | simplelr_Docs | [
{
"content": "Question:\n### Advanced Configuration File Parsing with `ConfigParser`\n\n#### Problem Statement\n\nYou are provided with a configuration file (`config.ini`) with the following sections and key-values:\n\n```\n[General]\nversion = 1.2.3\ndefault_path = /usr/local/bin\n\n[Database]\nhost = localhos... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4263,
"level": 1,
"question": "### Advanced Configuration File Parsing with `ConfigParser`\n\n#### Problem Statement\n\nYou are provided with a configuration file (`config.ini`) with the following sections and key-values:\n\n```\n[General]\nversion = 1.2.3\ndefault_path = /usr/local... |
# Function to sort a list of numbers in ascending order
def sort_numbers(numbers):
"""
Sorts a list of numbers in ascending order and returns the sorted list.
Args:
numbers (list): A list of numbers to be sorted.
Returns:
list: A new list containing the numbers sorted in ascend... | simplelr_Filter | [
{
"content": "Question:\nWrite a program in Python that sorts a list of numbers in ascending order. Make sure to use a function for this task and include comments explaining each part of your code.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4264,
"level": 1,
"question": "Write a program in Python that sorts a list of numbers in ascending order. Make sure to use a function for this task and include comments explaining each part of your code.",
"split": "train"
} |
def dp_binomial_coefficient(n: int, k: int) -> int:
if k == 0 or k == n:
return 1
dp = [0] * (k + 1)
dp[0] = 1
for i in range(1, n + 1):
max_j = min(i, k)
for j in range(max_j, 0, -1):
dp[j] += dp[j - 1]
return dp[k] | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem: Dynamic Programming Binomial Coefficient\n\nYou are required to implement a function to compute the binomial coefficient \\( C(n, k) \\) using a dynamic programming approach. The binomial coefficient represents the number of ways to choose \\( k \\) items from \\( n \\) ite... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4265,
"level": 1,
"question": "### Problem: Dynamic Programming Binomial Coefficient\n\nYou are required to implement a function to compute the binomial coefficient \\( C(n, k) \\) using a dynamic programming approach. The binomial coefficient represents the number of ways to choose... |
import uuid
def uuid_operations():
# Generate UUIDs
uuid1 = uuid.uuid1()
uuid4 = uuid.uuid4()
# Create UUIDs from their representations
uuid1_from_hex = uuid.UUID(hex=uuid1.hex)
uuid4_from_bytes = uuid.UUID(bytes=uuid4.bytes)
# List of tuples containing each UUID and its name
... | simplelr_Docs | [
{
"content": "Question:\n**Understanding and Manipulating UUIDs**\n\n**Objective:**\n\nWrite a Python function that demonstrates your understanding of the `uuid` module, specifically focusing on the following aspects:\n\n1. Generating UUIDs using different algorithms.\n2. Creating a UUID from various representa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4266,
"level": 1,
"question": "**Understanding and Manipulating UUIDs**\n\n**Objective:**\n\nWrite a Python function that demonstrates your understanding of the `uuid` module, specifically focusing on the following aspects:\n\n1. Generating UUIDs using different algorithms.\n2. Crea... |
import re
def is_valid_phone_number(phone_number):
pattern = r'^\+1 \d{3} \d{3} \d{4}$'
return bool(re.fullmatch(pattern, phone_number)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to check the validity of a given phone number in the format of `+1 123 456 7890`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4267,
"level": 1,
"question": "Write a python function to check the validity of a given phone number in the format of `+1 123 456 7890`.",
"split": "train"
} |
def pad_string(s, length, pad_char=' '):
if len(s) >= length:
return s
pad_length = length - len(s)
return s + pad_char * pad_length | simplelr_Filter | [
{
"content": "Question:\nCan you write a Python function that takes a string and a number as input and pads the string with a specified character until the total length of the string reaches the given number? If the string is already longer than the specified number, it should be returned unchanged. The functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4268,
"level": 1,
"question": "Can you write a Python function that takes a string and a number as input and pads the string with a specified character until the total length of the string reaches the given number? If the string is already longer than the specified number, it should... |
import re
def most_frequent_word(text):
text = text.lower()
text = re.sub(r'[^a-z]', ' ', text)
words = text.split()
if not words:
return ('', 0)
freq = {}
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
max_count = 0
... | simplelr_Evol | [
{
"content": "Question:\nFormulate a function that takes a string of text and returns the most frequently occurring word along with its frequency. If multiple words have the same highest frequency, return the one that appears first in the string. Ignore punctuation and ensure the function handles both uppercase... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4269,
"level": 1,
"question": "Formulate a function that takes a string of text and returns the most frequently occurring word along with its frequency. If multiple words have the same highest frequency, return the one that appears first in the string. Ignore punctuation and ensure ... |
def fibonacci_sequence(n):
if n <= 0:
return []
elif n == 1:
return [0]
else:
fibs = [0, 1]
for i in range(2, n):
next_num = fibs[i-1] + fibs[i-2]
fibs.append(next_num)
return fibs | simplelr_Filter | [
{
"content": "Question:\nIn Python, create a function called `fibonacci_sequence` that takes an integer `n` as input and returns a list containing the first `n` Fibonacci numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4270,
"level": 1,
"question": "In Python, create a function called `fibonacci_sequence` that takes an integer `n` as input and returns a list containing the first `n` Fibonacci numbers.",
"split": "train"
} |
def maximum_product_of_three(nums):
nums.sort()
n = len(nums)
candidate1 = nums[-1] * nums[-2] * nums[-3]
candidate2 = nums[0] * nums[1] * nums[-1]
return max(candidate1, candidate2) | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of integers `nums`, find and return the maximum product of any three integers in the list. The integers in the list can be positive, negative, or zero, and the length of the list will be at least three. You should aim to find an efficient solution that runs in linear time o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4271,
"level": 1,
"question": "Given a list of integers `nums`, find and return the maximum product of any three integers in the list. The integers in the list can be positive, negative, or zero, and the length of the list will be at least three. You should aim to find an efficient ... |
def process_booking_requests(events: dict, bookings: list) -> list:
results = []
for booking in bookings:
event = booking['event']
name = booking['name']
number = booking['number']
if event not in events:
status = 'invalid'
else:
available... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function in Python that simulates a ticket booking system for a series of events. The function should process a series of booking requests and return the status of each booking. Each event has a limited number of available tickets.\n\nHere are the detailed st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4272,
"level": 1,
"question": "You are required to write a function in Python that simulates a ticket booking system for a series of events. The function should process a series of booking requests and return the status of each booking. Each event has a limited number of available t... |
def generate_intervals(min_note, max_note):
notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
min_idx = notes.index(min_note)
max_idx = notes.index(max_note)
total_steps = (max_idx - min_idx) % 12
intervals = []
for step in range(total_steps + 1):
current_note = n... | simplelr_Filter | [
{
"content": "Question:\ndef generate_intervals(min_note, max_note):\n \"\"\"\n This function generates all possible intervals from min_note to max_note.\n Intervals are generated in half steps (1 semitone) and the output is a list of tuples.\n Each tuple contains the name of the interval and the nu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4273,
"level": 1,
"question": "def generate_intervals(min_note, max_note):\n \"\"\"\n This function generates all possible intervals from min_note to max_note.\n Intervals are generated in half steps (1 semitone) and the output is a list of tuples.\n Each tuple contains ... |
def add_positive_integers_without_plus_operator(a: int, b: int) -> int:
while b != 0:
sum_without_carry = a ^ b
carry = (a & b) << 1
a, b = sum_without_carry, carry
return a | simplelr_Data_Structure | [
{
"content": "Question:\nWrite a function `add_positive_integers_without_plus_operator(a: int, b: int) -> int` that adds two non-negative integers a and b without using the '+' operator or any other arithmetic operators such as '-', '*', or '/'.\n\n### Input\n* `a` and `b`: non-negative integers (0 <= a, b <= 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4274,
"level": 1,
"question": "Write a function `add_positive_integers_without_plus_operator(a: int, b: int) -> int` that adds two non-negative integers a and b without using the '+' operator or any other arithmetic operators such as '-', '*', or '/'.\n\n### Input\n* `a` and `b`: no... |
def findDuplicate(nums):
first_occurrence = {}
second_occurrence = {}
for index, num in enumerate(nums):
if num not in first_occurrence:
first_occurrence[num] = index
else:
if num not in second_occurrence:
second_occurrence[num] = index
if not seco... | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function `findDuplicate` that takes a list of integers as an input and returns the first duplicate number for which the second occurrence has the minimal index. If there is no such element, return -1. \n\n#### Example\nInput\n```\n[2, 3, 3, 1, 5, 2]\n```\nOutput\n```\n3\n```\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4275,
"level": 1,
"question": "Write a function `findDuplicate` that takes a list of integers as an input and returns the first duplicate number for which the second occurrence has the minimal index. If there is no such element, return -1. \n\n#### Example\nInput\n```\n[2, 3, 3, 1, ... |
from typing import List, Tuple
def filter_and_sort_students(student_records: List[Tuple[str, int]], threshold: int) -> List[str]:
# Filter the students with scores above the threshold
filtered = [(name, score) for name, score in student_records if score > threshold]
# Sort the filtered list by descending s... | simplelr_Algorithm | [
{
"content": "Question:\n### Sorting and Filtering Question\n\n**Scenario**: As a data analyst, you often need to process and analyze large datasets. One common task is filtering and sorting the data based on specific criteria. Suppose you have a list of student records where each record consists of the student... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4276,
"level": 1,
"question": "### Sorting and Filtering Question\n\n**Scenario**: As a data analyst, you often need to process and analyze large datasets. One common task is filtering and sorting the data based on specific criteria. Suppose you have a list of student records where ... |
def canPartition(n, arr):
total = sum(arr)
if total % 2 != 0:
return False
target = total // 2
dp = [False] * (target + 1)
dp[0] = True # Base case: sum 0 is always possible
for num in arr:
for s in range(target, num - 1, -1):
if dp[s - num]:
dp[... | simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, determine if it is possible to divide the list into two subsets such that the sum of the elements in both subsets is the same.\n\nExample 1:\nInput:\nn = 4\narr = [1, 5, 11, 5]\nOutput:\nTrue\nExplanation:\nThe list can be divided into the subsets [1, 5, 5] and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4277,
"level": 1,
"question": "Given a list of integers, determine if it is possible to divide the list into two subsets such that the sum of the elements in both subsets is the same.\n\nExample 1:\nInput:\nn = 4\narr = [1, 5, 11, 5]\nOutput:\nTrue\nExplanation:\nThe list can be div... |
def isPower(m, n):
if n == 1:
return m == 1
if m == 1:
return False
while m % n == 0:
m = m // n
if m == 1:
return True
return m == 1
| simplelr_Taco | [
{
"content": "Question:\nDetermine if a given number is a power of another number. Specifically, given two integers m and n, check whether m can be expressed as n raised to the power of some integer x (i.e., m = n^x, where x >= 1).\n\nExample 1:\nInput: m = 8, n = 2\nOutput: True\nExplanation: 8 can be expresse... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4278,
"level": 1,
"question": "Determine if a given number is a power of another number. Specifically, given two integers m and n, check whether m can be expressed as n raised to the power of some integer x (i.e., m = n^x, where x >= 1).\n\nExample 1:\nInput: m = 8, n = 2\nOutput: T... |
def is_rotation_string(s1, s2):
if len(s1) != len(s2):
return False
if len(s1) == 0:
return True
return s2 in (s1 + s1) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function called `is_rotation_string` that takes two strings as arguments. The function should determine if the second string is a rotation of the first string. For instance, \"waterbottle\" is a rotation of \"erbottlewat\". The function should return `True` if the second ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4279,
"level": 1,
"question": "Write a Python function called `is_rotation_string` that takes two strings as arguments. The function should determine if the second string is a rotation of the first string. For instance, \"waterbottle\" is a rotation of \"erbottlewat\". The function ... |
def next_bigger(num):
digits = list(str(num))
n = len(digits)
# Step 1: Find the first digit that can be swapped
i = n - 2
while i >= 0 and digits[i] >= digits[i + 1]:
i -= 1
if i == -1:
return -1 # No such number exists
# Step 2: Find the smallest digit great... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question:\n\n#### Scenario:\nYou are tasked with creating a function to find the next higher number with the same set of digits of a given number. This function can be particularly useful in combinatorial problems and number manipulation tasks where subsequent permutations are neces... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4280,
"level": 1,
"question": "### Question:\n\n#### Scenario:\nYou are tasked with creating a function to find the next higher number with the same set of digits of a given number. This function can be particularly useful in combinatorial problems and number manipulation tasks wher... |
def catalan_number(n):
if n == 0:
return 1
result = 1
for k in range(1, n + 1):
result = result * (n + k) // k
result = result // (n + 1)
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the nth Catalan number.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4281,
"level": 1,
"question": "Write a function to calculate the nth Catalan number.",
"split": "train"
} |
def rotate_matrix_90_degrees_clockwise(matrix):
n = len(matrix)
rotated = []
for j in range(n):
new_row = []
for i in range(n):
new_row.append(matrix[n - 1 - i][j])
rotated.append(new_row)
return rotated | simplelr_Evol | [
{
"content": "Question:\nCreate a Python function that rotates an NxN matrix 90 degrees clockwise. Your function should take as input a square matrix in the form of a list of lists and output a new matrix that has been rotated. For instance:\n\nmatrix = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4282,
"level": 1,
"question": "Create a Python function that rotates an NxN matrix 90 degrees clockwise. Your function should take as input a square matrix in the form of a list of lists and output a new matrix that has been rotated. For instance:\n\nmatrix = [[1, 2, 3],\n ... |
import matplotlib.pyplot as plt
def plot_fibonacci():
fib = [1, 1]
for i in range(2, 10):
fib.append(fib[i-1] + fib[i-2])
x = list(range(1, 11))
plt.plot(x, fib, marker='o')
plt.xlabel('Position')
plt.ylabel('Fibonacci Number')
plt.title('Fibonacci Sequence (First 10 Terms)')
pl... | simplelr_Package | [
{
"content": "Question:\n**Title: Calculating and Plotting Fibonacci Sequence Using Matplotlib**\n\n**Objective**: Learn to implement the Fibonacci sequence and visualize it using `matplotlib.pyplot` for plotting in Python.\n\n**Problem Statement**:\n\nWrite a function called `plot_fibonacci()` that generates t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4283,
"level": 1,
"question": "**Title: Calculating and Plotting Fibonacci Sequence Using Matplotlib**\n\n**Objective**: Learn to implement the Fibonacci sequence and visualize it using `matplotlib.pyplot` for plotting in Python.\n\n**Problem Statement**:\n\nWrite a function called ... |
def trapWater(heights):
if not heights:
return 0
left = 0
right = len(heights) - 1
max_left = 0
max_right = 0
result = 0
while left <= right:
if heights[left] <= heights[right]:
if heights[left] >= max_left:
max_left = heights[left]
els... | simplelr_Taco | [
{
"content": "Question:\nYou are given an array of non-negative integers representing the heights of walls at different positions. Each unit width section of the wall can trap some amount of rainwater. You need to write a function that calculates the maximum amount of rainwater that can be trapped between the w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4284,
"level": 1,
"question": "You are given an array of non-negative integers representing the heights of walls at different positions. Each unit width section of the wall can trap some amount of rainwater. You need to write a function that calculates the maximum amount of rainwate... |
def length_of_LIS(arr):
if not arr:
return 0
dp = [1] * len(arr)
for i in range(len(arr)):
for j in range(i):
if arr[i] > arr[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp) if dp else 0 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers as input and returns the length of the longest increasing subsequence (LIS) in the array. An increasing subsequence is a sequence of numbers such that each number is strictly larger than the previous number.\nAnswer:\nLet's think step by... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4285,
"level": 1,
"question": "Create a function that takes an array of integers as input and returns the length of the longest increasing subsequence (LIS) in the array. An increasing subsequence is a sequence of numbers such that each number is strictly larger than the previous nu... |
def absolute_difference(nums, k):
sorted_nums = sorted(nums)
sum_min = sum(sorted_nums[:k])
sum_max = sum(sorted_nums[-k:])
return abs(sum_max - sum_min) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums` and an integer `k`. You need to find the absolute difference between the sum of the maximum `k` elements and the sum of the minimum `k` elements from the array. Return this absolute difference.\nAnswer:\nLet's think step by step.\n",
"role":... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4286,
"level": 1,
"question": "You are given an array of integers `nums` and an integer `k`. You need to find the absolute difference between the sum of the maximum `k` elements and the sum of the minimum `k` elements from the array. Return this absolute difference.",
"split": "tr... |
def two_sum(arr, target):
seen = {}
for index, num in enumerate(arr):
complement = target - num
if complement in seen:
return [seen[complement], index]
seen[num] = index
return [] | simplelr_Filter | [
{
"content": "Question:\nHere's a coding problem:\n\nYou are given an array of integers `arr` and a target integer `target`. Your function should return the indices of the two numbers in the array that add up to the `target`. You may assume that each input would have exactly one solution, and you may not use th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4287,
"level": 1,
"question": "Here's a coding problem:\n\nYou are given an array of integers `arr` and a target integer `target`. Your function should return the indices of the two numbers in the array that add up to the `target`. You may assume that each input would have exactly o... |
def min_add_to_make_valid(s):
left_add = 0
balance = 0
for c in s:
if c == '(':
balance += 1
else:
balance -= 1
if balance < 0:
left_add += 1
balance = 0
right_add = balance
return left_add + right_add | simplelr_Apps | [
{
"content": "Question:\nGiven a string that consists of only '(' and ')', your task is to determine the minimum number of parentheses that need to be added to make the string valid. A string is considered valid if it is empty or it can be written as AB (A and B are valid strings) or (A) (A is a valid string). ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4288,
"level": 1,
"question": "Given a string that consists of only '(' and ')', your task is to determine the minimum number of parentheses that need to be added to make the string valid. A string is considered valid if it is empty or it can be written as AB (A and B are valid stri... |
def check_non_negative(lst):
"""
This function checks if all elements in the list are non-negative.
Args:
lst (list): A list of integers.
Returns:
bool: True if all elements are non-negative, False otherwise.
"""
return all(num >= 0 for num in lst) | simplelr_Filter | [
{
"content": "Question:\nGiven a list of integers, write a function that returns True if all elements in the list are greater than or equal to 0, and False otherwise.\n\nExample:\nInput: [1, 2, 3, 4, 5]\nOutput: True\n\nInput: [-1, 2, 3, 4, 5]\nOutput: False\n\nHere is the Python code for this problem:\n```pyth... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4289,
"level": 1,
"question": "Given a list of integers, write a function that returns True if all elements in the list are greater than or equal to 0, and False otherwise.\n\nExample:\nInput: [1, 2, 3, 4, 5]\nOutput: True\n\nInput: [-1, 2, 3, 4, 5]\nOutput: False\n\nHere is the Pyt... |
def larger_than_mean(lst):
if not lst:
return []
mean = sum(lst) / len(lst)
return [x for x in lst if x > mean]
| simplelr_Taco | [
{
"content": "Question:\nWrite a Python function that takes in a list of integers and returns a new list containing only the elements that are larger than the arithmetic mean of the input list. The arithmetic mean is calculated as the sum of the elements divided by the number of elements.\n\n### Examples\n\n```... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4290,
"level": 1,
"question": "Write a Python function that takes in a list of integers and returns a new list containing only the elements that are larger than the arithmetic mean of the input list. The arithmetic mean is calculated as the sum of the elements divided by the number ... |
def can_fit_logos(total_length, number, width):
return total_length == number * width | simplelr_Apps | [
{
"content": "Question:\nYou are designing a digital banner for an upcoming event and want the banner's total length to be an exact multiple of the logo's width. Each logo has the same width, but you are flexible with the total length of the banner.\n\nCreate a function, `can_fit_logos()`, that determines if a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4291,
"level": 1,
"question": "You are designing a digital banner for an upcoming event and want the banner's total length to be an exact multiple of the logo's width. Each logo has the same width, but you are flexible with the total length of the banner.\n\nCreate a function, `can_... |
import math
def count_unique_paths(m: int, n: int) -> int:
return math.comb(m + n - 2, m - 1) | simplelr_Evol | [
{
"content": "Question:\nGiven a rectangular grid of m rows and n columns, write a function that counts the number of unique paths from the top-left corner to the bottom-right corner. The only valid movements are to the right or down. You may assume m and n are positive integers.\n\nFunction signature:\n```pyth... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4292,
"level": 1,
"question": "Given a rectangular grid of m rows and n columns, write a function that counts the number of unique paths from the top-left corner to the bottom-right corner. The only valid movements are to the right or down. You may assume m and n are positive intege... |
from collections import Counter
def is_permutation(str1: str, str2: str) -> bool:
if len(str1) != len(str2):
return False
return Counter(str1) == Counter(str2) | simplelr_Algorithm | [
{
"content": "Question:\n### String Permutation Detector\n\n### Problem Description:\nYou are required to write a function that determines whether two given strings are permutations of each other. A permutation of a string is another string that contains the same characters, only the order of characters can be ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4293,
"level": 1,
"question": "### String Permutation Detector\n\n### Problem Description:\nYou are required to write a function that determines whether two given strings are permutations of each other. A permutation of a string is another string that contains the same characters, o... |
def reverse_string(s):
if len(s) <= 1:
return s
else:
return reverse_string(s[1:]) + s[0] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse a string. In your solution, avoid using slicing or built-in functions to reverse a string. Instead, use recursion.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4294,
"level": 1,
"question": "Write a python function to reverse a string. In your solution, avoid using slicing or built-in functions to reverse a string. Instead, use recursion.",
"split": "train"
} |
def length_of_longest_substring(s):
char_index = dict()
left = 0
max_length = 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 +... | simplelr_Filter | [
{
"content": "Question:\nYou are given a string, and you need to find the length of the longest substring without repeating characters.\n\nExample:\n\n Input: \"abcabcbb\"\n Output: 3 (\"abc\")\n Input: \"bbbbb\"\n Output: 1 (\"b\")\n\n\n\nCan you provide a Python code solution for this problem using a sliding ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4295,
"level": 1,
"question": "You are given a string, and you need to find the length of the longest substring without repeating characters.\n\nExample:\n\n Input: \"abcabcbb\"\n Output: 3 (\"abc\")\n Input: \"bbbbb\"\n Output: 1 (\"b\")\n\n\n\nCan you provide a Python code solutio... |
import pandas as pd
def create_customized_plot(df):
# Import required libraries
import seaborn.objects as so
import matplotlib
matplotlib.use('Agg') # Ensure SVG output even in non-interactive environments
# Configure plot theme
so.Plot.config.theme["axes.facecolor"] = "white"
from se... | simplelr_Docs | [
{
"content": "Question:\n#### Objective \nDemonstrate proficiency in configuring plot themes and display settings using the seaborn.objects (`so`) module.\n\n#### Problem Statement\nYou are provided with a dataset and need to visualize it using Seaborn. Your task is to create a seaborn plot with specific theme ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4296,
"level": 1,
"question": "#### Objective \nDemonstrate proficiency in configuring plot themes and display settings using the seaborn.objects (`so`) module.\n\n#### Problem Statement\nYou are provided with a dataset and need to visualize it using Seaborn. Your task is to create ... |
def count_vowels_and_consonants(input_string: str) -> tuple[int, int]:
vowels = {'a', 'e', 'i', 'o', 'u'}
vowels_count = 0
consonants_count = 0
for char in input_string:
if char.isalpha():
if char.lower() in vowels:
vowels_count += 1
else:
... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that analyzes a given string and returns the number of vowels and consonants in the string.\n\n## Description\nA vowel is defined as any of the characters: 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'. Consonants are characters that are letters but are not vowels.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4297,
"level": 1,
"question": "Write a function that analyzes a given string and returns the number of vowels and consonants in the string.\n\n## Description\nA vowel is defined as any of the characters: 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'. Consonants are characters tha... |
def generate_fibonacci_sum(n):
if not isinstance(n, int) or n < 0:
return 0
a, b = 0, 1
total = 0
for _ in range(n):
total += a
a, b = b, a + b
return total | simplelr_Package | [
{
"content": "Question:\nDesign a function named `generate_fibonacci_sum(n)` that takes an integer `n` as input and returns the sum of the first `n` Fibonacci numbers. The Fibonacci sequence is defined as follows:\n\n1. The first two Fibonacci numbers are 0 and 1.\n2. Each subsequent Fibonacci number is the sum... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4298,
"level": 1,
"question": "Design a function named `generate_fibonacci_sum(n)` that takes an integer `n` as input and returns the sum of the first `n` Fibonacci numbers. The Fibonacci sequence is defined as follows:\n\n1. The first two Fibonacci numbers are 0 and 1.\n2. Each sub... |
def second_largest(lst):
unique = list(set(lst))
if len(unique) < 2:
return None
unique_sorted = sorted(unique)
return unique_sorted[-2] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the second largest element in a list. If the list is empty or only contains one unique element, the function should return `None`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4299,
"level": 1,
"question": "Write a python function to find the second largest element in a list. If the list is empty or only contains one unique element, the function should return `None`.",
"split": "train"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.