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 decode_compressed(compressed: str) -> str:
""" Decode a run-length encoded string of integer and character pairs into the original string """
decoded_string = ""
i = 0
while i < len(compressed):
# Read the count (which can be more than one digit)
count = 0
while i < len(compr... | simplelr_Evol | [
{
"content": "Question:\nCreate a function `decode_compressed` that decodes a run-length encoded string. The input string is composed of pairs of integers and characters, which indicate how many times each character should be repeated in the decoded string. Your function should return the original string.\n\nWr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1500,
"level": 1,
"question": "Create a function `decode_compressed` that decodes a run-length encoded string. The input string is composed of pairs of integers and characters, which indicate how many times each character should be repeated in the decoded string. Your function shoul... |
from collections import Counter
def findSpecialElements(nums):
n = len(nums)
if n == 0:
return []
threshold = n // 3
counts = Counter(nums)
result = [x for x in counts if counts[x] > threshold]
return result
| simplelr_Taco | [
{
"content": "Question:\nMasha loves arrays. She defines a \"special element\" in an array as the element that appears strictly more than ⌊n/3⌋ times, where n is the size of the array and ⌊x⌋ denotes the floor function.\n\nGiven an integer array `nums`, your task is to find all the \"special elements\" in the a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1501,
"level": 1,
"question": "Masha loves arrays. She defines a \"special element\" in an array as the element that appears strictly more than ⌊n/3⌋ times, where n is the size of the array and ⌊x⌋ denotes the floor function.\n\nGiven an integer array `nums`, your task is to find al... |
import string
def query_vocabulary(texts):
word_counts = {}
for text in texts:
for word in text.split():
cleaned = word.lower().strip(string.punctuation)
if cleaned:
word_counts[cleaned] = word_counts.get(cleaned, 0) + 1
return word_counts | simplelr_Filter | [
{
"content": "Question:\nWrite a small python module for querying vocabulary words from an array of texts. The querying should be case insensitive and the module should be able to return the number of times each word has appeared in the texts. The input to the function should be an array of strings. The output ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1502,
"level": 1,
"question": "Write a small python module for querying vocabulary words from an array of texts. The querying should be case insensitive and the module should be able to return the number of times each word has appeared in the texts. The input to the function should ... |
def sum_of_distances(arr):
sorted_arr = sorted(arr)
return sum(sorted_arr[i+1] - sorted_arr[i] for i in range(len(sorted_arr)-1)) | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers, return the sum of the distances between consecutive elements in the sorted version of this array.\n\n## Examples\n\n```\n[4, 2, 9, 7] ==> 7 // Sorted array: [2, 4, 7, 9] => (4-2) + (7-4) + (9-7) = 2 + 3 + 2 = 7\n[1, 5, 3] ==> 4 // Sorted array: [1, 3, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1503,
"level": 1,
"question": "Given an array of integers, return the sum of the distances between consecutive elements in the sorted version of this array.\n\n## Examples\n\n```\n[4, 2, 9, 7] ==> 7 // Sorted array: [2, 4, 7, 9] => (4-2) + (7-4) + (9-7) = 2 + 3 + 2 = 7\n[1, 5, 3] ... |
def summarize_transactions(input_string: str) -> dict:
result = {
"total_expense": 0.0,
"total_income": 0.0,
"categories": {}
}
transactions = input_string.split(';')
for tx in transactions:
stripped_tx = tx.strip()
if not stripped_tx:
continue
... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nWrite a Python program that takes a structured text input representing transactions and organizes them into a summary report. Your task demonstrates understanding of data structures, functions, file handling, and exception management.\n\n#### Problem Description:\nYou a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1504,
"level": 1,
"question": "#### Objective:\nWrite a Python program that takes a structured text input representing transactions and organizes them into a summary report. Your task demonstrates understanding of data structures, functions, file handling, and exception management.\... |
def max_task_pairs(tasks, t):
tasks.sort()
left = 0
right = len(tasks) - 1
count = 0
while left < right:
if tasks[left] + tasks[right] <= t:
count += 1
left += 1
right -= 1
else:
right -= 1
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `n` tasks represented by an integer array `tasks`, where `tasks[i]` represents the time required to complete the `i-th` task. A server can handle exactly two tasks simultaneously, but the same task cannot be paired with itself. The objective is to maximize the nu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1505,
"level": 1,
"question": "You are given a list of `n` tasks represented by an integer array `tasks`, where `tasks[i]` represents the time required to complete the `i-th` task. A server can handle exactly two tasks simultaneously, but the same task cannot be paired with itself. ... |
def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
return celsius | simplelr_Filter | [
{
"content": "Question:\nDevelop a function to convert temperature from Fahrenheit to Celsius in Python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1506,
"level": 1,
"question": "Develop a function to convert temperature from Fahrenheit to Celsius in Python.",
"split": "train"
} |
import curses
def main(stdscr):
# Enable the cursor
curses.curs_set(1)
# Initialize the screen
stdscr.clear()
height, width = stdscr.getmaxyx()
text_win = curses.newwin(height - 1, width, 0, 0)
status_bar = curses.newwin(1, width, height - 1, 0)
# Initialize editor state
l... | simplelr_Docs | [
{
"content": "Question:\n### Advanced Coding Assessment Question: Create a Simple Text Editor\n\n**Objective**: \nCreate a simple text-based editor using the curses library in Python. This editor should allow users to type text, navigate using arrow keys, and provide some basic text editing functionalities.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1507,
"level": 1,
"question": "### Advanced Coding Assessment Question: Create a Simple Text Editor\n\n**Objective**: \nCreate a simple text-based editor using the curses library in Python. This editor should allow users to type text, navigate using arrow keys, and provide some basi... |
def peak_index_in_mountain_array(nums):
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
return i
return -1 # This line is theoretically unreachable for valid mountain arrays | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `nums` consisting of `n` distinct integers. The array is described as a **mountain array** if and only if: \n- `n >= 3`\n- There exists an index `i` with `0 < i < n - 1` such that:\n * `nums[0] < nums[1] < ... < nums[i - 1] < nums[i]`\n * `n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1508,
"level": 1,
"question": "You are given a **0-indexed** integer array `nums` consisting of `n` distinct integers. The array is described as a **mountain array** if and only if: \n- `n >= 3`\n- There exists an index `i` with `0 < i < n - 1` such that:\n * `nums[0] < nums[1] < .... |
import string
def word_frequency(sentence, word):
words = sentence.split()
count = 0
for w in words:
cleaned = w.strip(string.punctuation)
if cleaned == word:
count += 1
return count | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the frequency of occurrence of a given word in a sentence. The function should take two parameters: the sentence and the word to search for. It should return the frequency of the word in the sentence.\nAnswer:\nLet's think step by step.\n",
"role": "u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1509,
"level": 1,
"question": "Write a python function to find the frequency of occurrence of a given word in a sentence. The function should take two parameters: the sentence and the word to search for. It should return the frequency of the word in the sentence.",
"split": "train... |
from collections import Counter
def most_frequent_kgram(word, k):
n = len(word)
if n <= k:
return word
grams = [word[i:i+k] for i in range(n - k + 1)]
counts = Counter(grams)
max_count = max(counts.values())
candidates = [gram for gram in counts if counts[gram] == max_count]
candida... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `word` and an integer `k`. A k-gram is defined as a substring of `word` that is exactly `k` characters long. Your task is to find the most frequent k-gram in `word`. If there are multiple k-grams with the same highest frequency, return the lexicographically smalle... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1510,
"level": 1,
"question": "You are given a string `word` and an integer `k`. A k-gram is defined as a substring of `word` that is exactly `k` characters long. Your task is to find the most frequent k-gram in `word`. If there are multiple k-grams with the same highest frequency, ... |
import cmath
def find_complex_roots(a, b, c):
discriminant = b**2 - 4*a*c
sqrt_discriminant = cmath.sqrt(discriminant)
root1 = (-b + sqrt_discriminant) / (2 * a)
root2 = (-b - sqrt_discriminant) / (2 * a)
return (root1, root2) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `find_complex_roots` that calculates the complex roots of the quadratic equation \\( ax^2 + bx + c = 0 \\) when the discriminant is less than zero. The function should take three parameters, `a`, `b`, and `c`, representing the coefficients of the quadratic equati... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1511,
"level": 1,
"question": "Write a Python function `find_complex_roots` that calculates the complex roots of the quadratic equation \\( ax^2 + bx + c = 0 \\) when the discriminant is less than zero. The function should take three parameters, `a`, `b`, and `c`, representing the c... |
from typing import List
def generate_fibonacci(n: int) -> List[int]:
# Check if n is a positive integer and not a boolean
if not isinstance(n, int) or isinstance(n, bool) or n < 1:
return []
if n == 1:
return [0]
fib = [0, 1]
for i in range(2, n):
next_num = fib[i-... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Problem Statement\nWrite a function `generate_fibonacci(n: int) -> List[int]` that generates a list of the first `n` numbers in the Fibonacci sequence. The Fibonacci sequence is defined as follows:\n- The first two numbers are 0 and 1.\n- Each subs... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1512,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Problem Statement\nWrite a function `generate_fibonacci(n: int) -> List[int]` that generates a list of the first `n` numbers in the Fibonacci sequence. The Fibonacci sequence is defined as follows:\n- The first tw... |
def next_bigger(num: int) -> int:
digits = list(str(num))
n = len(digits)
# Step 1: Find the largest index 'i' such that digits[i] < digits[i+1]
i = n - 2
while i >= 0 and digits[i] >= digits[i + 1]:
i -= 1
if i == -1:
return -1 # No such number possible
# Step 2: ... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a number as input, and you need to find the next higher number that has the same set of digits as the original number. If such a number does not exist (i.e., the input number is the highest permutation of its digits), return -1.\n\n### Function Signature\n```python\ndef ne... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1513,
"level": 1,
"question": "You are given a number as input, and you need to find the next higher number that has the same set of digits as the original number. If such a number does not exist (i.e., the input number is the highest permutation of its digits), return -1.\n\n### Fu... |
def sum_of_squares(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return sum_of_squares(n-1) + n ** 2 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the sum of the squares of the first `n` natural numbers. The function should use recursion and not any iterative constructs like loops.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1514,
"level": 1,
"question": "Write a python function to calculate the sum of the squares of the first `n` natural numbers. The function should use recursion and not any iterative constructs like loops.",
"split": "train"
} |
def findWinner(n, array):
if not array:
return "Ben"
m = min(array)
if m == 0:
return "Ben"
# Check if there exists any element greater than m
has_greater = any(x > m for x in array)
if has_greater:
return "Anna" if m % 2 == 1 else "Ben"
else:
#... | simplelr_Codeforces | [
{
"content": "Question:\nAnna and Ben play a game involving an array of n integers. They take turns making moves. A move consists of selecting a subarray of the given array and reducing each element in the subarray by 1. Anna always goes first.\n\nThe game ends when the array contains at least one negative elem... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1515,
"level": 1,
"question": "Anna and Ben play a game involving an array of n integers. They take turns making moves. A move consists of selecting a subarray of the given array and reducing each element in the subarray by 1. Anna always goes first.\n\nThe game ends when the array ... |
def min_difference(tasks):
total = sum(tasks)
target = total // 2
dp = [False] * (target + 1)
dp[0] = True # Base case: sum of 0 is always possible
for task in tasks:
# Iterate backwards to avoid using the same task multiple times
for j in range(target, task - 1, -1):
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array `tasks` where `tasks[i]` represents the processing time of the `i-th` task. Each task is assigned to one of two available servers. You need to distribute the tasks between the two servers such that the difference between the total processing times of the two serve... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1516,
"level": 1,
"question": "You are given an array `tasks` where `tasks[i]` represents the processing time of the `i-th` task. Each task is assigned to one of two available servers. You need to distribute the tasks between the two servers such that the difference between the tota... |
def character_count(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count | simplelr_Filter | [
{
"content": "Question:\nHello, Qwen, how can I create a function in Python that takes a string as input and returns the number of times each character appears in the string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1517,
"level": 1,
"question": "Hello, Qwen, how can I create a function in Python that takes a string as input and returns the number of times each character appears in the string?",
"split": "train"
} |
def adjust_schedule(schedules, dst):
adjusted = []
for device, time in schedules:
hour_str, min_str = time.split(':')
hour = int(hour_str)
minute = int(min_str)
if dst:
hour = (hour + 1) % 24
new_time = f"{hour:02d}:{minute:02d}"
adjusted.append((devic... | simplelr_Apps | [
{
"content": "Question:\nYou are working with a smart home automation system where devices can be programmed to turn on and off at specific times. One of the features of the system is to adjust the time settings according to daylight savings. Given a list of device schedules and a boolean indicating the activat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1518,
"level": 1,
"question": "You are working with a smart home automation system where devices can be programmed to turn on and off at specific times. One of the features of the system is to adjust the time settings according to daylight savings. Given a list of device schedules a... |
def counting_sort(arr):
if not arr:
return []
min_val = min(arr)
max_val = max(arr)
if min_val == max_val:
return arr.copy()
adjusted = [x - min_val for x in arr]
range_size = max_val - min_val + 1
count = [0] * range_size
for x in adjusted:
co... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to sort a list of integers using the counting sort algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1519,
"level": 1,
"question": "Write a python function to sort a list of integers using the counting sort algorithm.",
"split": "train"
} |
import grp
from collections import defaultdict
def analyze_group_database() -> dict:
groups_without_members = []
user_group_counts = defaultdict(int)
groups_list = []
for group in grp.getgrall():
group_name = group.gr_name
group_gid = group.gr_gid
groups_list.append((group_name... | simplelr_Docs | [
{
"content": "Question:\n**Objective:**\nThe goal of this question is to assess your understanding and application of the `grp` module in Python for accessing the Unix group database.\n\n**Problem Statement:**\n\nYou are required to write a Python function that analyzes the Unix group database and provides spec... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1520,
"level": 1,
"question": "**Objective:**\nThe goal of this question is to assess your understanding and application of the `grp` module in Python for accessing the Unix group database.\n\n**Problem Statement:**\n\nYou are required to write a Python function that analyzes the Un... |
def has_repeating_character(s):
seen = {}
for char in s:
if char in seen:
return True
seen[char] = True
return False | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to check if a string has a repeating character in it. You should use a dictionary to keep track of characters as you iterate through the string. If a character is already in the dictionary, it means that the character has been seen before. Return `True` if a repe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1521,
"level": 1,
"question": "Write a python function to check if a string has a repeating character in it. You should use a dictionary to keep track of characters as you iterate through the string. If a character is already in the dictionary, it means that the character has been s... |
def removeDuplicates(input_list: list) -> list:
seen = set()
result = []
for item in input_list:
if item not in seen:
result.append(item)
seen.add(item)
return result | simplelr_Package | [
{
"content": "Question:\nYou have been asked to write a Python function named `removeDuplicates` that removes duplicate values from a list while maintaining the original order of elements. The function should return a new list without duplicates, keeping the first occurrence of each element in the given list.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1522,
"level": 1,
"question": "You have been asked to write a Python function named `removeDuplicates` that removes duplicate values from a list while maintaining the original order of elements. The function should return a new list without duplicates, keeping the first occurrence o... |
def string_to_word_list(s):
return s.split() | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert a given string into a list containing individual words. The function should handle punctuation as well, treating punctuation as part of the word it is attached to (i.e., \"word,\" should be converted to [\"word,\"]).\nAnswer:\nLet's think step by step.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1523,
"level": 1,
"question": "Write a python function to convert a given string into a list containing individual words. The function should handle punctuation as well, treating punctuation as part of the word it is attached to (i.e., \"word,\" should be converted to [\"word,\"])."... |
def sort_descending(xs):
return sorted(xs, reverse=True) | simplelr_Filter | [
{
"content": "Question:\nPlease revise the provided Python function to not modify the input list 'xs' in place, but instead return a new list that is sorted in descending order. Also ensure your code handles the case of an empty list input.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1524,
"level": 1,
"question": "Please revise the provided Python function to not modify the input list 'xs' in place, but instead return a new list that is sorted in descending order. Also ensure your code handles the case of an empty list input.",
"split": "train"
} |
from typing import List
def generate_sequence(n: int) -> List[str]:
result = []
for num in range(1, n + 1):
if num % 15 == 0:
result.append("FizzBuzz")
elif num % 3 == 0:
result.append("Fizz")
elif num % 5 == 0:
result.append("Buzz")
else:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context\nYou have been tasked with implementing a function that generates a sequence based on a specific set of rules. This problem tests your understanding of loops, conditionals, and string operations in Python.\n\n#### Problem Statement\nWrite a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1525,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context\nYou have been tasked with implementing a function that generates a sequence based on a specific set of rules. This problem tests your understanding of loops, conditionals, and string operations in Python.... |
from collections import Counter
def max_length_after_k_operations(s, k):
if not s:
return 0
count = Counter(s)
freq = sorted(count.values())
m = len(freq)
t = min(k, m)
sum_removed = sum(freq[:t])
return len(s) - sum_removed | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` and an integer `k`, you need to perform the following operation exactly `k` times: Choose any character `c` in `s` and all occurrences of `c` in the string will be removed. Your goal is to maximize the length of the remaining string after `k` operations. Return _the l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1526,
"level": 1,
"question": "Given a string `s` and an integer `k`, you need to perform the following operation exactly `k` times: Choose any character `c` in `s` and all occurrences of `c` in the string will be removed. Your goal is to maximize the length of the remaining string ... |
def filter_words_by_length(word_list, min_length):
return [word for word in word_list if len(word) >= min_length] | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function `filter_words_by_length` that takes a list of strings and an integer `min_length` as arguments and returns a new list containing only the strings that have a length greater than or equal to `min_length`.\nAnswer:\nLet's think step by step.\n",
"role": "user"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1527,
"level": 1,
"question": "Design a Python function `filter_words_by_length` that takes a list of strings and an integer `min_length` as arguments and returns a new list containing only the strings that have a length greater than or equal to `min_length`.",
"split": "train"
} |
import http.client
def perform_requests(host: str, requests: list[tuple[str, str, dict, bytes]]) -> dict:
result = {}
for request in requests:
method, url, headers, body = request
conn = None
try:
conn = http.client.HTTPConnection(host)
conn.request(method, url, ... | simplelr_Docs | [
{
"content": "Question:\n### HTTP Client Challenge\n\nUsing the `http.client` module in Python, write a function called `perform_requests` that performs a series of HTTP requests to a given server and handles both successful and erroneous responses.\n\n#### Function Signature\n```python\ndef perform_requests(ho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1528,
"level": 1,
"question": "### HTTP Client Challenge\n\nUsing the `http.client` module in Python, write a function called `perform_requests` that performs a series of HTTP requests to a given server and handles both successful and erroneous responses.\n\n#### Function Signature\... |
from collections import Counter
import heapq
def top_k_frequent(nums, k):
count = Counter(nums)
return [x[0] for x in heapq.nlargest(k, count.items(), key=lambda x: x[1])] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to return a list of the top k frequent elements in nums. You may return the answer in any order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1529,
"level": 1,
"question": "Write a python function to return a list of the top k frequent elements in nums. You may return the answer in any order.",
"split": "train"
} |
from collections import deque
def shortest_path_to_target(grid):
m = len(grid)
if m == 0:
return -1
n = len(grid[0])
if n == 0:
return -1
if grid[0][0] == 1:
return -1
if grid[0][0] == 2:
return 0
visited = [[False for _ in range(n)] for _ in range(... | simplelr_Apps | [
{
"content": "Question:\nYou are given a grid of size m x n where each cell in the grid can have one of three values:\n- 0 representing an empty cell,\n- 1 representing a wall,\n- 2 representing a target cell you want to reach.\n\nYou start from the top-left corner of the grid and you can move up, down, left, o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1530,
"level": 1,
"question": "You are given a grid of size m x n where each cell in the grid can have one of three values:\n- 0 representing an empty cell,\n- 1 representing a wall,\n- 2 representing a target cell you want to reach.\n\nYou start from the top-left corner of the grid... |
def search_pattern(main_str, pattern_str, case_sensitive=True):
if not pattern_str:
return []
indices = []
if not case_sensitive:
main_str = main_str.lower()
pattern_str = pattern_str.lower()
pattern_len = len(pattern_str)
main_len = len(main_str)
for i in range(main_len ... | simplelr_Filter | [
{
"content": "Question:\nI need to develop a feature in my Python application that will allow users to search for a pattern in a given string, but with an option for case sensitivity. The feature should be able to return all the start indices of the pattern occurrences, including overlapping ones. How can I imp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1531,
"level": 1,
"question": "I need to develop a feature in my Python application that will allow users to search for a pattern in a given string, but with an option for case sensitivity. The feature should be able to return all the start indices of the pattern occurrences, includ... |
def compress_string(uncompressed_string: str) -> str:
compressed_parts = []
count = 1
for i in range(1, len(uncompressed_string)):
if uncompressed_string[i] == uncompressed_string[i - 1]:
count += 1
else:
compressed_parts.append(uncompressed_string[i - 1] + str(c... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem: String Compression Algorithm\n\nYou are tasked with developing a string compression function commonly used in data transmission and storage systems. Your function needs to compress a given string by replacing sequences of the same character with a single character followed ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1532,
"level": 1,
"question": "### Problem: String Compression Algorithm\n\nYou are tasked with developing a string compression function commonly used in data transmission and storage systems. Your function needs to compress a given string by replacing sequences of the same characte... |
def book_room(bookings: dict, room_number: int, start_time: int, end_time: int) -> bool:
if start_time >= end_time:
return False
if room_number not in bookings:
bookings[room_number] = [(start_time, end_time)]
return True
else:
for (e_start, e_end) in bookings[room_number]:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Hotel Booking Management System:\n\nIn this task, you need to implement a small part of a booking management system for a hotel. This involves managing room reservations where each room can be booked for different time slots.\n\n#### Scenario:\nYou are writing software for a hotel t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1533,
"level": 1,
"question": "### Hotel Booking Management System:\n\nIn this task, you need to implement a small part of a booking management system for a hotel. This involves managing room reservations where each room can be booked for different time slots.\n\n#### Scenario:\nYou... |
def filter_expired_items(food_items, current_date):
current_tuple = tuple(map(int, current_date.split('-')))
result = []
for item in food_items:
exp_date_str = item[1]
exp_tuple = tuple(map(int, exp_date_str.split('-')))
if exp_tuple >= current_tuple:
result.append(item[0... | simplelr_Taco | [
{
"content": "Question:\nMaria is managing a food distribution center and needs to keep track of the food items and their expiration dates. She wants to write a function that will help her filter out the food items that have expired based on the current date.\n\nThe function `filter_expired_items` should take a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1534,
"level": 1,
"question": "Maria is managing a food distribution center and needs to keep track of the food items and their expiration dates. She wants to write a function that will help her filter out the food items that have expired based on the current date.\n\nThe function `... |
def common_elements(list1, list2):
set2 = set(list2)
seen = set()
result = []
for element in list1:
if element in set2 and element not in seen:
result.append(element)
seen.add(element)
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two lists as parameters. The function should compare the elements of both lists and return a new list containing only the elements that are common to both lists. The function should also be case-sensitive and should not return any duplicates.\nAnswer:\nLet's... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1535,
"level": 1,
"question": "Create a function that takes two lists as parameters. The function should compare the elements of both lists and return a new list containing only the elements that are common to both lists. The function should also be case-sensitive and should not ret... |
def smallest_lexicographical_string(s, num):
stack = []
for c in s:
while stack and num > 0 and c < stack[-1]:
stack.pop()
num -= 1
stack.append(c)
if num > 0:
stack = stack[:-num]
return ''.join(stack) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters, and an integer `num`. You need to form a new string by deleting exactly `num` characters from `s` such that the resulting string is the smallest possible string (lexicographically). Return _the lexicographically smalles... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1536,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters, and an integer `num`. You need to form a new string by deleting exactly `num` characters from `s` such that the resulting string is the smallest possible string (lexicographically). Re... |
def sort_string_by_characters(s):
# Convert each character to its corresponding number (a=1, b=2, ..., z=26)
numbers = [ord(c) - 96 for c in s]
# Sort the numbers in ascending order
numbers.sort()
# Convert the sorted numbers back to characters
sorted_chars = [chr(n + 96) for n in numbers]
#... | simplelr_Code_Contests | [
{
"content": "Question:\nEve is interested in sorting strings in a specific manner that alters their characters. She wants to perform operations on each character of the string to achieve the desired result. The operation consists of converting the character into its corresponding number from 1 to 26 ('a' becom... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1537,
"level": 1,
"question": "Eve is interested in sorting strings in a specific manner that alters their characters. She wants to perform operations on each character of the string to achieve the desired result. The operation consists of converting the character into its correspon... |
def convert_temperature(fahrenheit: float) -> tuple:
celsius = (fahrenheit - 32) * 5 / 9
kelvin = celsius + 273.15
rounded_celsius = round(celsius, 2)
rounded_kelvin = round(kelvin, 2)
return (rounded_celsius, rounded_kelvin) | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function named `convert_temperature` that converts a given temperature from Fahrenheit to Celsius and Kelvin. The function should accept a single float input, `fahrenheit`, representing the temperature in Fahrenheit, and should return a tuple containing th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1538,
"level": 1,
"question": "You are tasked with creating a function named `convert_temperature` that converts a given temperature from Fahrenheit to Celsius and Kelvin. The function should accept a single float input, `fahrenheit`, representing the temperature in Fahrenheit, and ... |
def key_with_max_value(dictionary):
if not dictionary:
return None
return max(dictionary, key=lambda k: dictionary[k]) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a dictionary as an input and returns the key with the maximum value in the dictionary.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1539,
"level": 1,
"question": "Create a function that takes a dictionary as an input and returns the key with the maximum value in the dictionary.",
"split": "train"
} |
def group_anagrams(strs: list[str]) -> list[list[str]]:
anagrams = {}
for s in strs:
key = ''.join(sorted(s))
if key in anagrams:
anagrams[key].append(s)
else:
anagrams[key] = [s]
return list(anagrams.values()) | simplelr_Algorithm | [
{
"content": "Question:\n### Group Anagrams - Hash Map Challenge\n\n**Context**:\nYou are given a list of strings, and you need to group the anagrams together. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1540,
"level": 1,
"question": "### Group Anagrams - Hash Map Challenge\n\n**Context**:\nYou are given a list of strings, and you need to group the anagrams together. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all t... |
from typing import List
def rotate_matrix(image: List[List[int]]) -> None:
n = len(image)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
image[i][j], image[j][i] = image[j][i], image[i][j]
# Reverse each row
for row in image:
row.reverse() | simplelr_Data_Structure | [
{
"content": "Question:\n### Rotating Matrix Problem\n\nYou are working as a developer for a graphics software company. One of the tasks at hand is to rotate images efficiently. Each image is represented by an n x n matrix of integers, where each integer corresponds to the pixel value.\n\nWrite a function **rot... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1541,
"level": 1,
"question": "### Rotating Matrix Problem\n\nYou are working as a developer for a graphics software company. One of the tasks at hand is to rotate images efficiently. Each image is represented by an n x n matrix of integers, where each integer corresponds to the pix... |
def filter_duplicates(input_list):
seen = set()
result = []
for item in input_list:
if item not in seen:
result.append(item)
seen.add(item)
return result | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function to filter out duplicate elements from a list while maintaining the original order?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1542,
"level": 1,
"question": "How can I create a Python function to filter out duplicate elements from a list while maintaining the original order?",
"split": "train"
} |
def is_perfect_square(a, b):
return a ** 2 == b | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two parameters, `a` and `b`, which are positive integers. The function should check if `b` is a perfect square of `a`. If it is, return `True`. Otherwise, return `False`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1543,
"level": 1,
"question": "Create a function that takes two parameters, `a` and `b`, which are positive integers. The function should check if `b` is a perfect square of `a`. If it is, return `True`. Otherwise, return `False`.",
"split": "train"
} |
def square_list(numbers):
return [num ** 2 for num in numbers] | simplelr_Filter | [
{
"content": "Question:\nI need to write a function that can iterate through a list of integers and return a new list containing the squares of the original numbers. How can I do that in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1544,
"level": 1,
"question": "I need to write a function that can iterate through a list of integers and return a new list containing the squares of the original numbers. How can I do that in Python?",
"split": "train"
} |
import math
def count_digits(n: int) -> int:
n = abs(n)
if n == 0:
return 1
return int(math.log10(n)) + 1 | simplelr_Data_Structure | [
{
"content": "Question:\n# Coding Assessment Question\n\n## Objective\nWrite a function to determine the number of digits present in a given integer. This task will test your understanding of logarithms and edge cases for special values such as zero and negative numbers.\n\n## Question\n### Problem Statement\nI... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1545,
"level": 1,
"question": "# Coding Assessment Question\n\n## Objective\nWrite a function to determine the number of digits present in a given integer. This task will test your understanding of logarithms and edge cases for special values such as zero and negative numbers.\n\n##... |
def find_largest(a, b, c):
if a >= b and a >= c:
return a
elif b >= c:
return b
else:
return c | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the largest of three numbers. The function should take three integer arguments and return the largest of them.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1546,
"level": 1,
"question": "Write a function to find the largest of three numbers. The function should take three integer arguments and return the largest of them.",
"split": "train"
} |
import itertools
def unique_permutations(s):
return sorted({''.join(p) for p in itertools.permutations(s)})
| simplelr_Taco | [
{
"content": "Question:\nAlex is working on a new project that involves generating all possible permutations of a given string. However, due to the specific requirements of his project, he only needs the permutations where all characters are unique. To simplify his task, he also wants to sort the resulting perm... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1547,
"level": 1,
"question": "Alex is working on a new project that involves generating all possible permutations of a given string. However, due to the specific requirements of his project, he only needs the permutations where all characters are unique. To simplify his task, he al... |
import re
def parse_log_entries(log_entries):
# Compile the regex pattern to match each log entry's components
pattern = re.compile(
r'^(\d+\.\d+\.\d+\.\d+)\s+-\s+([^\s]+)\s+\[([^\]]+)\]\s+"(.*?)"\s+(\d+)\s+(\d+)$'
)
result = []
for log in log_entries:
match = pattern.match(log... | simplelr_Docs | [
{
"content": "Question:\nParsing and Analyzing Log Entries\n\n#### Objective\nThe goal of this exercise is to write a Python function that uses regular expressions to parse and analyze log entries from a web server. This will test your understanding of pattern compilation, grouping, and extracting information u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1548,
"level": 1,
"question": "Parsing and Analyzing Log Entries\n\n#### Objective\nThe goal of this exercise is to write a Python function that uses regular expressions to parse and analyze log entries from a web server. This will test your understanding of pattern compilation, gro... |
def last_task_position(n, robots):
zero_pos = None
for i in range(n):
if robots[i] == 0:
zero_pos = i
break
if zero_pos is None:
return n
if zero_pos == 0:
return -1
else:
return zero_pos | simplelr_Code_Contests | [
{
"content": "Question:\nA manufacturing company has an assembly line with various robots performing tasks. Each robot either performs a task or passes the item to the next robot. However, there's a twist: some robots on the line malfunction and pass a faulty item that cannot be repaired. The goal is to identif... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1549,
"level": 1,
"question": "A manufacturing company has an assembly line with various robots performing tasks. Each robot either performs a task or passes the item to the next robot. However, there's a twist: some robots on the line malfunction and pass a faulty item that cannot ... |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def exercise_plot(data: pd.DataFrame) -> None:
# Clean the data by removing any rows with missing values
data_clean = data.dropna()
# Set up the figure with a suitable size
plt.figure(figsize=(12, 6))
# Create the r... | simplelr_Docs | [
{
"content": "Question:\n### Seaborn Visualization Task\n\nYou are given a dataset, `exercise`, which contains exercise data with the following columns:\n- `id`: Identifier for the individual.\n- `time`: Time in minutes.\n- `pulse`: Pulse rate.\n- `diet`: Type of diet (e.g., 'low', 'med', 'high').\n- `kind`: Ty... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1550,
"level": 1,
"question": "### Seaborn Visualization Task\n\nYou are given a dataset, `exercise`, which contains exercise data with the following columns:\n- `id`: Identifier for the individual.\n- `time`: Time in minutes.\n- `pulse`: Pulse rate.\n- `diet`: Type of diet (e.g., '... |
def is_strictly_increasing(lst):
return all(lst[i] > lst[i-1] for i in range(1, len(lst))) | simplelr_Filter | [
{
"content": "Question:\nCould you write a Python function that checks if a given list of integers is strictly increasing? A list is considered strictly increasing if each element is greater than the preceding one.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1551,
"level": 1,
"question": "Could you write a Python function that checks if a given list of integers is strictly increasing? A list is considered strictly increasing if each element is greater than the preceding one.",
"split": "train"
} |
def length_of_longest_substring(s):
max_len = 0
left = 0
char_map = {}
for right in range(len(s)):
char = s[right]
if char in char_map and char_map[char] >= left:
left = char_map[char] + 1
char_map[char] = right
current_len = right - left + 1
if curren... | simplelr_Leetcode | [
{
"content": "Question:\n**Given a string `s` consisting of lowercase letters, you need to find the length of the longest substring without repeating characters. Implement a function that returns the length of such a substring.**\n\n_Write a function that takes a string `s` as input and returns an integer repre... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1552,
"level": 1,
"question": "**Given a string `s` consisting of lowercase letters, you need to find the length of the longest substring without repeating characters. Implement a function that returns the length of such a substring.**\n\n_Write a function that takes a string `s` as... |
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function to find the n-th Fibonacci number using memoization to improve efficiency. Explain the benefits of using memoization in this context.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1553,
"level": 1,
"question": "Create a Python function to find the n-th Fibonacci number using memoization to improve efficiency. Explain the benefits of using memoization in this context.",
"split": "train"
} |
def remove_target(nums, val):
nums[:] = [x for x in nums if x != val]
return len(nums) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove all instances of a target value from an integer array. The function should return the new length of the array after removal. The relative order of the elements should be preserved.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1554,
"level": 1,
"question": "Write a python function to remove all instances of a target value from an integer array. The function should return the new length of the array after removal. The relative order of the elements should be preserved.",
"split": "train"
} |
def twoSumSorted(nums, target):
left = 0
right = len(nums) - 1
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1
else:
right -= 1
return [] # ... | simplelr_Filter | [
{
"content": "Question:\nGiven an array of integers `nums`, sorted in ascending order, write a function `twoSumSorted` to find two numbers such that they add up to a specific `target`.\n\n Example:\n Input: `nums = [2, 7, 11, 15]`, `target = 9`\n Output: `[0, 1]`\n\n Constraints:\n `2 <= nums.length <... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1555,
"level": 1,
"question": "Given an array of integers `nums`, sorted in ascending order, write a function `twoSumSorted` to find two numbers such that they add up to a specific `target`.\n\n Example:\n Input: `nums = [2, 7, 11, 15]`, `target = 9`\n Output: `[0, 1]`\n\n Con... |
def allocate_seats(seating, num_seats):
if num_seats == 0:
return (False, seating.copy())
new_seating = list(seating)
n = len(new_seating)
for i in range(n - num_seats + 1):
if all(new_seating[i:i + num_seats]):
continue
if all(x == 0 for x in new_seating[i:... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nYou are tasked to develop a software module to aid a reservation system for a train service. The problem entails tracking the allocation of seats in such a way that a specified number of consecutive seats can be reserved together for a gr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1556,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario\nYou are tasked to develop a software module to aid a reservation system for a train service. The problem entails tracking the allocation of seats in such a way that a specified number of consecutive seat... |
def sum_within_range(lst, lower, upper):
total = 0
lower_bound = min(lower, upper)
upper_bound = max(lower, upper)
for num in lst:
if lower_bound <= num <= upper_bound:
total += num
return total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the sum of all elements in a given list that are within a specified range. The list, lower bound, and upper bound of the range will be passed to the function. The function should iterate through the list, check if a list element falls within the range, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1557,
"level": 1,
"question": "Create a function that calculates the sum of all elements in a given list that are within a specified range. The list, lower bound, and upper bound of the range will be passed to the function. The function should iterate through the list, check if a li... |
def twoSum(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_Taco | [
{
"content": "Question:\nGiven an array of integers nums and an integer target, return the indices of the two numbers such that they add up to the target value. You may assume that each input would have exactly one solution, and you may not use the same element twice.\n\nExample:\nInput:\n2\n4\n2 7 11 15\n9\n3\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1558,
"level": 1,
"question": "Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to the target value. You may assume that each input would have exactly one solution, and you may not use the same element twice.\n\nExamp... |
def find_primes(nums):
if not nums:
return []
max_num = max(nums)
if max_num < 2:
return []
sieve = [True] * (max_num + 1)
sieve[0] = sieve[1] = False
for current in range(2, int(max_num ** 0.5) + 1):
if sieve[current]:
for multiple in range(current * current,... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that, given a list of integers, returns a list of the integers that are prime numbers. Use the Sieve of Eratosthenes algorithm for an efficient solution. The function should be named `find_primes` and must handle lists with up to 10,000 elements. \n\n**Example:**\n\n```... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1559,
"level": 1,
"question": "Write a function that, given a list of integers, returns a list of the integers that are prime numbers. Use the Sieve of Eratosthenes algorithm for an efficient solution. The function should be named `find_primes` and must handle lists with up to 10,00... |
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
less = [x for x in arr if x < pivot]
equal = [x for x in arr if x == pivot]
greater = [x for x in arr if x > pivot]
return quicksort(less) + equal + quicksort(greater) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to sort a list using the quicksort algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1560,
"level": 1,
"question": "Write a function to sort a list using the quicksort algorithm.",
"split": "train"
} |
from typing import List
def maxSumWithOneDeletion(arr: List[int]) -> int:
if len(arr) == 0:
return 0 # Though according to constraints, this case won't occur as n >=1
if len(arr) == 1:
return arr[0]
prev_dp0 = arr[0]
prev_dp1 = float('-inf')
max_sum = prev_dp0
for i i... | simplelr_Code_Contests | [
{
"content": "Question:\nGiven an array of integers, find the maximum sum of a contiguous subarray with at most one deletion allowed. A deletion is removing one element from the subarray to maximize the sum. The subarray must contain at least one element.\n\nWrite a function `maxSumWithOneDeletion` that takes a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1561,
"level": 1,
"question": "Given an array of integers, find the maximum sum of a contiguous subarray with at most one deletion allowed. A deletion is removing one element from the subarray to maximize the sum. The subarray must contain at least one element.\n\nWrite a function `... |
def squares_of_positive_integers(numbers):
return [x ** 2 for x in numbers if x > 0] | simplelr_Apps | [
{
"content": "Question:\nWrite a function that accepts a list of integers and returns a new list containing the squares of all the positive integers from the original list. If there are no positive integers, the function should return an empty list.\n\nFor example: \nInput: [1, -2, 3, -4, 5] \nOutput: [1, 9, 25... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1562,
"level": 1,
"question": "Write a function that accepts a list of integers and returns a new list containing the squares of all the positive integers from the original list. If there are no positive integers, the function should return an empty list.\n\nFor example: \nInput: [1... |
def reverse_vowels(s: str) -> str:
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
vowels_collected = [char for char in s if char in vowels]
reversed_vowels = vowels_collected[::-1]
chars = list(s)
i = 0
for j in range(len(chars)):
if chars[j] in vowels:
chars[j] ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Reverse Vowels in a String\n\n**Scenario**:\nYou are building a text editor feature that allows users to process and reverse the positions of vowels in any given text string. The goal is to ensure that all vowels within the string are reversed, while all non-vowel characters remain ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1563,
"level": 1,
"question": "### Reverse Vowels in a String\n\n**Scenario**:\nYou are building a text editor feature that allows users to process and reverse the positions of vowels in any given text string. The goal is to ensure that all vowels within the string are reversed, whi... |
def is_valid_parentheses(s: str) -> bool:
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Code_Contests | [
{
"content": "Question:\nGiven a string consisting of opening and closing parentheses `(` and `)`, write a function to determine if the string is valid. A string is considered valid if parentheses are properly closed and nested.\n\n### Function signature\n```python\ndef is_valid_parentheses(s: str) -> bool:\n``... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1564,
"level": 1,
"question": "Given a string consisting of opening and closing parentheses `(` and `)`, write a function to determine if the string is valid. A string is considered valid if parentheses are properly closed and nested.\n\n### Function signature\n```python\ndef is_val... |
def can_form_by_repeating_substring(s):
n = len(s)
if n <= 1:
return False
for k in range(1, n // 2 + 1):
if n % k != 0:
continue
m = n // k
is_repeating = True
for i in range(1, m):
if s[i*k : (i+1)*k] != s[0:k]:
is_repeating =... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to determine if a given string can be formed by repeating a substring. A substring is a contiguous sequence of characters within a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1565,
"level": 1,
"question": "Write a python function to determine if a given string can be formed by repeating a substring. A substring is a contiguous sequence of characters within a string.",
"split": "train"
} |
def remove_duplicates(s):
seen = set()
result = []
for c in s:
if c not in seen:
result.append(c)
seen.add(c)
return ''.join(result) | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s`, which consists of lowercase letters, remove duplicates such that every letter appears only once in the resulting string but keep the order of their first occurrences. Return the resulting string with removed duplicates.\nAnswer:\nLet's think step by step.\n",
"ro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1566,
"level": 1,
"question": "Given a string `s`, which consists of lowercase letters, remove duplicates such that every letter appears only once in the resulting string but keep the order of their first occurrences. Return the resulting string with removed duplicates.",
"split":... |
def fourSum(arr, X):
arr.sort()
n = len(arr)
res = []
for i in range(n - 3):
if i > 0 and arr[i] == arr[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and arr[j] == arr[j - 1]:
continue
rem = X - arr[i] - arr[j]
... | simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers and an integer X, find all unique quadruplets in the array which sum up to X. Each quadruplet should be sorted in ascending order and the list of all quadruplets should also be sorted lexicographically. \n\nExample 1:\nInput:\narr = [1, 0, -1, 0, -2, 2]\nX = 0... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1567,
"level": 1,
"question": "Given an array of integers and an integer X, find all unique quadruplets in the array which sum up to X. Each quadruplet should be sorted in ascending order and the list of all quadruplets should also be sorted lexicographically. \n\nExample 1:\nInput:... |
def convert_date_format(date_str: str, current_format: str, target_format: str) -> str:
# Determine current separator
current_sep = '/' if '/' in current_format else '-'
current_parts = current_format.split(current_sep)
date_parts = date_str.split(current_sep)
# Extract year, month, day
yea... | simplelr_Algorithm | [
{
"content": "Question:\n### Conversion Between Date Formats\n\nYou are tasked with implementing a function that converts a date from one string format to another. The input and output formats are given as arguments to the function. The possible formats are:\n\n- \"YYYY-MM-DD\": Year-Month-Day format, e.g., \"2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1568,
"level": 1,
"question": "### Conversion Between Date Formats\n\nYou are tasked with implementing a function that converts a date from one string format to another. The input and output formats are given as arguments to the function. The possible formats are:\n\n- \"YYYY-MM-DD\... |
def find_second_smallest(numbers):
unique = list(set(numbers))
if len(unique) < 2:
return None
unique.sort()
return unique[1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that can read a list of integers, remove any duplicates, and then find the second smallest number in the list. If there are no duplicates or the list has only one element, the function should return `None`. Write the function `find_second_smallest(numbers)`.\nAnswer:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1569,
"level": 1,
"question": "Create a function that can read a list of integers, remove any duplicates, and then find the second smallest number in the list. If there are no duplicates or the list has only one element, the function should return `None`. Write the function `find_se... |
def reverse_words(s: str) -> str:
words = s.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Algorithm | [
{
"content": "Question:\n### Implement a Function to Reverse Words in a String\nWrite a function named `reverse_words` that takes in a string, where each word is separated by a single space, and returns a new string with the order of the words reversed. \n\n### Function Signature\n```python\ndef reverse_words(s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1570,
"level": 1,
"question": "### Implement a Function to Reverse Words in a String\nWrite a function named `reverse_words` that takes in a string, where each word is separated by a single space, and returns a new string with the order of the words reversed. \n\n### Function Signat... |
def normalize_path(path: str) -> str:
# Split the path into components, ignoring empty strings
components = [p for p in path.split('/') if p != '']
stack = []
for part in components:
if part == '.':
continue
elif part == '..':
if stack:
stack.pop()... | simplelr_Algorithm | [
{
"content": "Question:\n### Question:\n\nYou are tasked with implementing a function to simulate a simplified version of a file system's path normalization process. Your task is to create a function `normalize_path` that takes a file path as input and returns the simplified canonical path.\n\n**Function Signat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1571,
"level": 1,
"question": "### Question:\n\nYou are tasked with implementing a function to simulate a simplified version of a file system's path normalization process. Your task is to create a function `normalize_path` that takes a file path as input and returns the simplified c... |
def all_even_numbers(numbers):
return all(num % 2 == 0 for num in numbers) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to check if a given list of numbers contains only even numbers. The function should return a boolean value (True if all numbers are even, False otherwise).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1572,
"level": 1,
"question": "Write a python function to check if a given list of numbers contains only even numbers. The function should return a boolean value (True if all numbers are even, False otherwise).",
"split": "train"
} |
def is_valid_sequence(s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(... | simplelr_Algorithm | [
{
"content": "Question:\nValid Parentheses Sequence\n\n**Context:**\nA common task in computer science is to ensure that sequences of various delimiters (like parentheses, brackets, and braces) are well-formed. A well-formed sequence means that all types of delimiters are correctly opened and closed in the prop... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1573,
"level": 1,
"question": "Valid Parentheses Sequence\n\n**Context:**\nA common task in computer science is to ensure that sequences of various delimiters (like parentheses, brackets, and braces) are well-formed. A well-formed sequence means that all types of delimiters are corr... |
from typing import List, Tuple
def sort_packets(packets: List[Tuple[int, int]]) -> List[int]:
sorted_pks = sorted(packets, key=lambda x: x[1])
return [pk[0] for pk in sorted_pks] | simplelr_Codeforces | [
{
"content": "Question:\nAmy is a software developer at a tech company. Her team is building a data processing system that processes data in batches. Each batch consists of a sequence of data packets. Each packet has a unique identifier and a timestamp when it was created. The packets in a batch are not necessa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1574,
"level": 1,
"question": "Amy is a software developer at a tech company. Her team is building a data processing system that processes data in batches. Each batch consists of a sequence of data packets. Each packet has a unique identifier and a timestamp when it was created. The... |
def check_and_update_list(num, lst):
if num in lst:
return [n for n in lst if n != num]
else:
return lst + [num]
# Test the function
numbers = [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4]
print(check_and_update_list(5, numbers)) | simplelr_Filter | [
{
"content": "Question:\nI need to check if a certain number exists in a list. If the number doesn't exist, it should be added to the list. If the number already exists, it should be removed from the list. \n\nHere's my list: `[1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4]`. \n\nI'm checking for the number 5. \n\nH... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1575,
"level": 1,
"question": "I need to check if a certain number exists in a list. If the number doesn't exist, it should be added to the list. If the number already exists, it should be removed from the list. \n\nHere's my list: `[1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4]`. \n\nI... |
from sklearn.preprocessing import MultiLabelBinarizer
import numpy as np
def preprocess_movie_genres(movie_titles, movie_genres):
"""
Preprocess the movie genres to create a binary indicator matrix.
Parameters:
movie_titles (list of str): List of movie titles.
movie_genres (list of list of str... | simplelr_Docs | [
{
"content": "Question:\n### Question:\n\nYou are given a dataset containing information about multiple movies and their respective genres. Each movie can belong to multiple genres. Your task is to preprocess this data to train a machine learning model that predicts the genres of a given movie.\n\n**Input:**\n-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1576,
"level": 1,
"question": "### Question:\n\nYou are given a dataset containing information about multiple movies and their respective genres. Each movie can belong to multiple genres. Your task is to preprocess this data to train a machine learning model that predicts the genres... |
def contains_palindrome(lst):
return any(s == s[::-1] for s in lst) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that checks if a given list of strings contains at least one string that is a palindrome. A palindrome is a string that reads the same forward and backward.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1577,
"level": 1,
"question": "Write a Python function that checks if a given list of strings contains at least one string that is a palindrome. A palindrome is a string that reads the same forward and backward.",
"split": "train"
} |
def find_first_occurrence(arr, target):
low = 0
high = len(arr) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
result = mid
high = mid - 1 # Look for earlier occurrences in the left half
elif arr[mid] < target:
... | simplelr_Filter | [
{
"content": "Question:\nGiven a sorted array of integers, write a Python function that finds the index of the first occurrence of a given target value. If the target is not found, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1578,
"level": 1,
"question": "Given a sorted array of integers, write a Python function that finds the index of the first occurrence of a given target value. If the target is not found, return -1.",
"split": "train"
} |
def reverse_and_uppercase(sentence):
return ' '.join(word.upper() for word in reversed(sentence.split())) | simplelr_Package | [
{
"content": "Question:\nYou need to write a function named `reverse_and_uppercase(sentence)` that takes a single string argument representing a sentence. This function should reverse the words in the sentence and convert all characters to uppercase. Words are defined as sequences of characters separated by spa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1579,
"level": 1,
"question": "You need to write a function named `reverse_and_uppercase(sentence)` that takes a single string argument representing a sentence. This function should reverse the words in the sentence and convert all characters to uppercase. Words are defined as seque... |
import os
def update_environment(env_vars: dict) -> int:
for var, value in env_vars.items():
os.environ[var] = value
return os.system("printenv")
| simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nTo assess your understanding of handling environment variables using the `os` module in Python, which provides a superset of the `posix` interface.\n\n#### Problem Statement:\nWrite a Python function `update_environment` that:\n- Takes a dictionary of environment variab... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1580,
"level": 1,
"question": "#### Objective:\nTo assess your understanding of handling environment variables using the `os` module in Python, which provides a superset of the `posix` interface.\n\n#### Problem Statement:\nWrite a Python function `update_environment` that:\n- Takes... |
def first_non_repeating_char(s):
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
for char in s:
if freq[char] == 1:
return char
return '' | simplelr_Apps | [
{
"content": "Question:\nWrite an efficient function that accepts a string and returns the first non-repeating character. For example, for the string \"swiss\", the function should return the character 'w'. If all characters are repeating, return an empty string. The function should make use of a single travers... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1581,
"level": 1,
"question": "Write an efficient function that accepts a string and returns the first non-repeating character. For example, for the string \"swiss\", the function should return the character 'w'. If all characters are repeating, return an empty string. The function ... |
def max_contiguous_sum(strengths):
max_current = max_global = strengths[0]
for num in strengths[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global | simplelr_Leetcode | [
{
"content": "Question:\nIn a kingdom, there are `n` knights and each knight has a unique strength value. The strengths of the knights are represented as an integer array `strengths` where `strengths[i]` is the strength of the `i-th` knight. The knights want to form a team such that the team's total strength is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1582,
"level": 1,
"question": "In a kingdom, there are `n` knights and each knight has a unique strength value. The strengths of the knights are represented as an integer array `strengths` where `strengths[i]` is the strength of the `i-th` knight. The knights want to form a team suc... |
def first_duplicate(nums):
seen = set()
for num in nums:
if num in seen:
return num
seen.add(num)
return None | simplelr_Filter | [
{
"content": "Question:\nGiven a list of integers, write a Python function that returns the first duplicate in the list. The first duplicate is defined as the first number that appears twice in the list. If no duplicates are found, return None.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1583,
"level": 1,
"question": "Given a list of integers, write a Python function that returns the first duplicate in the list. The first duplicate is defined as the first number that appears twice in the list. If no duplicates are found, return None.",
"split": "train"
} |
def rob(nums):
if not nums:
return 0
n = len(nums)
if n == 1:
return nums[0]
prev_prev = nums[0]
prev = max(nums[0], nums[1])
for i in range(2, n):
current = max(prev, prev_prev + nums[i])
prev_prev, prev = prev, current
return prev | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums` which represents the amount of money of each house in a street. All the houses are arranged in a linear fashion. A robber is planning to rob houses along the street, but he can't rob two adjacent houses because it would automatically alert the p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1584,
"level": 1,
"question": "You are given an array of integers `nums` which represents the amount of money of each house in a street. All the houses are arranged in a linear fashion. A robber is planning to rob houses along the street, but he can't rob two adjacent houses because... |
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_Evol | [
{
"content": "Question:\nGiven an array of integers that may contain both positive and negative numbers, devise a function that finds the subarray with the largest sum and returns that sum. Ensure that your solution takes into account edge cases such as arrays with only negative numbers or empty arrays. Additio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1585,
"level": 1,
"question": "Given an array of integers that may contain both positive and negative numbers, devise a function that finds the subarray with the largest sum and returns that sum. Ensure that your solution takes into account edge cases such as arrays with only negati... |
def next_divisible_by_3(n):
return 3 * ((n // 3) + 1) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the smallest integer that is larger than the input integer \\( n \\) and is divisible by 3. If there is no such integer, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1586,
"level": 1,
"question": "Write a python function to find the smallest integer that is larger than the input integer \\( n \\) and is divisible by 3. If there is no such integer, return -1.",
"split": "train"
} |
from typing import List
def moving_average(nums: List[int], k: int) -> List[float]:
if not nums:
return []
current_sum = 0.0
result = []
for i in range(len(nums)):
current_sum += nums[i]
if i >= k:
current_sum -= nums[i - k]
if i < k - 1:
avg = cu... | simplelr_Algorithm | [
{
"content": "Question:\n**Context:** In many applications, data often needs to be condensed or extracted based on specific criteria. For example, in signal processing or time series analysis, it is common to work with moving averages to understand trends over time.\n\n**Question:**\nWrite a function `moving_av... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1587,
"level": 1,
"question": "**Context:** In many applications, data often needs to be condensed or extracted based on specific criteria. For example, in signal processing or time series analysis, it is common to work with moving averages to understand trends over time.\n\n**Quest... |
def construct_directory_tree(paths: list) -> dict:
root = {}
for path in paths:
parts = path.split('/')
current = root
for i in range(len(parts) - 1):
part = parts[i]
if part not in current:
current[part] = {}
current = current[part]
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge:\n\nGiven a list of strings representing file paths, create a function that organizes these paths into a hierarchical directory structure. Each path is made up of directory names separated by the '/' character. Your task is to construct a nested dictionary where eac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1588,
"level": 1,
"question": "### Coding Challenge:\n\nGiven a list of strings representing file paths, create a function that organizes these paths into a hierarchical directory structure. Each path is made up of directory names separated by the '/' character. Your task is to cons... |
import math
def lcm(a, b):
if a == 0 or b == 0:
return 0
return abs(a * b) // math.gcd(a, b) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to return the least common multiple (LCM) of two numbers, a and b.你能帮我用Python编写一个求两个数a和b的最小公倍数的函数吗?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1589,
"level": 1,
"question": "Write a function to return the least common multiple (LCM) of two numbers, a and b.你能帮我用Python编写一个求两个数a和b的最小公倍数的函数吗?",
"split": "train"
} |
def sort_sublists(lst, iv):
n = len(lst)
for i in range(n):
if lst[i][1] != iv:
continue
# Find the index of the minimum eligible sublist starting from i
min_idx = i
min_val = lst[i][0]
for j in range(i, n):
if lst[j][1] == iv and lst[j][0] < min_v... | simplelr_Filter | [
{
"content": "Question:\nI have a list of lists in Python, and I need to sort the sublists based on the first element of each sublist, but only if one condition is met: the second element in the sublist should be equal to a certain value, let's call it `iv`. \n\nFor instance, if `iv` is 5, I would only sort the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1590,
"level": 1,
"question": "I have a list of lists in Python, and I need to sort the sublists based on the first element of each sublist, but only if one condition is met: the second element in the sublist should be equal to a certain value, let's call it `iv`. \n\nFor instance, ... |
def binary_search(nums, target):
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif target < nums[mid]:
right = mid - 1
else:
left = mid + 1
return -1 | simplelr_Filter | [
{
"content": "Question:\nYou are given a sorted array of unique integers and a target integer. You need to find the index of the target integer in the array. If the target integer is not found in the array, return -1.\n\nExample:\n\n```\nInput: nums = [2, 5, 7, 8, 11, 12], target = 7\nOutput: 2\n```\n\nConstrai... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1591,
"level": 1,
"question": "You are given a sorted array of unique integers and a target integer. You need to find the index of the target integer in the array. If the target integer is not found in the array, return -1.\n\nExample:\n\n```\nInput: nums = [2, 5, 7, 8, 11, 12], tar... |
def max_subarray_sum(arr):
if not arr:
return 0 # or return None based on requirements
current_max = max_sum = arr[0]
for number in arr[1:]:
current_max = max(number, current_max + number)
if current_max > max_sum:
max_sum = current_max
return max_sum | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function that calculates the maximum sum of any contiguous subarray within a one-dimensional numeric array? This is essentially solving the Maximum Subarray Problem.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1592,
"level": 1,
"question": "Can you provide a Python function that calculates the maximum sum of any contiguous subarray within a one-dimensional numeric array? This is essentially solving the Maximum Subarray Problem.",
"split": "train"
} |
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for i in range(2, n + 1):
c = a + b
a = b
b = c
return b | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a positive integer `n` and returns the `n`-th Fibonacci number. The Fibonacci sequence is defined as follows:\n- F(0) = 0\n- F(1) = 1\n- F(n) = F(n-1) + F(n-2) for n > 1\n\nOptimize your solution for efficiency, ensuring the function can handle relatively lar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1593,
"level": 1,
"question": "Write a function that takes a positive integer `n` and returns the `n`-th Fibonacci number. The Fibonacci sequence is defined as follows:\n- F(0) = 0\n- F(1) = 1\n- F(n) = F(n-1) + F(n-2) for n > 1\n\nOptimize your solution for efficiency, ensuring the... |
def count_words(sentence):
return len(sentence.split())
# Example usage:
print(count_words("Hello world, this is a test.")) # Output: 5 | simplelr_Filter | [
{
"content": "Question:\nHow can I count the number of words in a sentence using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1594,
"level": 1,
"question": "How can I count the number of words in a sentence using Python?",
"split": "train"
} |
def separateAndConcatenate(s):
letters = ''
digits = ''
for char in s:
if char.isalpha():
letters += char
elif char.isdigit():
digits += char
return letters + digits
| simplelr_Taco | [
{
"content": "Question:\nYou are given a string that contains both alphabetical characters and digits. Your task is to separate the alphabetic characters and the digits into two different strings and return them concatenated, with alphabets appearing first, followed by digits.\n\n#Examples:\n```\nseparateAndCon... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1595,
"level": 1,
"question": "You are given a string that contains both alphabetical characters and digits. Your task is to separate the alphabetic characters and the digits into two different strings and return them concatenated, with alphabets appearing first, followed by digits.... |
def evaluate_expression(expr: str) -> int:
terms = expr.split('+')
total = 0
for term in terms:
factors = term.split('*')
product = 1
for factor in factors:
product *= int(factor)
total += product
return total | simplelr_Evol | [
{
"content": "Question:\nCreate a function that takes a string representing a mathematical expression involving addition and multiplication of non-negative integers (e.g., '3+5*2') and returns the evaluated result as an integer. The expression will be a valid mathematical expression without parentheses and invo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1596,
"level": 1,
"question": "Create a function that takes a string representing a mathematical expression involving addition and multiplication of non-negative integers (e.g., '3+5*2') and returns the evaluated result as an integer. The expression will be a valid mathematical expr... |
import bisect
def search_insert(array, val):
return bisect.bisect_left(array, val) | simplelr_Data_Structure | [
{
"content": "Question:\n### Coding Challenge\n\nYou are given a sorted integer array `array` and a target integer value `val`. Your task is to write a function `search_insert(array, val)` that finds the index at which `val` should be inserted to maintain the sorted order of the array. If `val` is already prese... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1597,
"level": 1,
"question": "### Coding Challenge\n\nYou are given a sorted integer array `array` and a target integer value `val`. Your task is to write a function `search_insert(array, val)` that finds the index at which `val` should be inserted to maintain the sorted order of t... |
from collections import deque
from typing import List
def sliding_window_maximum(nums: List[int], k: int) -> List[int]:
dq = deque()
result = []
for i in range(len(nums)):
# Remove indices from the back which have values less than the current value
while dq and nums[i] >= nums[dq[-1]]:
... | simplelr_Package | [
{
"content": "Question:\n**Sliding Window Maximum**\n\nYour task is to implement a function that finds the maximum value in a sliding window of a fixed size for a given list of integers. The sliding window moves from the left end of the list to the right end, one position at a time, and you must return a list o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1598,
"level": 1,
"question": "**Sliding Window Maximum**\n\nYour task is to implement a function that finds the maximum value in a sliding window of a fixed size for a given list of integers. The sliding window moves from the left end of the list to the right end, one position at a... |
from bs4 import BeautifulSoup
def count_unique_urls(html_docs):
result = {}
url_tags = {
'a': ['href'],
'link': ['href'],
'img': ['src', 'srcset'],
'script': ['src'],
'source': ['src', 'srcset'],
'embed': ['src'],
'object': ['data'],
'iframe': ['s... | simplelr_Filter | [
{
"content": "Question:\nPlease write a Python function that takes a list of HTML documents as input and returns a dictionary containing the number of unique URLs found in each document. The keys of the dictionary should be the index of the document in the input list, and the values should be the count of uniqu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1599,
"level": 1,
"question": "Please write a Python function that takes a list of HTML documents as input and returns a dictionary containing the number of unique URLs found in each document. The keys of the dictionary should be the index of the document in the input list, and the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.