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 rearrange_sentence(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
words = s.split()
vowel_list = []
consonant_list = []
for word in words:
if word[0] in vowels:
vowel_list.append(word)
else:
consonant_list.append(word)
return ' '.join(vowel_list + consonant_li... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` representing a sentence. The sentence consists of words separated by spaces. Each word contains only lowercase letters. A **vowel** is any of the letters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. A **consonant** is any letter that is not a vowel. \n\nWrite a func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 200,
"level": 1,
"question": "You are given a string `s` representing a sentence. The sentence consists of words separated by spaces. Each word contains only lowercase letters. A **vowel** is any of the letters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. A **consonant** is any letter tha... |
def group_indices(vector):
groups = {}
for index, value in enumerate(vector):
if value not in groups:
groups[value] = []
groups[value].append(index)
return list(groups.values()) | simplelr_Filter | [
{
"content": "Question:\nI have a vector of integers and I wish to create a variable, let's call it \"groups\", which would contain a number of vectors, each of which contains the indices of the original vector which have a certain property. \n\nFor example, given the vector [1, 2, 2, 4, 4, 4] of integers, I wi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 201,
"level": 1,
"question": "I have a vector of integers and I wish to create a variable, let's call it \"groups\", which would contain a number of vectors, each of which contains the indices of the original vector which have a certain property. \n\nFor example, given the vector [1... |
def count_upper_and_lower(s):
uppercase_count = 0
lowercase_count = 0
for char in s:
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
return (uppercase_count, lowercase_count) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a single string as an input and returns the number of uppercase and lowercase letters in the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 202,
"level": 1,
"question": "Create a function that takes a single string as an input and returns the number of uppercase and lowercase letters in the string.",
"split": "train"
} |
import math
def sqrt_list(lst):
return [math.sqrt(x) for x in lst] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that converts a list of integers to a list of their square roots. For example, if you call the function with a list `[1, 4, 16]`, it should return `[1.0, 2.0, 4.0]`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 203,
"level": 1,
"question": "Create a function that converts a list of integers to a list of their square roots. For example, if you call the function with a list `[1, 4, 16]`, it should return `[1.0, 2.0, 4.0]`.",
"split": "train"
} |
from typing import Any, List
def find_duplicates(dataset: List[Any]) -> List[Any]:
elements_info = {}
for index, element in enumerate(dataset):
if element in elements_info:
current_count, first_index = elements_info[element]
elements_info[element] = (current_count + 1, first_ind... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are working on a project that involves processing large datasets. One of the tasks requires you to identify duplicate entries in an efficient manner. To achieve this, you need to write a function that can detect and return all duplicate elements in the dataset.\n\n### ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 204,
"level": 1,
"question": "### Scenario\nYou are working on a project that involves processing large datasets. One of the tasks requires you to identify duplicate entries in an efficient manner. To achieve this, you need to write a function that can detect and return all duplicat... |
def reservoir_water_balance(
inflow: float,
outflow: float,
precipitation: float,
evaporation: float
) -> float:
# Check if any parameter is negative
if inflow < 0 or outflow < 0 or precipitation < 0 or evaporation < 0:
raise ValueError("All parameters must be non-negative.")
# ... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Problem: Reservoir Water Balance Calculation\n\n**Context**: You have been hired by a water resources management company. They frequently need to calculate the water balance of a reservoir for operational management and planning. The water balance calculation considers inflow... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 205,
"level": 1,
"question": "### Coding Problem: Reservoir Water Balance Calculation\n\n**Context**: You have been hired by a water resources management company. They frequently need to calculate the water balance of a reservoir for operational management and planning. The water ba... |
def does_subsequence_sum_exist(arr, x):
if x == 0:
return True
possible_sums = {0}
for num in arr:
new_sums = set()
for s in possible_sums:
new_sum = s + num
if new_sum == x:
return True
if new_sum not in possible_sums:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` of size `n` and an integer `x`. Your task is to determine if there exists a **subsequence** of `arr` such that the sum of its elements is exactly `x`. A subsequence is a sequence that can be derived from another sequence by deleting some or no el... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 206,
"level": 1,
"question": "You are given an array of integers `arr` of size `n` and an integer `x`. Your task is to determine if there exists a **subsequence** of `arr` such that the sum of its elements is exactly `x`. A subsequence is a sequence that can be derived from another ... |
def max_subarray_sum(arr):
if not arr:
return 0
max_current = max_global = arr[0]
for num in arr[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to solve the following problem: For a given array, find and return the maximum sum of all possible subarrays (repeating of elements allowed).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 207,
"level": 1,
"question": "Write a python function to solve the following problem: For a given array, find and return the maximum sum of all possible subarrays (repeating of elements allowed).",
"split": "train"
} |
def remove_duplicates(input_list):
seen = set()
unique = []
for item in input_list:
if item not in seen:
unique.append(item)
seen.add(item)
return unique | simplelr_Filter | [
{
"content": "Question:\n# Define a function `remove_duplicates` that takes a list of elements as input and returns a new list that contains only the unique elements from the original list. The function should preserve the original order of elements.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 208,
"level": 1,
"question": "# Define a function `remove_duplicates` that takes a list of elements as input and returns a new list that contains only the unique elements from the original list. The function should preserve the original order of elements.",
"split": "train"
} |
from collections import Counter
def min_window(s, t):
if not t:
return ""
if len(t) > len(s):
return ""
t_count = Counter(t)
required = len(t_count)
s_count = {}
have = 0
left = 0
min_len = float('inf')
min_window = ""
for right in range(len(s)):
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` and a string `t`, your task is to find the minimum window in `s` which contains all the characters from `t`. If such a window does not exist, return an empty string. If there are multiple minimal windows, return the one which starts first. \n\nNote that when the windo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 209,
"level": 1,
"question": "Given a string `s` and a string `t`, your task is to find the minimum window in `s` which contains all the characters from `t`. If such a window does not exist, return an empty string. If there are multiple minimal windows, return the one which starts f... |
def sort_words_characters(s):
return ' '.join(''.join(sorted(word)) for word in s.split()) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string and returns a new string where each word's characters are sorted in alphabetical order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 210,
"level": 1,
"question": "Create a function that takes a string and returns a new string where each word's characters are sorted in alphabetical order.",
"split": "train"
} |
def firstUniqChar(s):
seen = set()
unique = set()
first_occurrence = {}
for i, c in enumerate(s):
if c not in seen:
seen.add(c)
unique.add(c)
first_occurrence[c] = i
else:
if c in unique:
unique.remove(c)
if no... | simplelr_Filter | [
{
"content": "Question:\nThis is supposed to be a simple coding problem, but I'm finding it quite challenging.\n\nThe problem is this:\n\n**Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.**\n\nFor example:\n\n* **\"leetcode\"** should return **... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 211,
"level": 1,
"question": "This is supposed to be a simple coding problem, but I'm finding it quite challenging.\n\nThe problem is this:\n\n**Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.**\n\nFor example:\n\n* ... |
import bisect
def flag_fraudulent_transactions(
transactions: list[tuple[str, int]],
window: int
) -> list[str]:
id_map = {}
flagged_ids = set()
for id, t in transactions:
if id in flagged_ids:
id_map[id].append(t)
continue
if id not in id_map:
... | simplelr_Algorithm | [
{
"content": "Question:\n```markdown\n### Coding Assessment Question\n\n#### Scenario:\nYou're working on analyzing a series of transactions for potential fraud. Each transaction is recorded with a unique ID, a timestamp, and an amount. Your task is to identify if any transactions are repeated within a specifie... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 212,
"level": 1,
"question": "```markdown\n### Coding Assessment Question\n\n#### Scenario:\nYou're working on analyzing a series of transactions for potential fraud. Each transaction is recorded with a unique ID, a timestamp, and an amount. Your task is to identify if any transacti... |
def fizzbuzz(n):
s = ''
if n % 3 == 0:
s += 'Fizz'
if n % 5 == 0:
s += 'Buzz'
return s if s else n | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to return \"Fizz\" if the number is divisible by 3, \"Buzz\" if it is divisible by 5, and \"FizzBuzz\" if it is divisible by both 3 and 5. If the number is not divisible by either, return the number itself.\nAnswer:\nLet's think step by step.\n",
"role": "use... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 213,
"level": 1,
"question": "Write a python function to return \"Fizz\" if the number is divisible by 3, \"Buzz\" if it is divisible by 5, and \"FizzBuzz\" if it is divisible by both 3 and 5. If the number is not divisible by either, return the number itself.",
"split": "train"
} |
def reverse_strings_keep_last_occurrence(lst):
result = {}
for word in lst:
reversed_word = word[::-1]
result[word] = reversed_word
return result | simplelr_Evol | [
{
"content": "Question:\nWrite a function in Python that takes a list of strings and returns a dictionary where each key is a string from the list, and the corresponding value is the string reversed. If the input list contains duplicate strings, retain only the last occurrence of each string in the dictionary. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 214,
"level": 1,
"question": "Write a function in Python that takes a list of strings and returns a dictionary where each key is a string from the list, and the corresponding value is the string reversed. If the input list contains duplicate strings, retain only the last occurrence ... |
def process_sales(sales_list):
author_sales = {}
for data in sales_list:
author, sale = data.split(',')
sale = int(sale)
author_sales[author] = author_sales.get(author, 0) + sale
author_list = list(author_sales.items())
sorted_authors = sorted(author_list, key=lambda x: (-x[1], x... | simplelr_Taco | [
{
"content": "Question:\nCreate a function that takes an array of strings as input and returns an array of strings where each string contains the names and total sale of all authors ranked by their total sales in descending order. If two authors have the same total sale, order them alphabetically by their names... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 215,
"level": 1,
"question": "Create a function that takes an array of strings as input and returns an array of strings where each string contains the names and total sale of all authors ranked by their total sales in descending order. If two authors have the same total sale, order ... |
import math
def cosine_similarity(vec1: list[float], vec2: list[float]) -> float:
dot = 0.0
mag_a_sq = 0.0
mag_b_sq = 0.0
for a, b in zip(vec1, vec2):
dot += a * b
mag_a_sq += a ** 2
mag_b_sq += b ** 2
mag_a = math.sqrt(mag_a_sq)
mag_b = math.sqrt(mag_b_sq)
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Cosine Similarity for Document Analysis\n\nIn data mining and natural language processing, measuring the similarity between texts is a fundamental task. A common technique to quantify this similarity is by treating texts as vectors of their word occurrences and using cosine similari... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 216,
"level": 1,
"question": "### Cosine Similarity for Document Analysis\n\nIn data mining and natural language processing, measuring the similarity between texts is a fundamental task. A common technique to quantify this similarity is by treating texts as vectors of their word occ... |
def canFormPalindrome(s: str, k: int) -> bool:
from collections import Counter
count = Counter(s)
O_initial = sum(1 for v in count.values() if v % 2 != 0)
m = len(s) - k
if m < 0:
return False
required_odds = m % 2
min_steps = abs(O_initial - required_odds)
if... | simplelr_Taco | [
{
"content": "Question:\nYou are given a string s that consists of lowercase English letters and an integer k. Your task is to remove exactly k characters from the string such that the remaining string can be rearranged to form a palindrome. Return true if it's possible to do so, and false otherwise.\n\nExample... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 217,
"level": 1,
"question": "You are given a string s that consists of lowercase English letters and an integer k. Your task is to remove exactly k characters from the string such that the remaining string can be rearranged to form a palindrome. Return true if it's possible to do s... |
def int_to_hex(n):
return hex(n) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that converts a given integer to its hexadecimal representation. The function should return a string that starts with \"0x\" followed by the hexadecimal value of the integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 218,
"level": 1,
"question": "Create a function that converts a given integer to its hexadecimal representation. The function should return a string that starts with \"0x\" followed by the hexadecimal value of the integer.",
"split": "train"
} |
def command_parser(commands):
numbers = []
for cmd in commands:
parts = cmd.split()
action = parts[0]
if action == 'append':
x = int(parts[1])
numbers.append(x)
elif action == 'remove':
x = int(parts[1])
if x in numbers:
... | simplelr_Taco | [
{
"content": "Question:\nFunction Command Parser\n\nWrite a Python function `command_parser` that processes a sequence of commands provided in a list of strings. Each command performs a specific action on a list of integers. The function should start with an empty list and update it based on the commands.\n\nTh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 219,
"level": 1,
"question": "Function Command Parser\n\nWrite a Python function `command_parser` that processes a sequence of commands provided in a list of strings. Each command performs a specific action on a list of integers. The function should start with an empty list and upda... |
def transform_string(s):
result = []
for c in s:
if c.islower():
if c == 'z':
result.append('a')
else:
result.append(chr(ord(c) + 1))
elif c.isupper():
if c == 'Z':
result.append('A')
else:
... | simplelr_Evol | [
{
"content": "Question:\nGenerate a function that takes a string consisting of ASCII characters and returns a transformed version where each letter is replaced by the next one in the alphabet (with 'z' going to 'a'), digits (0-9) are replaced by their complement to 9 (e.g., '0' with '9', '1' with '8', etc.), an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 220,
"level": 1,
"question": "Generate a function that takes a string consisting of ASCII characters and returns a transformed version where each letter is replaced by the next one in the alphabet (with 'z' going to 'a'), digits (0-9) are replaced by their complement to 9 (e.g., '0'... |
def is_sorted_ascending(lst):
int_list = []
for item in lst:
try:
converted = int(item)
except (ValueError, TypeError):
return False
int_list.append(converted)
for i in range(len(int_list) - 1):
if int_list[i] > int_list[i + 1]:
return Fals... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if a given list of integers is sorted in ascending order. If the list is sorted, return `True`; otherwise, return `False`. The function should also handle any exceptions that might occur when converting strings to integers.\nAnswer:\nLet's think step by ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 221,
"level": 1,
"question": "Create a function that checks if a given list of integers is sorted in ascending order. If the list is sorted, return `True`; otherwise, return `False`. The function should also handle any exceptions that might occur when converting strings to integers.... |
def count_pairs(nums: list[int], target: int) -> int:
from collections import defaultdict
freq = defaultdict(int)
for num in nums:
freq[num] += 1
seen_pairs = set()
count = 0
for num in nums:
complement = target - num
if complement in freq:
pair = (min(num, co... | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function that takes two parameters: a list of integers and a target integer. The function should return the number of distinct pairs in the list that sum up to the target integer. Each pair should only be counted once, and the order of elements in the pairs does not matter.\n\nE... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 222,
"level": 1,
"question": "Write a function that takes two parameters: a list of integers and a target integer. The function should return the number of distinct pairs in the list that sum up to the target integer. Each pair should only be counted once, and the order of elements ... |
from typing import List, Tuple
def filter_logs(logs: List[Tuple[str, str, str]], level: str, start_time: str, end_time: str) -> List[str]:
result = []
for log in logs:
timestamp, log_level, message = log
if log_level == level and start_time <= timestamp <= end_time:
result.append(me... | simplelr_Taco | [
{
"content": "Question:\nKaori is a software developer who needs to write a log managing module for her application. The logs are categorized into three levels: INFO, WARNING, and ERROR. Each log entry has a timestamp, level, and message.\n\nWrite a function `filter_logs(logs: List[Tuple[str, str, str]], level:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 223,
"level": 1,
"question": "Kaori is a software developer who needs to write a log managing module for her application. The logs are categorized into three levels: INFO, WARNING, and ERROR. Each log entry has a timestamp, level, and message.\n\nWrite a function `filter_logs(logs: ... |
def longest_common_prefix(strings: list[str]) -> str:
if not strings:
return ""
min_len = min(len(s) for s in strings)
for i in range(min_len):
current_char = strings[0][i]
for s in strings[1:]:
if s[i] != current_char:
return strings[0][:i]
return str... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nYou are developing an algorithm for a recommendation system to find the most common prefixes shared among a list of strings, which will help in auto-completion features. The algorithm should find the longest common prefix (LCP) among a list of strings provided.\n\n### Objec... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 224,
"level": 1,
"question": "### Context\nYou are developing an algorithm for a recommendation system to find the most common prefixes shared among a list of strings, which will help in auto-completion features. The algorithm should find the longest common prefix (LCP) among a list... |
def word_pattern(pattern: str, text: str) -> bool:
words = text.split()
if len(pattern) != len(words):
return False
pattern_to_word = {}
word_to_pattern = {}
for i in range(len(pattern)):
c = pattern[i]
word = words[i]
if c in pattern_to_word:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Pattern Matching Bijection\n\nYou are given a pattern string and a text string containing multiple words separated by spaces. Your task is to implement a function `word_pattern(pattern: str, text: str) -> bool` that determines if the text string follows the same pattern as... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 225,
"level": 1,
"question": "### Question: Pattern Matching Bijection\n\nYou are given a pattern string and a text string containing multiple words separated by spaces. Your task is to implement a function `word_pattern(pattern: str, text: str) -> bool` that determines if the text ... |
import os
def normalize_path(file_path: str) -> str:
expanded = os.path.expanduser(file_path)
absolute = os.path.abspath(expanded)
return absolute | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nYou are developing a file management application that needs to handle file paths provided by users reliably. To ensure that file operations such as reading and writing work correctly, you need to convert any user-provided file path, which could be in a relative format or ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 226,
"level": 1,
"question": "#### Scenario\nYou are developing a file management application that needs to handle file paths provided by users reliably. To ensure that file operations such as reading and writing work correctly, you need to convert any user-provided file path, which... |
from collections import defaultdict
def length_of_longest_substring_k_distinct(s, k):
if k == 0:
return 0
unique_count = len(set(s))
if k >= unique_count:
return len(s)
freq = defaultdict(int)
max_len = 0
left = 0
for right in range(len(s)):
char = s[right]... | simplelr_Apps | [
{
"content": "Question:\nYou are given a string `s` which consists of lowercase English letters, and an integer `k`. Your task is to find the length of the longest substring that contains at most `k` distinct characters. If `k` is greater than or equal to the length of `s`, return the length of `s`.\n\nFor exam... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 227,
"level": 1,
"question": "You are given a string `s` which consists of lowercase English letters, and an integer `k`. Your task is to find the length of the longest substring that contains at most `k` distinct characters. If `k` is greater than or equal to the length of `s`, ret... |
def max_subarray_sum(arr, n):
max_so_far = arr[0]
current_max = arr[0]
for i in range(1, n):
current_max = max(arr[i], current_max + arr[i])
if current_max > max_so_far:
max_so_far = current_max
return max_so_far | simplelr_Filter | [
{
"content": "Question:\nThis is a question we\n\nwere asked in an online\n\ninterview :\n\nGiven an array of positive\n\nintegers\n**arr[]**, with the size **n**,\n\nfind the maximum sum of\n\ncontiguous subarray\n\n(maximum non-empty sum\n\nachieved using elements of the\n\narray).\n\n**Example:**\n\n**arr[] ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 228,
"level": 1,
"question": "This is a question we\n\nwere asked in an online\n\ninterview :\n\nGiven an array of positive\n\nintegers\n**arr[]**, with the size **n**,\n\nfind the maximum sum of\n\ncontiguous subarray\n\n(maximum non-empty sum\n\nachieved using elements of the\n\na... |
def find_team_leader(productivity_scores: list[int]) -> int:
max_score = productivity_scores[0]
max_index = 0
for index, score in enumerate(productivity_scores):
if score > max_score:
max_score = score
max_index = index
return max_index | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given a list of employees and their respective productivity scores. Each productivity score is an integer, and it represents the efficiency of the employee. The company plans to assign a team leader based on these scores. The team leader must be the empl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 229,
"level": 1,
"question": "### Problem Statement\n\nYou are given a list of employees and their respective productivity scores. Each productivity score is an integer, and it represents the efficiency of the employee. The company plans to assign a team leader based on these scores... |
import re
def validate_mac_addresses(mac_list):
pattern = r'^([0-9A-F]{2}[:\-]){5}[0-9A-F]{2}$|^[0-9A-F]{12}$'
valid_macs = []
for mac in mac_list:
mac_clean = mac.strip()
if re.fullmatch(pattern, mac_clean, flags=re.IGNORECASE):
valid_macs.append(mac_clean)
return valid_mac... | simplelr_Filter | [
{
"content": "Question:\nImplement a Python function that validates a list of MAC (Media Access Control) addresses utilizing regex patterns. This function should return a list of valid MAC addresses while filtering out the invalid ones.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 230,
"level": 1,
"question": "Implement a Python function that validates a list of MAC (Media Access Control) addresses utilizing regex patterns. This function should return a list of valid MAC addresses while filtering out the invalid ones.",
"split": "train"
} |
def product_of_pairs(nums):
result = []
for i in range(0, len(nums), 2):
if i + 1 < len(nums):
product = nums[i] * nums[i + 1]
else:
product = nums[i] * 2
result.append(product)
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a list where each element is the product of pairs of integers from the input list. If the input list has an odd number of elements, the last remaining element should be doubled in the output list.\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 231,
"level": 1,
"question": "Create a function that takes a list of integers and returns a list where each element is the product of pairs of integers from the input list. If the input list has an odd number of elements, the last remaining element should be doubled in the output li... |
def count_partitions(n: int) -> int:
dp = [0] * (n + 1)
dp[0] = 1 # Base case: one way to partition 0
for j in range(1, n + 1):
for i in range(j, n + 1):
dp[i] += dp[i - j]
return dp[n] | simplelr_Data_Structure | [
{
"content": "Question:\n**Problem Statement**:\n\nYour task is to implement a function that counts the number of ways to partition a given positive integer. A partition of a positive integer is a way of writing it as a sum of positive integers. For instance, the partitions of 4 are `4, 3+1, 2+2, 2+1+1, 1+1+1+1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 232,
"level": 1,
"question": "**Problem Statement**:\n\nYour task is to implement a function that counts the number of ways to partition a given positive integer. A partition of a positive integer is a way of writing it as a sum of positive integers. For instance, the partitions of ... |
def sum_of_digits(number):
number = abs(number)
return sum(int(digit) for digit in str(number)) | simplelr_Filter | [
{
"content": "Question:\nProvide a Python code snippet that creates a function to calculate the sum of the digits of a given number.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 233,
"level": 1,
"question": "Provide a Python code snippet that creates a function to calculate the sum of the digits of a given number.",
"split": "train"
} |
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the factorial of a number using recursion. The function should be able to handle large numbers, and it should return the result as a `BigInteger`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 234,
"level": 1,
"question": "Write a function to calculate the factorial of a number using recursion. The function should be able to handle large numbers, and it should return the result as a `BigInteger`.",
"split": "train"
} |
def letter_count(s):
counts = {}
for char in s:
if char.isalpha():
lower_char = char.lower()
counts[lower_char] = counts.get(lower_char, 0) + 1
return counts | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates and returns the number of times each unique letter (ignoring case) appears in a given string. The function should return a dictionary where the keys are unique letters and the values are the counts of those letters. For instance, if the input is \"Hello... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 235,
"level": 1,
"question": "Create a function that calculates and returns the number of times each unique letter (ignoring case) appears in a given string. The function should return a dictionary where the keys are unique letters and the values are the counts of those letters. For... |
def reverse_string_to_list(s):
chars = list(s)
chars.reverse()
return chars | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that converts a string to a list of characters, reverses the list, and then returns it. Implement this in Python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 236,
"level": 1,
"question": "Create a function that converts a string to a list of characters, reverses the list, and then returns it. Implement this in Python.",
"split": "train"
} |
def get_top_customers(orders: list, n: int) -> list:
customer_totals = {}
for order in orders:
customer = order['customer']
for item in order['items']:
amount = item['quantity'] * item['price']
if customer in customer_totals:
customer_totals[customer] += a... | simplelr_Package | [
{
"content": "Question:\nYou are given a list of dictionaries representing orders from a food delivery service. Each dictionary contains the keys 'order_id', 'customer', and 'items', where 'items' is a list of dictionaries. Each item dictionary consists of 'item_name', 'quantity', and 'price'. The task is to wr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 237,
"level": 1,
"question": "You are given a list of dictionaries representing orders from a food delivery service. Each dictionary contains the keys 'order_id', 'customer', and 'items', where 'items' is a list of dictionaries. Each item dictionary consists of 'item_name', 'quantit... |
import bisect
def kth_smallest_element(mat, k):
if not mat or not mat[0]:
return None # Handle empty matrix case
rows = len(mat)
cols = len(mat[0])
low = mat[0][0]
high = mat[-1][-1]
while low < high:
mid = (low + high) // 2
count = 0
for... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a matrix `mat` of integers, where each row is sorted in ascending order and each column is sorted in ascending order, find the k-th smallest element in the matrix. For example, if the matrix is:\n\n```\nmat = [\n [1, 5, 9],\n [10, 11, 13],\n [12, 13, 15]\n]\n```\nand `k =... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 238,
"level": 1,
"question": "Given a matrix `mat` of integers, where each row is sorted in ascending order and each column is sorted in ascending order, find the k-th smallest element in the matrix. For example, if the matrix is:\n\n```\nmat = [\n [1, 5, 9],\n [10, 11, 13],\n... |
from collections import Counter
def first_non_repeating_char_index(s):
freq = Counter(s)
for index, char in enumerate(s):
if freq[char] == 1:
return index
return -1
| simplelr_Taco | [
{
"content": "Question:\nGiven a string of lowercase letters, write a function that finds the first non-repeating character in it and returns its index. If no non-repeating character exists, return -1. \n\nFor example:\n\n```python\nfirst_non_repeating_char_index('leetcode') => 0\nfirst_non_repeating_char_index... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 239,
"level": 1,
"question": "Given a string of lowercase letters, write a function that finds the first non-repeating character in it and returns its index. If no non-repeating character exists, return -1. \n\nFor example:\n\n```python\nfirst_non_repeating_char_index('leetcode') =>... |
def elementwise_xor(arr1, arr2):
min_len = min(len(arr1), len(arr2))
result = []
for i in range(min_len):
result.append(arr1[i] ^ arr2[i])
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two arrays as input and returns their element-wise bitwise XOR result. The function should be able to handle arrays of different lengths, in which case the XOR operation will only be performed up to the length of the shorter array.\nAnswer:\nLet's think step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 240,
"level": 1,
"question": "Create a function that takes two arrays as input and returns their element-wise bitwise XOR result. The function should be able to handle arrays of different lengths, in which case the XOR operation will only be performed up to the length of the shorter... |
def is_valid_dosage(schedule: list[tuple[int, int]], max_daily_dosage: int, min_interval: int) -> bool:
# Calculate the total dosage
total_dosage = sum(amount for time, amount in schedule)
if total_dosage > max_daily_dosage:
return False
# Sort the schedule by the timing of each dose
so... | simplelr_Algorithm | [
{
"content": "Question:\n### Medication Dosage Schedule Validator\n\nYou are given a class `MedicationDosage` that helps manage and validate the medication dosages prescribed to patients. Each dosage has a specific time interval and amount. The objective is to ensure that the daily medication plan for a patient... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 241,
"level": 1,
"question": "### Medication Dosage Schedule Validator\n\nYou are given a class `MedicationDosage` that helps manage and validate the medication dosages prescribed to patients. Each dosage has a specific time interval and amount. The objective is to ensure that the d... |
def square_and_reverse(nums):
return [x ** 2 for x in reversed(nums)] | simplelr_Evol | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a new list where all the elements are squared and the order is reversed. Ensure the function works efficiently with large datasets. For example, given the input `[1, 2, 3, 4, 5]`, the function should return `[25, 16, 9, 4, 1]`.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 242,
"level": 1,
"question": "Create a function that takes a list of integers and returns a new list where all the elements are squared and the order is reversed. Ensure the function works efficiently with large datasets. For example, given the input `[1, 2, 3, 4, 5]`, the function ... |
def string_lengths(strings):
return [len(s) for s in strings] | simplelr_Filter | [
{
"content": "Question:\nPlease write a Python function that takes a list of strings and returns a list containing the length of each string in the input list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 243,
"level": 1,
"question": "Please write a Python function that takes a list of strings and returns a list containing the length of each string in the input list.",
"split": "train"
} |
def reverse_array(arr):
left = 0
right = len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr | simplelr_Filter | [
{
"content": "Question:\nReverse an array without using any built-in functions. The input array will always contain at least 10 elements and at most 1000 elements. The time complexity of the solution should be O(n), where n is the length of the input array. Additionally, you must not use any extra space except ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 244,
"level": 1,
"question": "Reverse an array without using any built-in functions. The input array will always contain at least 10 elements and at most 1000 elements. The time complexity of the solution should be O(n), where n is the length of the input array. Additionally, you mu... |
def highestElevationGain(n, elevations, queries):
results = []
for query in queries:
i, j = query[0], query[1]
sub = elevations[i:j+1]
if len(sub) < 2:
results.append(0)
continue
gains = [sub[k+1] - sub[k] for k in range(len(sub)-1)]
max_gain = max... | simplelr_Taco | [
{
"content": "Question:\nA group of tourists is on a hiking trip. They want to keep track of the highest elevation gain during their hike. They have a record of the elevations at various points along the trail.\n\nYou will be given an array of elevations and a list of query pairs, each representing the start an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 245,
"level": 1,
"question": "A group of tourists is on a hiking trip. They want to keep track of the highest elevation gain during their hike. They have a record of the elevations at various points along the trail.\n\nYou will be given an array of elevations and a list of query pai... |
def max_area(heights):
if len(heights) < 2:
return 0
left = 0
right = len(heights) - 1
max_area = 0
while left < right:
current_area = (right - left) * min(heights[left], heights[right])
if current_area > max_area:
max_area = current_area
if heights[left] ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of non-negative integers that represent the heights of pillars arranged in a line. You have to find the maximum area of water that can be trapped between two pillars. Write a function that receives a list `heights` of integers, where `heights[i]` represents the heig... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 246,
"level": 1,
"question": "You are given a list of non-negative integers that represent the heights of pillars arranged in a line. You have to find the maximum area of water that can be trapped between two pillars. Write a function that receives a list `heights` of integers, wher... |
import numpy as np
from typing import Tuple
def svd_factorization(matrix: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
# Perform SVD using numpy's implementation
U, s, Vh = np.linalg.svd(matrix, full_matrices=True)
# Get the dimensions of the original matrix
M, N = matrix.shape
... | simplelr_Algorithm | [
{
"content": "Question:\n### Objective\nYou are required to implement a function that performs matrix factorization using the Singular Value Decomposition (SVD) method. The goal is to evaluate your understanding of matrix decompositions and matrix operations.\n\n### Problem Statement\nWrite a Python function `s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 247,
"level": 1,
"question": "### Objective\nYou are required to implement a function that performs matrix factorization using the Singular Value Decomposition (SVD) method. The goal is to evaluate your understanding of matrix decompositions and matrix operations.\n\n### Problem Sta... |
def linear_search(lst, target):
for index in range(len(lst)):
if lst[index] == target:
return index
return -1 | simplelr_Filter | [
{
"content": "Question:\nWrite an algorithm to implement a linear search in a list of unordered elements. The function should accept the list and the target value as inputs and return the index of the target value if found, or -1 if the target is not in the list.\nAnswer:\nLet's think step by step.\n",
"rol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 248,
"level": 1,
"question": "Write an algorithm to implement a linear search in a list of unordered elements. The function should accept the list and the target value as inputs and return the index of the target value if found, or -1 if the target is not in the list.",
"split": "... |
import re
from collections import Counter
def most_common_words(filename, n):
with open(filename, 'r') as f:
text = f.read().lower()
# Extract all words, considering apostrophes and letters
all_words = re.findall(r"\b[a-zA-Z']+\b", text)
# Filter out any 'words' that don't contain at ... | simplelr_Package | [
{
"content": "Question:\nWrite a function that reads a text file, computes the frequency of each word, and returns the `n` most common words as a list of tuples. Each tuple should contain the word and its frequency. Words should be compared in a case-insensitive manner and punctuation should be ignored.\n\nThe ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 249,
"level": 1,
"question": "Write a function that reads a text file, computes the frequency of each word, and returns the `n` most common words as a list of tuples. Each tuple should contain the word and its frequency. Words should be compared in a case-insensitive manner and punc... |
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Example usage:
print(factorial(5)) # Output: 120 | simplelr_Filter | [
{
"content": "Question:\nLet's dive into the code. Can you provide a simple example of a function that uses recursion to calculate the factorial of a number in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 250,
"level": 1,
"question": "Let's dive into the code. Can you provide a simple example of a function that uses recursion to calculate the factorial of a number in Python?",
"split": "train"
} |
def check_sum(arr, target):
seen = set()
for num in arr:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Apps | [
{
"content": "Question:\nYou are given an integer array and a target number. Your task is to determine if there are two distinct elements in the array whose sum is equal to the target number. \n\nFor instance:\n```python\ncheck_sum([1, 2, 3, 4], 5) = True // because 1 + 4 = 5\ncheck_sum([1, 2, 3, 4], 8) = Fals... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 251,
"level": 1,
"question": "You are given an integer array and a target number. Your task is to determine if there are two distinct elements in the array whose sum is equal to the target number. \n\nFor instance:\n```python\ncheck_sum([1, 2, 3, 4], 5) = True // because 1 + 4 = 5\... |
import re
def string_to_float(s):
# Regular expression pattern to match valid float strings
pattern = r'^[+-]?((\d+\.?\d*)|(\.\d+))([eE][+-]?\d+)?$'
if not re.fullmatch(pattern, s):
raise ValueError("Invalid float string")
return float(s) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that converts a string to a floating-point number. The function should handle both positive and negative numbers, as well as scientific notation. It should also raise a ValueError if the input string is not a valid floating-point number.\nAnswer:\nLet's think ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 252,
"level": 1,
"question": "Write a Python function that converts a string to a floating-point number. The function should handle both positive and negative numbers, as well as scientific notation. It should also raise a ValueError if the input string is not a valid floating-point... |
from collections import defaultdict
def smallestSubstringContainingUniqueChars(s):
unique_chars = len(set(s))
char_count = defaultdict(int)
num_unique = 0
min_length = float('inf')
left = 0
for right in range(len(s)):
char = s[right]
if char_count[char] == 0:
num_un... | simplelr_Taco | [
{
"content": "Question:\nYou are given a string containing only lowercase alphabetical characters. You need to determine the smallest substring that contains all unique characters present in the original string. Return the length of this substring.\n\n```\nsmallestSubstringContainingUniqueChars(originalString)\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 253,
"level": 1,
"question": "You are given a string containing only lowercase alphabetical characters. You need to determine the smallest substring that contains all unique characters present in the original string. Return the length of this substring.\n\n```\nsmallestSubstringCont... |
def longest_palindromic_subsequence(s: str) -> int:
n = len(s)
if n == 0:
return 0
# Create a 2D DP table with all elements initialized to 0
dp = [[0] * n for _ in range(n)]
# All substrings of length 1 are palindromes of length 1
for i in range(n):
dp[i][i] = 1
# F... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question: Computing the Longest Palindromic Subsequence\n\n**Scenario**: \nYou are developing a text analysis application that needs to determine structural patterns within texts. One important feature is to identify the longest palindromic subsequence within a giv... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 254,
"level": 1,
"question": "### Coding Assessment Question: Computing the Longest Palindromic Subsequence\n\n**Scenario**: \nYou are developing a text analysis application that needs to determine structural patterns within texts. One important feature is to identify the longest pa... |
def flatten_file_paths(file_paths):
counts = {}
output = []
for path in file_paths:
filename = path.split('/')[-1]
if filename not in counts:
output.append(filename)
counts[filename] = 1
else:
if '.' in filename:
base, ext = filenam... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function that processes a list of strings representing file paths and returns a new list of these file paths but with their directories flattened. The function will be named `flatten_file_paths` and should take one parameter `file_paths`, which is a list o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 255,
"level": 1,
"question": "You are tasked with creating a function that processes a list of strings representing file paths and returns a new list of these file paths but with their directories flattened. The function will be named `flatten_file_paths` and should take one paramet... |
import math
def circumference(radius):
return 2 * math.pi * radius | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the circumference of a circle given the radius.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 256,
"level": 1,
"question": "Write a python function to calculate the circumference of a circle given the radius.",
"split": "train"
} |
import heapq
def shortest_path(graph, source):
if not graph:
return []
# Initialize distances to infinity for all nodes except the source
distances = {node: float('infinity') for node in graph}
distances[source] = 0
# Priority queue to process nodes by their current shortest dista... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem: Find the Shortest Path in a Weighted Graph\n\nYou are provided with an implementation of Dijkstra's algorithm to find the shortest path in a weighted graph. Your task is to validate this implementation and fix any bugs or inefficiencies.\n\n#### Instructions:\n\n1. **Fix th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 257,
"level": 1,
"question": "### Problem: Find the Shortest Path in a Weighted Graph\n\nYou are provided with an implementation of Dijkstra's algorithm to find the shortest path in a weighted graph. Your task is to validate this implementation and fix any bugs or inefficiencies.\n\... |
from typing import Dict, List, Tuple
import heapq
def shortest_path(graph: Dict[str, List[Tuple[str, int]]], start: str, end: str) -> List[str]:
# Check if start or end are not present in the graph
if start not in graph or end not in graph:
raise ValueError("Invalid start or end warehouse")
# ... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nAs a software developer for a logistics company, you are tasked with creating a function that simulates delivery routes. Specifically, you need to create a system that finds the most efficient path between warehouse locations while accounting for road closures.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 258,
"level": 1,
"question": "### Problem Statement\n\nAs a software developer for a logistics company, you are tasked with creating a function that simulates delivery routes. Specifically, you need to create a system that finds the most efficient path between warehouse locations wh... |
def merge_sorted_lists(list1: list[int], list2: list[int]) -> list[int]:
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
result.exte... | simplelr_Package | [
{
"content": "Question:\nWrite a function named `merge_sorted_lists` that takes two input lists `list1` and `list2`, where each list contains integers sorted in non-decreasing order. Your task is to merge these two lists into a single list that remains sorted in non-decreasing order and return it.\n\nThe functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 259,
"level": 1,
"question": "Write a function named `merge_sorted_lists` that takes two input lists `list1` and `list2`, where each list contains integers sorted in non-decreasing order. Your task is to merge these two lists into a single list that remains sorted in non-decreasing ... |
def aggregate_sales(sales_data):
aggregated = {}
for item in sales_data:
region = item['region']
product = item['product']
sales = item['sales']
if region not in aggregated:
aggregated[region] = {}
aggregated[region][product] = aggregated[region].get(product, ... | simplelr_Taco | [
{
"content": "Question:\n### Story\nAs a software developer, you are often required to parse and manipulate data in various formats. One common task is to convert a list of dictionaries into a single dictionary, using specific keys for aggregation.\n\n### Info\nYou have a list of dictionaries, each representing... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 260,
"level": 1,
"question": "### Story\nAs a software developer, you are often required to parse and manipulate data in various formats. One common task is to convert a list of dictionaries into a single dictionary, using specific keys for aggregation.\n\n### Info\nYou have a list ... |
def int_divide(n: int) -> int:
dp = [0] * (n + 1)
dp[0] = 1 # Base case: there's one way to partition 0
for k in range(1, n + 1):
for i in range(k, n + 1):
dp[i] += dp[i - k]
return dp[n] | simplelr_Data_Structure | [
{
"content": "Question:\n#### Background\nInteger partitioning is a common problem in combinatorics that involves expressing a positive integer `n` as the sum of one or more positive integers, disregarding the order of the addends. For instance, the number 4 can be partitioned in five different ways: 4, 3+1, 2+... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 261,
"level": 1,
"question": "#### Background\nInteger partitioning is a common problem in combinatorics that involves expressing a positive integer `n` as the sum of one or more positive integers, disregarding the order of the addends. For instance, the number 4 can be partitioned ... |
from collections import deque
def min_steps_maze(grid):
rows = len(grid)
if rows == 0:
return -1
cols = len(grid[0])
start = None
for i in range(rows):
for j in range(cols):
if grid[i][j] == 'S':
start = (i, j)
break
if start:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a 2D grid of characters representing a maze, and two distinct characters 'S' (start) and 'E' (end), write a function to determine the **minimum** number of steps required to move from 'S' to 'E'. You can only move up, down, left, or right, and you cannot pass through '#' (walls). ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 262,
"level": 1,
"question": "Given a 2D grid of characters representing a maze, and two distinct characters 'S' (start) and 'E' (end), write a function to determine the **minimum** number of steps required to move from 'S' to 'E'. You can only move up, down, left, or right, and you... |
def find_balance_point(arr):
total_sum = sum(arr)
left_sum = 0
for i in range(len(arr)):
current = arr[i]
right_sum = total_sum - left_sum - current
if left_sum == right_sum:
return i
left_sum += current
return -1
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `find_balance_point` that takes a list of integers as input and returns the index of the element where the sum of all elements to the left of that element is equal to the sum of all elements to the right of that element. If no such index exists, return -1. If there are ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 263,
"level": 1,
"question": "Write a function `find_balance_point` that takes a list of integers as input and returns the index of the element where the sum of all elements to the left of that element is equal to the sum of all elements to the right of that element. If no such inde... |
from collections import defaultdict
from typing import List
def pigeonhole_sort_v2(arr: List[int]) -> List[int]:
if not arr:
return []
min_val = min(arr)
max_val = max(arr)
freq = defaultdict(int)
for num in arr:
freq[num] += 1
result = []
for num in range(min... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nYou are tasked with implementing a sorting function for a specialized storage system that frequently deals with numerical transactions. Due to the nature of the transactions, the transaction amounts are usually within a limited range. The optimal strategy here would invol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 264,
"level": 1,
"question": "#### Scenario\nYou are tasked with implementing a sorting function for a specialized storage system that frequently deals with numerical transactions. Due to the nature of the transactions, the transaction amounts are usually within a limited range. The... |
def product_except_self(nums):
n = len(nums)
if n == 0:
return []
prefix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]
postfix = [1] * n
for i in range(n-2, -1, -1):
postfix[i] = postfix[i+1] * nums[i+1]
return [prefix[i] * postfix... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns a new list where each element is the product of all the numbers in the original list except the one at the current index. For example, given the list [1, 2, 3, 4], the output should be [24, 12, 8, 6] since 24 = 2*3*4, 12 = 1*3*4... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 265,
"level": 1,
"question": "Write a function that takes a list of integers and returns a new list where each element is the product of all the numbers in the original list except the one at the current index. For example, given the list [1, 2, 3, 4], the output should be [24, 12, ... |
def sum_of_pairs(x, y, z):
return 2 * (x + y + z) | simplelr_Filter | [
{
"content": "Question:\nYou need to write a code that takes 3 parameters x, y, z and returns the sum of all possible pairs (x,y), (x,z), (y,z).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 266,
"level": 1,
"question": "You need to write a code that takes 3 parameters x, y, z and returns the sum of all possible pairs (x,y), (x,z), (y,z).",
"split": "train"
} |
import random
def guess_number():
play_again = True
while play_again:
target = random.randint(1, 100)
print("Welcome to the number guessing game!")
print("I'm thinking of a number between 1 and 100.\n")
while True:
try:
guess = int(input("Tak... | simplelr_Filter | [
{
"content": "Question:\nCreate a simple game in Python that involves guessing a number. The computer picks a random number between 1 and 100, and the player has to guess the number. The game should provide feedback to the player if the guess is too high or too low, and should congratulate the player upon guess... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 267,
"level": 1,
"question": "Create a simple game in Python that involves guessing a number. The computer picks a random number between 1 and 100, and the player has to guess the number. The game should provide feedback to the player if the guess is too high or too low, and should ... |
from typing import List
def find_book(book_ids: List[int], book_id: int) -> int:
low = 0
high = len(book_ids) - 1
while low <= high:
if low == high:
mid = low
else:
low_val = book_ids[low]
high_val = book_ids[high]
if high_val == low_val:
... | simplelr_Data_Structure | [
{
"content": "Question:\n**Problem Statement: Library Book Finder**\n\nYou're given a sorted list of book IDs in a library, and you need to find a specific book given its ID. However, this library periodically encounters an issue where the books are sometimes not perfectly uniformly distributed by ID due to don... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 268,
"level": 1,
"question": "**Problem Statement: Library Book Finder**\n\nYou're given a sorted list of book IDs in a library, and you need to find a specific book given its ID. However, this library periodically encounters an issue where the books are sometimes not perfectly unif... |
def is_leap_year(year):
return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that determines if a given year is a leap year or not. A leap year is exactly divisible by 4 except for end-of-century years, which must be divisible by 400. This means that the year 2000 was a leap year, although 1900 was not.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 269,
"level": 1,
"question": "Create a function that determines if a given year is a leap year or not. A leap year is exactly divisible by 4 except for end-of-century years, which must be divisible by 400. This means that the year 2000 was a leap year, although 1900 was not.",
"sp... |
def gcd(a, b):
a = abs(a)
b = abs(b)
while b != 0:
a, b = b, a % b
return a
# Test cases
print(gcd(48, 18)) # Expected output: 6
print(gcd(54, 24)) # Expected output: 6
print(gcd(0, 5)) # Expected output: 5
print(gcd(5, 0)) # Expected output: 5 | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the greatest common divisor (GCD) of two numbers, `a` and `b`, using the Euclidean algorithm. Ensure your function is efficient and can handle large numbers. Additionally, include a simple way to test your function with a couple of examples to verify its ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 270,
"level": 1,
"question": "Write a Python function to find the greatest common divisor (GCD) of two numbers, `a` and `b`, using the Euclidean algorithm. Ensure your function is efficient and can handle large numbers. Additionally, include a simple way to test your function with a... |
def concatenateAlphabets(a: str, b: str) -> str:
"""
Concatenates two input strings and returns the result.
Parameters:
a (str): The first string to be concatenated.
b (str): The second string to be concatenated.
Returns:
str: The combined string of 'a' and 'b'.
"""
return ... | simplelr_Filter | [
{
"content": "Question:\nAuthor a Python procedure labeled 'concatenateAlphabets' which accepts two parameters of the data type string and outputs the resultant string, amalgamated from both inputs.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 271,
"level": 1,
"question": "Author a Python procedure labeled 'concatenateAlphabets' which accepts two parameters of the data type string and outputs the resultant string, amalgamated from both inputs.",
"split": "train"
} |
def has_pair_with_sum(nums, target):
seen = set()
for num in nums:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Filter | [
{
"content": "Question:\nYour task is to implement a function that takes two parameters - a list of integers and a target integer. The function should then return a boolean value indicating whether there is a pair of numbers in the list that sum to the target integer.\n\nExample:\nInput: nums = [2, 7, 11, 15], ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 272,
"level": 1,
"question": "Your task is to implement a function that takes two parameters - a list of integers and a target integer. The function should then return a boolean value indicating whether there is a pair of numbers in the list that sum to the target integer.\n\nExampl... |
import re
def replace_hello_with_goodbye(s):
return re.sub(r'\bHello\b', 'Goodbye', s, flags=re.IGNORECASE) | simplelr_Filter | [
{
"content": "Question:\nManipulate the string \"Hello, World!\" using the correct Python function that will replace the word \"Hello\" with \"Goodbye\". Remember to consider different cases such as the string being in all uppercase or all lowercase, and ensure that the function can handle such cases. Additiona... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 273,
"level": 1,
"question": "Manipulate the string \"Hello, World!\" using the correct Python function that will replace the word \"Hello\" with \"Goodbye\". Remember to consider different cases such as the string being in all uppercase or all lowercase, and ensure that the functio... |
from collections import Counter
from typing import List
def frequent_students(names: List[str], k: int) -> List[str]:
counts = Counter(names)
result = [name for name, count in counts.items() if count >= k]
return sorted(result) | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes an array of strings representing a list of student names and an integer `k`. The task is to return an array containing all the names that appear `k` or more times in the list. The returned array should be in alphabetical order. \n\n**Function Signature:**\n``... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 274,
"level": 1,
"question": "Write a function that takes an array of strings representing a list of student names and an integer `k`. The task is to return an array containing all the names that appear `k` or more times in the list. The returned array should be in alphabetical orde... |
import numpy as np
def solve_linear_system(coefficients, constants):
"""
Solves a system of linear equations using numpy.
Args:
coefficients (numpy.ndarray): A 2D array of coefficients.
constants (numpy.ndarray): A 1D array of constants.
Returns:
numpy.ndarray: The sol... | simplelr_Filter | [
{
"content": "Question:\nThis task requires you to create a Python function that can solve a system of linear equations using the numpy library. The function should accept a 2D array of coefficients and a 1D array of constants.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 275,
"level": 1,
"question": "This task requires you to create a Python function that can solve a system of linear equations using the numpy library. The function should accept a 2D array of coefficients and a 1D array of constants.",
"split": "train"
} |
def searchMatrix(matrix, target):
if not matrix or not matrix[0]:
return False
m = len(matrix)
n = len(matrix[0])
row, col = 0, n - 1
while row < m and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
col -= 1
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a matrix `matrix` of integers where each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom, write a function `searchMatrix` that returns _whether a given target value exists in the matrix_. You must write an algori... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 276,
"level": 1,
"question": "Given a matrix `matrix` of integers where each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom, write a function `searchMatrix` that returns _whether a given target value exists in the... |
def calculate_average_grades(student_grades):
result = []
for student in student_grades:
name = student['name']
grades = student['grades']
average = sum(grades) / len(grades)
rounded_average = round(average, 2)
result.append({'name': name, 'average': rounded_average})
... | simplelr_Package | [
{
"content": "Question:\nYou are given a list of dictionaries `student_grades`, where each dictionary contains the following key-value pairs:\n\n- `'name'` (str): The name of the student.\n- `'grades'` (list of int): A list of integers representing the grades received by the student.\n\nYour task is to create a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 277,
"level": 1,
"question": "You are given a list of dictionaries `student_grades`, where each dictionary contains the following key-value pairs:\n\n- `'name'` (str): The name of the student.\n- `'grades'` (list of int): A list of integers representing the grades received by the st... |
def longest_unique_substring_length(s):
max_length = 0
start = 0
char_index = {}
for end in range(len(s)):
char = s[end]
if char in char_index and char_index[char] >= start:
start = char_index[char] + 1
char_index[char] = end
current_length = end - start + 1
... | simplelr_Package | [
{
"content": "Question:\nImplement a function to find the longest consecutive sequence of unique characters in a given string. The function should return the length of this longest sequence.\n\nThe function should be named `longest_unique_substring_length`. The function will take the following parameter:\n\n- `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 278,
"level": 1,
"question": "Implement a function to find the longest consecutive sequence of unique characters in a given string. The function should return the length of this longest sequence.\n\nThe function should be named `longest_unique_substring_length`. The function will ta... |
def merge_alternating(list1, list2):
result = []
min_len = min(len(list1), len(list2))
for i in range(min_len):
result.append(list1[i])
result.append(list2[i])
result.extend(list1[min_len:])
result.extend(list2[min_len:])
return result | simplelr_Package | [
{
"content": "Question:\nYou are tasked with writing a Python function that merges two given lists into a single list, alternating elements from each list. If one list is longer than the other, append the remaining elements from the longer list to the end of the merged list. This problem should serve as an educ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 279,
"level": 1,
"question": "You are tasked with writing a Python function that merges two given lists into a single list, alternating elements from each list. If one list is longer than the other, append the remaining elements from the longer list to the end of the merged list. Th... |
def factorial(n):
if n < 0:
raise ValueError("n must be a non-negative integer")
result = 1
for i in range(1, n + 1):
result *= i
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the factorial of a number in Python. factorial(n) where n is a non-negative integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 280,
"level": 1,
"question": "Write a function to find the factorial of a number in Python. factorial(n) where n is a non-negative integer.",
"split": "train"
} |
import numpy as np
def encode_dna_data(dna_sequence):
char_to_index = {'A': 0, 'T': 1, 'C': 2, 'G': 3}
encoded = []
for char in dna_sequence:
vec = [0] * 6
vec[char_to_index[char]] = 1
encoded.append(vec)
return np.array(encoded) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function named `encode_dna_data` that converts a DNA sequence string into a 2D binary array representation using numpy. The DNA sequence only contains the characters 'A', 'T', 'C', and 'G'. Each DNA character should be represented by a 6-bit binary array where each bit po... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 281,
"level": 1,
"question": "Write a Python function named `encode_dna_data` that converts a DNA sequence string into a 2D binary array representation using numpy. The DNA sequence only contains the characters 'A', 'T', 'C', and 'G'. Each DNA character should be represented by a 6-... |
def min_max_indices(arr):
if not arr:
return []
min_val = min(arr)
max_val = max(arr)
min_index = arr.index(min_val)
reversed_arr = arr[::-1]
reversed_index = reversed_arr.index(max_val)
max_index = len(arr) - 1 - reversed_index
return [min_index, max_index] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer array as input and returns an array that contains the indices of the minimum and maximum values in the input array. If there are multiple occurrences of the same value, the function should return the index of the first occurrence of the minimum an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 282,
"level": 1,
"question": "Create a function that takes an integer array as input and returns an array that contains the indices of the minimum and maximum values in the input array. If there are multiple occurrences of the same value, the function should return the index of the ... |
from collections import Counter
def is_valid(s):
freq = Counter(s)
count_freq = Counter(freq.values())
if len(count_freq) == 1:
return "YES"
elif len(count_freq) == 2:
keys = sorted(count_freq.keys())
# Check if one of the frequencies is 1 and occurs once
if keys[0]... | simplelr_Code_Contests | [
{
"content": "Question:\nGiven a string `s`, you are required to determine if it is valid. A string is considered valid if two conditions are both satisfied:\n\n1. All characters of `s` appear the same number of times.\n2. An exception is allowed where you can remove just one character from `s` to achieve the f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 283,
"level": 1,
"question": "Given a string `s`, you are required to determine if it is valid. A string is considered valid if two conditions are both satisfied:\n\n1. All characters of `s` appear the same number of times.\n2. An exception is allowed where you can remove just one c... |
from typing import List
def min_max_pair_sum(arr: List[int]) -> int:
arr_sorted = sorted(arr)
n = len(arr_sorted)
max_sum = 0
for i in range(n // 2):
current = arr_sorted[i] + arr_sorted[n - 1 - i]
if current > max_sum:
max_sum = current
return max_sum | simplelr_Code_Contests | [
{
"content": "Question:\nYou are given an integer array `arr` of length `n`, where `n` is always even. Your task is to group the elements of `arr` into pairs such that the maximum sum of elements in any pair is minimized. For example, if you have an array [1, 4, 3, 2], you can pair (1, 4) and (3, 2).\n\nWrite a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 284,
"level": 1,
"question": "You are given an integer array `arr` of length `n`, where `n` is always even. Your task is to group the elements of `arr` into pairs such that the maximum sum of elements in any pair is minimized. For example, if you have an array [1, 4, 3, 2], you can ... |
def number_of_characters(words):
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
total = 0
for key, value in word_counts.items():
if value == 2:
total += len(key)
return total
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of strings words, return the total number of characters in the strings that appear exactly twice in the array.\n\nExample 1:\nInput: words = [\"apple\", \"banana\", \"apple\", \"orange\", \"kiwi\", \"banana\"]\nOutput: 11\nExplanation: \n\"apple\" appears twice with 5 cha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 285,
"level": 1,
"question": "Given an array of strings words, return the total number of characters in the strings that appear exactly twice in the array.\n\nExample 1:\nInput: words = [\"apple\", \"banana\", \"apple\", \"orange\", \"kiwi\", \"banana\"]\nOutput: 11\nExplanation: \n... |
import collections
def isPossibleDivide(nums, k):
if k == 1:
return True
n = len(nums)
if n % k != 0:
return False
nums.sort()
freq = collections.defaultdict(int)
for num in nums:
freq[num] += 1
for x in nums:
current_x = x
if freq.get(current_x, 0) <... | simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, determine whether it can be divided into subsequences of length `k` such that each subsequence contains integers that are consecutive. Return `True` if such a division is possible, and `False` otherwise.\n\nExample\n\nnums = [1,2,3,3,4,4,5,6] and k = 4\n\nThe l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 286,
"level": 1,
"question": "Given a list of integers, determine whether it can be divided into subsequences of length `k` such that each subsequence contains integers that are consecutive. Return `True` if such a division is possible, and `False` otherwise.\n\nExample\n\nnums = [1... |
def first_non_repeating_char(s: str) -> str:
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
for char in s:
if char_count[char] == 1:
return char
return "" | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nAs a software developer, you often need to find specific elements within a collection of data. For this task, you are to create a function that identifies the first non-repeating character in a given string. This will help in various applications, such as text processing a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 287,
"level": 1,
"question": "### Scenario\nAs a software developer, you often need to find specific elements within a collection of data. For this task, you are to create a function that identifies the first non-repeating character in a given string. This will help in various appli... |
def encrypt(s, shift):
result = ""
for char in s:
if char.isalpha():
if char.isupper():
base = ord('A')
else:
base = ord('a')
offset = ord(char) - base
new_offset = (offset + shift) % 26
new_char = chr(new_offset... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a string as input and encrypts it using a simple substitution cipher. The substitution cipher should shift each character in the string by a specified number of positions in the alphabet.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 288,
"level": 1,
"question": "Create a Python function that takes a string as input and encrypts it using a simple substitution cipher. The substitution cipher should shift each character in the string by a specified number of positions in the alphabet.",
"split": "train"
} |
def is_leap_year(year):
return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0) | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that checks if a given year is a leap year and returns a boolean value?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 289,
"level": 1,
"question": "How can I create a Python function that checks if a given year is a leap year and returns a boolean value?",
"split": "train"
} |
def word_pattern(pattern, string):
words = string.split()
if len(pattern) != len(words):
return False
p_map = {}
w_map = {}
for p_char, word in zip(pattern, words):
if p_char in p_map:
if p_map[p_char] != word:
return False
else:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Word Pattern Matching\n\n#### Scenario\nYou are developing a text processing framework that needs to verify if sentences conform to specified templates. Each template is represented by a pattern, which consists of lowercase letters, where each letter represents a unique word. The fr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 290,
"level": 1,
"question": "### Word Pattern Matching\n\n#### Scenario\nYou are developing a text processing framework that needs to verify if sentences conform to specified templates. Each template is represented by a pattern, which consists of lowercase letters, where each lette... |
def reverse_words(s):
return ' '.join(s.split()[::-1]) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that implements a function `reverse_words` which takes a string as input and returns a new string with the words in reverse order. For example, given the string \"hello world\", the function should return \"world hello\". Note that the characters in each word shou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 291,
"level": 1,
"question": "Write a Python program that implements a function `reverse_words` which takes a string as input and returns a new string with the words in reverse order. For example, given the string \"hello world\", the function should return \"world hello\". Note tha... |
import random
def draw_card_suit():
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
return random.choice(suits) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to simulate drawing a card from a deck and returning the suit. The function should return one of four possible suits: Hearts, Diamonds, Clubs, or Spades. Ensure that the function is truly random and that each suit has an equal chance of being selected.\nAnswer:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 292,
"level": 1,
"question": "Write a Python function to simulate drawing a card from a deck and returning the suit. The function should return one of four possible suits: Hearts, Diamonds, Clubs, or Spades. Ensure that the function is truly random and that each suit has an equal ch... |
from typing import List
def is_subset_sum(arr: List[int], k: int) -> bool:
arr.sort(reverse=True)
n = len(arr)
for mask in range(1 << n):
current_sum = 0
for j in range(n):
if mask & (1 << j):
current_sum += arr[j]
if current_sum > k:
... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a list of `n` integers and a positive integer `k`. Your task is to determine if there is a subset of the list that sums up to exactly `k`.\n\nWrite a function:\n\n```python\ndef is_subset_sum(arr: List[int], k: int) -> bool:\n```\n\nthat takes an array of integers `arr` an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 293,
"level": 1,
"question": "You are given a list of `n` integers and a positive integer `k`. Your task is to determine if there is a subset of the list that sums up to exactly `k`.\n\nWrite a function:\n\n```python\ndef is_subset_sum(arr: List[int], k: int) -> bool:\n```\n\nthat t... |
def is_valid_sentence(inputString):
if not inputString:
return False
if inputString[-1] != '.':
return False
if not inputString[0].isupper():
return False
words = inputString.split()
for i in range(len(words)):
word = words[i]
if i == len(words) - 1:
... | simplelr_Apps | [
{
"content": "Question:\n# Task\nGiven a string containing a sequence of words separated by spaces, write a function that returns true if the sequence forms a valid sentence according to the following rules:\n1. The sentence must start with an uppercase letter.\n2. Each word must contain only alphabetical chara... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 294,
"level": 1,
"question": "# Task\nGiven a string containing a sequence of words separated by spaces, write a function that returns true if the sequence forms a valid sentence according to the following rules:\n1. The sentence must start with an uppercase letter.\n2. Each word mu... |
def process_events(events):
total_time = 0
for event_time in events:
total_time += event_time
return total_time | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\nYou are given a sequence of events and the time it takes for each event to occur. Your task is to implement a `process_events` function that schedules these events in such a way that each subsequent event starts only after the previous event has complet... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 295,
"level": 1,
"question": "### Coding Assessment Question\n\nYou are given a sequence of events and the time it takes for each event to occur. Your task is to implement a `process_events` function that schedules these events in such a way that each subsequent event starts only af... |
def char_frequency(s):
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
return freq | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and outputs a dictionary that shows the frequency of each character in the string, including spaces. To handle case sensitivity, treat 'A' and 'a' as two different characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 296,
"level": 1,
"question": "Create a function that takes a string as input and outputs a dictionary that shows the frequency of each character in the string, including spaces. To handle case sensitivity, treat 'A' and 'a' as two different characters.",
"split": "train"
} |
import os
def find_folder(root_dir, target_folder):
found_path = None
for dirpath, dirnames, filenames in os.walk(root_dir):
if target_folder in dirnames:
found_path = os.path.join(dirpath, target_folder)
break # Exit the loop once found
return found_path
# Example usage
r... | simplelr_Filter | [
{
"content": "Question:\nHow can I find a specific folder within a nested directory structure using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 297,
"level": 1,
"question": "How can I find a specific folder within a nested directory structure using Python?",
"split": "train"
} |
import cmath
from typing import List
def fft(array: List[complex]) -> List[complex]:
n = len(array)
if n == 1:
return array
even = array[::2]
odd = array[1::2]
E = fft(even)
O = fft(odd)
m = n // 2
result = [0] * n
for k in range(m):
w = cmath.exp... | simplelr_Data_Structure | [
{
"content": "Question:\n### Fast Fourier Transform Coding Challenge\n\n#### Context\nThe Fast Fourier Transform (FFT) is a highly efficient algorithm to compute the Discrete Fourier Transform (DFT) and its inverse. It is widely used in various fields such as digital signal processing, image processing, and sol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 298,
"level": 1,
"question": "### Fast Fourier Transform Coding Challenge\n\n#### Context\nThe Fast Fourier Transform (FFT) is a highly efficient algorithm to compute the Discrete Fourier Transform (DFT) and its inverse. It is widely used in various fields such as digital signal pro... |
def longest_common_subsequence(s1, s2):
m = len(s1)
n = len(s2)
# Create a table with (m+1) rows and (n+1) columns
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1] + ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the longest common subsequence (LCS) between two strings. What is Longest Common Subsequence?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 299,
"level": 1,
"question": "Write a python function to find the longest common subsequence (LCS) between two strings. What is Longest Common Subsequence?",
"split": "train"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.