target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
from collections import Counter
def sum_of_unique_abs_pairs(nums):
freq = Counter(nums)
processed = set()
sum_total = 0
for num in freq:
if num in processed:
continue
if num > 0:
if -num in freq:
sum_total += 2 * num
processed... | simplelr_Evol | [
{
"content": "Question:\nWrite a function `sum_of_unique_abs_pairs(nums)` that accepts a list of integers `nums` and returns the sum of the absolute values of the unique integer pairs that add up to zero. A pair `[a, -a]` and `[-a, a]` should be considered the same and only counted once.\n\nFor example:\n```pyt... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3600,
"level": 1,
"question": "Write a function `sum_of_unique_abs_pairs(nums)` that accepts a list of integers `nums` and returns the sum of the absolute values of the unique integer pairs that add up to zero. A pair `[a, -a]` and `[-a, a]` should be considered the same and only co... |
import heapq
def dijkstra(graph, start):
"""
Calculate the shortest path from the start node to all other nodes in a weighted graph.
Args:
graph (dict): Adjacency list representation of the graph.
start (node): The node from which to start the search.
Returns:
dict: A ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the shortest path in a weighted graph.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3601,
"level": 1,
"question": "Write a function to calculate the shortest path in a weighted graph.",
"split": "train"
} |
def shift_on_n_move(arr, n):
len_arr = len(arr)
if len_arr == 0:
return []
effective_shift = n % len_arr
result = []
for i in range(len_arr):
index_in_arr = (i - effective_shift) % len_arr
result.append(arr[index_in_arr])
return result | simplelr_Filter | [
{
"content": "Question:\nBuild a Python function `shift_on_n_move` where a list `arr` and an integer `n` are the parameters. The function should create a new list `result` which mirrors the length of `arr`, but each instance's value should shift forward or back by `n` index positions. Assuming `arr = ['a', 'b',... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3602,
"level": 1,
"question": "Build a Python function `shift_on_n_move` where a list `arr` and an integer `n` are the parameters. The function should create a new list `result` which mirrors the length of `arr`, but each instance's value should shift forward or back by `n` index po... |
import os
def get_total_directory_size(dir_path):
total = 0
for root, dirs, files in os.walk(dir_path):
for file in files:
file_path = os.path.join(root, file)
total += os.path.getsize(file_path)
return total | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that calculates the total size of all files in a given directory, including all its subdirectories. The function should return the total size in bytes.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3603,
"level": 1,
"question": "Write a Python function that calculates the total size of all files in a given directory, including all its subdirectories. The function should return the total size in bytes.",
"split": "train"
} |
def collatz(n):
"""Returns the Collatz sequence starting with n and the number of steps it took to reach 1."""
seq = [n]
steps = 0
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
seq.append(n)
steps += 1
return seq, steps
# Exampl... | simplelr_Filter | [
{
"content": "Question:\nHere is the code, followed by my problem and then my question.\n\n```python\ndef collatz(n):\n \"\"\"Returns the Collatz sequence starting with n.\"\"\"\n seq = [n] \n while n != 1:\n if n % 2 == 0:\n n = n // 2\n else:\n n = 3 * n + 1\n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3604,
"level": 1,
"question": "Here is the code, followed by my problem and then my question.\n\n```python\ndef collatz(n):\n \"\"\"Returns the Collatz sequence starting with n.\"\"\"\n seq = [n] \n while n != 1:\n if n % 2 == 0:\n n = n // 2\n else... |
def unique_paths(m, n):
k = min(m-1, n-1)
a = m + n - 2
result = 1
for i in range(1, k+1):
result = result * (a - k + i) // i
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to determine the number of unique paths in an `m x n` grid from the top-left corner to the bottom-right corner, given that you can only move right or down at each step.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3605,
"level": 1,
"question": "Write a function to determine the number of unique paths in an `m x n` grid from the top-left corner to the bottom-right corner, given that you can only move right or down at each step.",
"split": "train"
} |
def filter_and_sort_strings(string_list):
filtered = []
seen = set()
for s in string_list:
if not any(c.isdigit() for c in s):
upper_s = s.upper()
if upper_s not in seen:
filtered.append(upper_s)
seen.add(upper_s)
return sorted(filtered, re... | simplelr_Evol | [
{
"content": "Question:\nWrite a function `filter_and_sort_strings` that takes a list of strings as input and performs the following operations:\n1. Remove all strings that contain any digit.\n2. Convert the remaining strings to uppercase.\n3. Return the list of strings sorted in descending order.\n\nExample:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3606,
"level": 1,
"question": "Write a function `filter_and_sort_strings` that takes a list of strings as input and performs the following operations:\n1. Remove all strings that contain any digit.\n2. Convert the remaining strings to uppercase.\n3. Return the list of strings sorted... |
def fibonacci(n):
if n <= 0:
return []
fib_sequence = []
a, b = 0, 1
for _ in range(n):
fib_sequence.append(a)
a, b = b, a + b
return fib_sequence | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to generate Fibonacci numbers up to n terms.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3607,
"level": 1,
"question": "Write a python function to generate Fibonacci numbers up to n terms.",
"split": "train"
} |
def get_high_value_customers(transactions: list, threshold: float) -> list:
customer_totals = {}
for transaction in transactions:
customer_id, amount = transaction
customer_totals[customer_id] = customer_totals.get(customer_id, 0) + amount
high_value_customers = [id for id in customer_totals... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\nYou are given multiple transactions in a single day for various customers of a bank. Each transaction is represented by a tuple with the format (customer_id, transaction_amount). Your task is to determine the total transaction amount per customer and return the I... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3608,
"level": 1,
"question": "### Problem Statement:\nYou are given multiple transactions in a single day for various customers of a bank. Each transaction is represented by a tuple with the format (customer_id, transaction_amount). Your task is to determine the total transaction a... |
def filter_by_prefix(names: list[str], prefix: str) -> list[str]:
return [name for name in names if name.startswith(prefix)] | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\n#### Scenario:\nYou have been tasked with enhancing an existing web application's search feature. Your team is currently working on optimizing a prefix-based search feature to help users quickly locate item names based on their initial characters. For this, you need to i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3609,
"level": 1,
"question": "### Question\n\n#### Scenario:\nYou have been tasked with enhancing an existing web application's search feature. Your team is currently working on optimizing a prefix-based search feature to help users quickly locate item names based on their initial ... |
def filter_words(words, char):
target = char.lower()
result = []
for word in words:
if target in word.lower():
result.append(word)
return result
| simplelr_Taco | [
{
"content": "Question:\n## Overview\n\nWrite a function that takes in a list of words and a single character, and returns a list of words that contain the given character. The function should be case-insensitive and maintain the original order of words in the input list.\n\n```python\nfilter_words([\"Apple\", ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3610,
"level": 1,
"question": "## Overview\n\nWrite a function that takes in a list of words and a single character, and returns a list of words that contain the given character. The function should be case-insensitive and maintain the original order of words in the input list.\n\n`... |
import heapq
def shortest_delivery_route(n: int, edges: list[tuple[int, int, int]], start: int) -> list[int]:
# Build adjacency list
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
# Initialize distances
distances = [float('inf')] * n
distances[start] = 0
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nA major shipping company needs to optimize delivery routes to minimize travel distance. The company uses a basic algorithm to determine the shortest path between multiple delivery points. Your task is to implement a simplified version of this algorithm using a w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3611,
"level": 1,
"question": "### Problem Statement\n\nA major shipping company needs to optimize delivery routes to minimize travel distance. The company uses a basic algorithm to determine the shortest path between multiple delivery points. Your task is to implement a simplified ... |
from typing import List
def longest_common_prefix(strs: List[str]) -> str:
if not strs:
return ""
min_len = min(len(s) for s in strs)
prefix = []
for i in range(min_len):
current_char = strs[0][i]
for s in strs[1:]:
if i >= len(s) or s[i] != current_char:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Longest Common Prefix\n\n**Given**: An array of strings containing N strings, each of length M.\n\n**Objective**: Write a function to find the longest common prefix (LCP) string amongst an array of strings.\n\n**Function Signature**:\n```python\ndef longest_common_prefix(strs: List[... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3612,
"level": 1,
"question": "### Longest Common Prefix\n\n**Given**: An array of strings containing N strings, each of length M.\n\n**Objective**: Write a function to find the longest common prefix (LCP) string amongst an array of strings.\n\n**Function Signature**:\n```python\nde... |
import re
from collections import Counter
from typing import List, Tuple
def most_frequent_words(file_path: str, n: int) -> List[Tuple[str, int]]:
with open(file_path, 'r') as f:
text = f.read()
text_lower = text.lower()
words = re.findall(r'[a-z]+', text_lower)
word_counts = Counter(... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nWrite a function that generates a report of the top `n` occurring words in a given text file. The report should include the word and its frequency, sorted by frequency in descending order. \n\n### Function Signature\n\n```python\ndef most_frequent_words(file_pat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3613,
"level": 1,
"question": "### Problem Statement\n\nWrite a function that generates a report of the top `n` occurring words in a given text file. The report should include the word and its frequency, sorted by frequency in descending order. \n\n### Function Signature\n\n```pytho... |
def processTickets(tickets):
ticket_list = []
for ticket in tickets:
name, priority = ticket.split(':')
ticket_list.append((int(priority), name))
ticket_list.sort()
return [item[1] for item in ticket_list] | simplelr_Leetcode | [
{
"content": "Question:\nA company has an automated ticket processor that processes customer service tickets. Each ticket is represented as a string and contains the name of the customer who submitted the ticket and a priority level separated by a colon. The priority levels are represented as integers, where a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3614,
"level": 1,
"question": "A company has an automated ticket processor that processes customer service tickets. Each ticket is represented as a string and contains the name of the customer who submitted the ticket and a priority level separated by a colon. The priority levels ar... |
import re
def is_palindrome(s):
cleaned = re.sub('[^a-zA-Z0-9]', '', s).lower()
return cleaned == cleaned[::-1] | simplelr_Filter | [
{
"content": "Question:\nDesign a program that checks if a given string is a palindrome, ignoring case sensitivity and non-alphanumeric characters. For example, the phrase \"A man, a plan, a canal, Panama!\" should be recognized as a palindrome.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3615,
"level": 1,
"question": "Design a program that checks if a given string is a palindrome, ignoring case sensitivity and non-alphanumeric characters. For example, the phrase \"A man, a plan, a canal, Panama!\" should be recognized as a palindrome.",
"split": "train"
} |
def reverse_integer(x):
if x == 0:
return 0
sign = 1 if x > 0 else -1
num = abs(x)
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num = num // 10
reversed_num *= sign
if reversed_num < -2**31 or reversed_num > (2**31 ... | simplelr_Apps | [
{
"content": "Question:\nGiven a 32-bit signed integer x, write a function that returns x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then the function should return 0.\n\nExample 1:\n\nInput:\nx = 123\n\nOutput:\n321\n\nExample 2:\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3616,
"level": 1,
"question": "Given a 32-bit signed integer x, write a function that returns x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then the function should return 0.\n\nExample 1:\n\nInput:\nx = 12... |
def max_subarray_sum(nums):
if not nums:
return 0 # According to the problem statement, this case won't occur as the subarray must have at least one element.
max_current = max_global = nums[0]
for num in nums[1:]:
temp = max_current + num
if num > temp:
max_current = num... | simplelr_Filter | [
{
"content": "Question:\nThis problem involves writing a program to process a list of integers and find the maximum sum of a contiguous subarray (a subarray is a contiguous part of an array). The subarray must have at least one element. The program should return the maximum sum of a subarray.\n\n### Example 1:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3617,
"level": 1,
"question": "This problem involves writing a program to process a list of integers and find the maximum sum of a contiguous subarray (a subarray is a contiguous part of an array). The subarray must have at least one element. The program should return the maximum su... |
import heapq
def find_kth_largest(nums, k):
heap = []
for num in nums:
if len(heap) < k:
heapq.heappush(heap, num)
else:
if num > heap[0]:
heapq.heappop(heap)
heapq.heappush(heap, num)
return heap[0] | simplelr_Apps | [
{
"content": "Question:\nGiven an array of distinct integers and an integer k, you need to return the k-th largest element in the array. You must solve this problem without using any sorting algorithm explicitly, aiming to maintain an average time complexity better than O(n log n).\n\nNote: The k-th largest ele... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3618,
"level": 1,
"question": "Given an array of distinct integers and an integer k, you need to return the k-th largest element in the array. You must solve this problem without using any sorting algorithm explicitly, aiming to maintain an average time complexity better than O(n lo... |
from typing import List, Tuple, Dict
def update_stock(sales: List[Tuple[str, int]], stock: Dict[str, int]) -> Dict[str, int]:
stock_copy = stock.copy()
for product, qty in sales:
current_stock = stock_copy[product]
if current_stock >= qty:
stock_copy[product] -= qty
return stock... | simplelr_Algorithm | [
{
"content": "Question:\n### Context:\nA system for managing an inventory of products needs a function to update stock levels after a sales transaction. The function must process multiple sales and ensure that the stock levels are never negative. If a sale quantity exceeds the available stock, the transaction s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3619,
"level": 1,
"question": "### Context:\nA system for managing an inventory of products needs a function to update stock levels after a sales transaction. The function must process multiple sales and ensure that the stock levels are never negative. If a sale quantity exceeds the... |
def least_frequent_char(s):
if not s:
return ""
freq = {}
first_occurrence = {}
for index, char in enumerate(s):
if char not in freq:
freq[char] = 1
first_occurrence[char] = index
else:
freq[char] += 1
min_freq = min(freq.val... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes in a string and returns the character that appears the least number of times. If there are multiple characters with the same minimum frequency, return the one that appears first in the string.\n\nExample:\n```\n\"minimum\" => 'm'\n\"alphabet\" => 'l'\n```\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3620,
"level": 1,
"question": "Write a function that takes in a string and returns the character that appears the least number of times. If there are multiple characters with the same minimum frequency, return the one that appears first in the string.\n\nExample:\n```\n\"minimum\" =... |
from typing import List
from collections import Counter
def find_duplicates(input_list: List[int]) -> List[int]:
frequency = Counter(input_list)
duplicates = [num for num, count in frequency.items() if count > 1]
duplicates.sort()
return duplicates | simplelr_Package | [
{
"content": "Question:\nWrite a function `find_duplicates` that identifies all the duplicate elements in a list of integers and returns them in a sorted list. The function should use Python's standard libraries and should be efficient in terms of both time and space complexity.\n\nSpecifically, you should foll... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3621,
"level": 1,
"question": "Write a function `find_duplicates` that identifies all the duplicate elements in a list of integers and returns them in a sorted list. The function should use Python's standard libraries and should be efficient in terms of both time and space complexit... |
def cumulative_sum(lst):
result = []
sum_so_far = 0
for num in lst:
sum_so_far += num
result.append(sum_so_far)
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that will take a list of numbers and return a new list where each element is the sum of the elements in the original list up to that point. For example, if the input list is `[1, 2, 3, 4]`, the output should be `[1, 3, 6, 10]`.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3622,
"level": 1,
"question": "Create a function that will take a list of numbers and return a new list where each element is the sum of the elements in the original list up to that point. For example, if the input list is `[1, 2, 3, 4]`, the output should be `[1, 3, 6, 10]`.",
"s... |
def count_visible_buildings(buildings):
max_height = 0
count = 0
for building in reversed(buildings):
if building > max_height:
count += 1
max_height = building
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `n` positive integers, where each integer represents the height of a building. The heights are given in an array `buildings`, where `buildings[i]` is the height of the i-th building. A building is **visible** if there are no taller buildings to its right. Write a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3623,
"level": 1,
"question": "You are given a list of `n` positive integers, where each integer represents the height of a building. The heights are given in an array `buildings`, where `buildings[i]` is the height of the i-th building. A building is **visible** if there are no tal... |
def add_one_to_large_number(s):
carry = 1
i = len(s) - 1
new_str = []
while i >= 0 or carry > 0:
if i >= 0:
digit = int(s[i])
else:
digit = 0
total = digit + carry
carry = total // 10
res_digit = total % 10
new_str.append(str(res_di... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to add one to a巨大整数。这个整数以字符串的形式给出,并且它可能包含数百万位。由于内置的整数类型无法处理如此大的数字,因此您需要自己编写函数来处理这个操作。\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3624,
"level": 1,
"question": "Write a function to add one to a巨大整数。这个整数以字符串的形式给出,并且它可能包含数百万位。由于内置的整数类型无法处理如此大的数字,因此您需要自己编写函数来处理这个操作。",
"split": "train"
} |
def trap(height):
if not height or len(height) < 3:
return 0
n = len(height)
left_max = [0] * n
for i in range(1, n):
left_max[i] = max(left_max[i-1], height[i-1])
right_max = [0] * n
for i in range(n-2, -1, -1):
right_max[i] = max(right_max[i+1], height[i+1])
total =... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of non-negative integers representing the heights of blocks where the width of each block is 1. Rainwater can be trapped between these blocks after it rains. Write a function to compute how much water it can trap after raining. The function should take an array of i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3625,
"level": 1,
"question": "You are given a list of non-negative integers representing the heights of blocks where the width of each block is 1. Rainwater can be trapped between these blocks after it rains. Write a function to compute how much water it can trap after raining. The... |
def add_to_nested_dict(nested_dict, keys, value):
current = nested_dict
for key in keys[:-1]:
if key not in current:
current[key] = {}
current = current[key]
current[keys[-1]] = value
return nested_dict
| simplelr_Taco | [
{
"content": "Question:\nImplement a function `add_to_nested_dict` that takes a nested dictionary and a list of keys. The function should add a final key-value pair to this nested dictionary where the keys are the elements of the provided list and the value is a given value. If the nested structure does not exi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3626,
"level": 1,
"question": "Implement a function `add_to_nested_dict` that takes a nested dictionary and a list of keys. The function should add a final key-value pair to this nested dictionary where the keys are the elements of the provided list and the value is a given value. I... |
def is_rotated(original, rotated):
if len(original) != len(rotated):
return False
return rotated in (original + original)
| simplelr_Taco | [
{
"content": "Question:\nWrite a Python function to determine if a given substring is a rotated version of a string. A string is considered a rotated version of another string if you can obtain it by rotating the original string by any number of characters.\n\nInput\n\nThe function should take two strings, `ori... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3627,
"level": 1,
"question": "Write a Python function to determine if a given substring is a rotated version of a string. A string is considered a rotated version of another string if you can obtain it by rotating the original string by any number of characters.\n\nInput\n\nThe fun... |
def max_absolute_difference(arr):
if not arr:
return 0
current_min = current_max = arr[0]
for num in arr[1:]:
if num < current_min:
current_min = num
elif num > current_max:
current_max = num
return current_max - current_min | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer array as an input and returns the maximum absolute difference between any two elements in the array. The function should be optimized for performance.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3628,
"level": 1,
"question": "Create a function that takes an integer array as an input and returns the maximum absolute difference between any two elements in the array. The function should be optimized for performance.",
"split": "train"
} |
def cocktail_shaker_sort(arr):
n = len(arr)
start = 0
end = n - 1
while start < end:
swapped = False
# Forward pass
for i in range(start, end):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = True
if no... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nSorting algorithms are fundamental in computer science, used in various applications like organizing records, searching algorithms, and more. As an aspiring developer, it's critical to understand different sorting strategies and where they shine or fall short.\n\n### Task\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3629,
"level": 1,
"question": "### Scenario\nSorting algorithms are fundamental in computer science, used in various applications like organizing records, searching algorithms, and more. As an aspiring developer, it's critical to understand different sorting strategies and where the... |
def convert_to_roman(num: int) -> str:
roman_numerals = [
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(90, 'XC'),
(50, 'L'),
(40, 'XL'),
(10, 'X'),
(9, 'IX'),
(5, 'V'),
(4, 'IV'),
(1, 'I')
... | simplelr_Package | [
{
"content": "Question:\nCreate a function named `convert_to_roman` that takes an integer `num` and converts it into its corresponding Roman numeral. Roman numerals are represented by combinations of the following symbols: `I, V, X, L, C, D, M`. Each symbol has a value: `I = 1, V = 5, X = 10, L = 50, C = 100, D... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3630,
"level": 1,
"question": "Create a function named `convert_to_roman` that takes an integer `num` and converts it into its corresponding Roman numeral. Roman numerals are represented by combinations of the following symbols: `I, V, X, L, C, D, M`. Each symbol has a value: `I = 1... |
def is_balanced(s):
stack = []
closing_to_opening = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in ['(', '[', '{']:
stack.append(char)
elif char in closing_to_opening:
if not stack:
return False
top = stack.pop()
if to... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to check if a given string has balanced parentheses, brackets, and braces. The function should return `True` if the string is balanced, and `False` otherwise. The string may contain other characters besides the parentheses, brackets, and braces.\nAnswer:\nLet's t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3631,
"level": 1,
"question": "Write a Python function to check if a given string has balanced parentheses, brackets, and braces. The function should return `True` if the string is balanced, and `False` otherwise. The string may contain other characters besides the parentheses, brac... |
def celsius_to_fahrenheit(c_temperatures):
return [c * 9/5 + 32 for c in c_temperatures] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes as input an array of temperatures (in Celsius) and returns an array of temperatures converted to Fahrenheit. The conversion formula to convert from Celsius to Fahrenheit is \\(F = C \\times \\frac{9}{5} + 32\\).\nAnswer:\nLet's think step by step.\n",
"r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3632,
"level": 1,
"question": "Create a function that takes as input an array of temperatures (in Celsius) and returns an array of temperatures converted to Fahrenheit. The conversion formula to convert from Celsius to Fahrenheit is \\(F = C \\times \\frac{9}{5} + 32\\).",
"split"... |
import re
def reverse_words(sentence):
tokens = re.findall(r'\S+|\s+', sentence)
result = []
for token in tokens:
if token.strip():
reversed_word = ''
for i in range(len(token)-1, -1, -1):
reversed_word += token[i]
result.append(reversed_word)
... | simplelr_Data_Structure | [
{
"content": "Question:\nReverse Words in a Sentence\n\n#### Context:\nYou are developing a text processing tool that needs to perform various string manipulations. One of the functionalities required is to reverse each word in a sentence while retaining the original word order. To better understand different a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3633,
"level": 1,
"question": "Reverse Words in a Sentence\n\n#### Context:\nYou are developing a text processing tool that needs to perform various string manipulations. One of the functionalities required is to reverse each word in a sentence while retaining the original word orde... |
def find_mode(nums):
if not nums:
return []
freq = {}
for num in nums:
freq[num] = freq.get(num, 0) + 1
max_freq = max(freq.values())
modes = [num for num, count in freq.items() if count == max_freq]
modes.sort()
return modes | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the mode of an array of integers. The mode is the number that appears most frequently in the array. If there are multiple modes, return all of them in ascending order. If the array is empty, return an empty list.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3634,
"level": 1,
"question": "Write a function to calculate the mode of an array of integers. The mode is the number that appears most frequently in the array. If there are multiple modes, return all of them in ascending order. If the array is empty, return an empty list.",
"spli... |
def sieve_of_eratosthenes(n):
if n < 2:
return []
sieve = [True] * n
sieve[0] = sieve[1] = False
for i in range(2, int(n ** 0.5) + 1):
if sieve[i]:
sieve[i*i : n : i] = [False] * len(sieve[i*i : n : i])
primes = [i for i, is_prime in enumerate(sieve) if is_prime]
retu... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to generate a list of all prime numbers less than a given number n. The function should use the Sieve of Eratosthenes algorithm. The Sieve of Eratosthenes is an ancient algorithm used to find all prime numbers up to any given limit.\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3635,
"level": 1,
"question": "Write a python function to generate a list of all prime numbers less than a given number n. The function should use the Sieve of Eratosthenes algorithm. The Sieve of Eratosthenes is an ancient algorithm used to find all prime numbers up to any given li... |
def find_pairs_with_sum(arr, target):
seen = set()
result = []
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
if arr[i] + arr[j] == target:
a, b = sorted((arr[i], arr[j]))
if (a, b) not in seen:
seen.add((a, b))
... | simplelr_Apps | [
{
"content": "Question:\n### Task:\nWrite a function `find_pairs_with_sum` that takes an array of integers and a target sum, and returns a list of pairs (two-element tuples) that add up to the target sum. Each pair should be sorted in ascending order and the list of pairs should be sorted lexicographically.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3636,
"level": 1,
"question": "### Task:\nWrite a function `find_pairs_with_sum` that takes an array of integers and a target sum, and returns a list of pairs (two-element tuples) that add up to the target sum. Each pair should be sorted in ascending order and the list of pairs shou... |
def is_palindrome(s):
cleaned = ''.join([char.lower() for char in s if char.isalnum()])
return cleaned == cleaned[::-1] | simplelr_Filter | [
{
"content": "Question:\nA palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Here is a list of 5 palindromes:\n* Madam\n* A man, a plan, a canal, Panama!\n* Racecar\n* Radar\n* Level\nDesign a functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3637,
"level": 1,
"question": "A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Here is a list of 5 palindromes:\n* Madam\n* A man, a plan, a canal, Panama!\n* Racecar... |
from typing import List
def most_frequent_values(arr: List[int]) -> List[int]:
if not arr:
return []
freq = {}
order = []
for num in arr:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
order.append(num)
max_freq = max(fr... | simplelr_Data_Structure | [
{
"content": "Question:\n### Most Frequent Values in an Array\n\nGiven an array of integers, write a function to find the most frequent values in the array. The function should return a list containing all values that appear most frequently in the array. If there are multiple values with the same highest freque... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3638,
"level": 1,
"question": "### Most Frequent Values in an Array\n\nGiven an array of integers, write a function to find the most frequent values in the array. The function should return a list containing all values that appear most frequently in the array. If there are multiple ... |
from typing import List
from decimal import Decimal
def precise_sum(numbers: List[float]) -> Decimal:
total = Decimal(0)
for num in numbers:
total += Decimal(str(num))
return total
| simplelr_Docs | [
{
"content": "Question:\n### Floating-Point Arithmetic Precision\n\n**Background**:\nIn Python, floating-point numbers are represented using binary fractions which can introduce small errors in precision when representing certain decimal values. These errors can accumulate during arithmetic operations, leading ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3639,
"level": 1,
"question": "### Floating-Point Arithmetic Precision\n\n**Background**:\nIn Python, floating-point numbers are represented using binary fractions which can introduce small errors in precision when representing certain decimal values. These errors can accumulate dur... |
def max_sum_non_adjacent(nums: list[int]) -> int:
if not nums:
return 0
incl = 0
excl = 0
for num in nums:
new_incl = excl + num
new_excl = max(incl, excl)
incl, excl = new_incl, new_excl
return max(incl, excl) | simplelr_Package | [
{
"content": "Question:\n**Maximum Sum of Non-Adjacent Elements**\n\nYou need to write a function `max_sum_non_adjacent()` that calculates the maximum sum of non-adjacent elements in a given list of integers. Non-adjacent elements are elements that do not sit next to each other in the list.\n\n### Function Sign... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3640,
"level": 1,
"question": "**Maximum Sum of Non-Adjacent Elements**\n\nYou need to write a function `max_sum_non_adjacent()` that calculates the maximum sum of non-adjacent elements in a given list of integers. Non-adjacent elements are elements that do not sit next to each othe... |
def analyze_and_filter_data(data: list) -> dict:
result = {
"integers": [],
"floats": [],
"complex_numbers": [],
"strings": [],
"lists": [],
"dictionaries": [],
"sets": []
}
for item in data:
item_type = type(item)
if item_type == ... | simplelr_Docs | [
{
"content": "Question:\n**Problem: Analyze and Filter Mixed Data Types**\n\nYou are given a list of mixed data types containing numeric objects (integers, floating-point numbers, complex numbers), sequence objects (strings, lists, bytes), and container objects (dictionaries, sets). Your task is to implement a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3641,
"level": 1,
"question": "**Problem: Analyze and Filter Mixed Data Types**\n\nYou are given a list of mixed data types containing numeric objects (integers, floating-point numbers, complex numbers), sequence objects (strings, lists, bytes), and container objects (dictionaries, ... |
def two_sum(nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return [] | simplelr_Codeforces | [
{
"content": "Question:\nGiven an integer array nums and an integer target, return the indices of the two numbers such that they add up to the target. You may assume that each input array has exactly one solution.\n\nExample:\nInput: nums = [2, 7, 11, 15], target = 9\nOutput: [0, 1]\n\nExplanation: Because nums... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3642,
"level": 1,
"question": "Given an integer array nums and an integer target, return the indices of the two numbers such that they add up to the target. You may assume that each input array has exactly one solution.\n\nExample:\nInput: nums = [2, 7, 11, 15], target = 9\nOutput: ... |
def process_transactions(transactions):
balance = 0
for transaction in transactions:
parts = transaction.split(':')
amount = int(parts[2])
if parts[1] == 'D':
balance += amount
elif parts[1] == 'W':
balance -= amount
return balance | simplelr_Code_Contests | [
{
"content": "Question:\nYou are a software engineer tasked with developing a system to manage a simple banking ledger. The ledger consists of a list of transactions, where each transaction can be a deposit or a withdrawal. Each transaction also has a timestamp indicating when it occurred. You need to implement... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3643,
"level": 1,
"question": "You are a software engineer tasked with developing a system to manage a simple banking ledger. The ledger consists of a list of transactions, where each transaction can be a deposit or a withdrawal. Each transaction also has a timestamp indicating when... |
def max_in_array_using_stack(arr):
if not arr:
return None # Returns None if the array is empty
stack = []
for num in arr:
stack.append(num)
max_val = stack.pop()
while stack:
current = stack.pop()
if current > max_val:
max_val = current
return max_va... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in an array of numbers and returns the maximum number in the array using a stack.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3644,
"level": 1,
"question": "Create a function that takes in an array of numbers and returns the maximum number in the array using a stack.",
"split": "train"
} |
def find_first_appearance(main_str, char):
try:
return main_str.index(char)
except ValueError:
return -1 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the first appearance of a character in a string. The function should take two strings as input: the first string is the main string `main_str` and the second string is the character `char`. The function should return the index of the first occurrence of t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3645,
"level": 1,
"question": "Write a python function to find the first appearance of a character in a string. The function should take two strings as input: the first string is the main string `main_str` and the second string is the character `char`. The function should return the... |
def duplicate_consecutively(lst):
result = []
for num in lst:
result.append(num)
result.append(num)
return result | simplelr_Evol | [
{
"content": "Question:\nCreate an algorithm in Python that takes a list of integers and returns a new list with each element in the original list duplicated consecutively. For instance, given the input list [1, 2, 3], the function should return [1, 1, 2, 2, 3, 3]. Ensure that your solution has a linear time co... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3646,
"level": 1,
"question": "Create an algorithm in Python that takes a list of integers and returns a new list with each element in the original list duplicated consecutively. For instance, given the input list [1, 2, 3], the function should return [1, 1, 2, 2, 3, 3]. Ensure that... |
def configure_setup(option_mappings: dict) -> None:
"""
Updates the setup.cfg file with the given option mappings.
Parameters:
option_mappings (dict): A dictionary where keys are commands and values are dictionaries
of options to set for those commands.
Returns:
None... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nDemonstrate the ability to:\n1. Read and manipulate configuration files using Python.\n2. Interact with Distutils commands through the `setup.cfg` file.\n\n#### Problem Statement:\nYou are provided with a partially completed Python package that includes a `setup.cfg` fi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3647,
"level": 1,
"question": "#### Objective:\nDemonstrate the ability to:\n1. Read and manipulate configuration files using Python.\n2. Interact with Distutils commands through the `setup.cfg` file.\n\n#### Problem Statement:\nYou are provided with a partially completed Python pac... |
import random
def generate_random_time():
hour = random.randint(0, 23)
minute = random.randint(0, 59)
second = random.randint(0, 59)
return f"{hour:02d}:{minute:02d}:{second:02d}"
# Example usage:
random_time = generate_random_time()
print(random_time) | simplelr_Filter | [
{
"content": "Question:\nHow can I write a Python function that generates a random time in the format 'HH:MM:SS'?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3648,
"level": 1,
"question": "How can I write a Python function that generates a random time in the format 'HH:MM:SS'?",
"split": "train"
} |
def expectedValue(diceRolls):
points = {1: 10, 2: 2, 3: 5, 4: 8, 5: -6, 6: 0}
total = 0
for roll in diceRolls:
total += points[roll]
average = total / len(diceRolls)
return round(average, 2)
| simplelr_Taco | [
{
"content": "Question:\nYou are tasked with simulating a simplified dice game and calculating the expected value of a player's score based on specified dice rolls.\n\nIn this game, a player rolls a six-sided die a certain number of times. Each face of the die has a unique score value instead of the typical 1 t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3649,
"level": 1,
"question": "You are tasked with simulating a simplified dice game and calculating the expected value of a player's score based on specified dice rolls.\n\nIn this game, a player rolls a six-sided die a certain number of times. Each face of the die has a unique sco... |
def longest_two_char_substring(s: str) -> str:
if not s:
return ""
max_length = 0
start = 0
freq = {}
left = 0
for right in range(len(s)):
char = s[right]
if char in freq:
freq[char] += 1
else:
freq[char] = 1
# Ensure the window h... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question\n\n**Problem Statement**:\nYou are tasked with implementing a function to find the longest substring of a given string that contains exactly two distinct characters. If there are multiple substrings of the same length, return the one that appears first in the string.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3650,
"level": 1,
"question": "### Coding Question\n\n**Problem Statement**:\nYou are tasked with implementing a function to find the longest substring of a given string that contains exactly two distinct characters. If there are multiple substrings of the same length, return the on... |
def fill_grid(m, n):
# We will always return the grid filled with the checkerboard pattern.
grid = []
for i in range(m):
row = []
for j in range(n):
if (i + j) % 2 == 0:
row.append('X')
else:
row.append('.')
grid.append(row)
... | simplelr_Filter | [
{
"content": "Question:\nYou are given two positive integers, `m` and `n`, representing the dimensions of a 2D grid. You need to fill the grid with the characters 'X' and '.' such that no two 'X' are adjacent (either horizontally, vertically, or diagonally). Determine if it's possible to fill the grid consideri... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3651,
"level": 1,
"question": "You are given two positive integers, `m` and `n`, representing the dimensions of a 2D grid. You need to fill the grid with the characters 'X' and '.' such that no two 'X' are adjacent (either horizontally, vertically, or diagonally). Determine if it's ... |
def longest_increasing_subsequence(arr: list) -> int:
if not arr:
return 0
n = len(arr)
dp = [1] * n
for i in range(1, n):
for j in range(i):
if arr[j] < arr[i]:
if dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
return max(dp)
| simplelr_Taco | [
{
"content": "Question:\n> Design an algorithm that will take an input list of integers and output the length of the longest increasing subsequence (LIS). The longest increasing subsequence is a subsequence of a given sequence in which the subsequence's elements are in strictly increasing order, and the subsequ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3652,
"level": 1,
"question": "> Design an algorithm that will take an input list of integers and output the length of the longest increasing subsequence (LIS). The longest increasing subsequence is a subsequence of a given sequence in which the subsequence's elements are in strictl... |
def filter_by_starting_letter(strings, letter):
"""
This function takes a list of strings and a letter as input and returns a new list
containing only the strings from the input list that start with the specified letter.
Args:
strings: A list of strings.
letter: The letter to filter by... | simplelr_Filter | [
{
"content": "Question:\nFor the following exercises, complete the provided template:\n\n**Exercise 1:** **Write a function that takes a list of strings as input and returns a new list containing only the strings that start with a specific letter.**\n\n```python\ndef filter_by_starting_letter(strings, letter):\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3653,
"level": 1,
"question": "For the following exercises, complete the provided template:\n\n**Exercise 1:** **Write a function that takes a list of strings as input and returns a new list containing only the strings that start with a specific letter.**\n\n```python\ndef filter_by... |
def longest_subarray(nums):
if not nums:
return 0
# Split the array into runs of 0's and 1's
runs = []
current_val = nums[0]
count = 1
for num in nums[1:]:
if num == current_val:
count += 1
else:
runs.append((current_val, count))
curre... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums`, return the length of **the longest** subarray containing only `1`'s after deleting **one element** from `nums`. If all the elements in `nums` are `0`, return `0`. Note: The deletion operation can only be performed once, and the result should be the max... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3654,
"level": 1,
"question": "Given an array of integers `nums`, return the length of **the longest** subarray containing only `1`'s after deleting **one element** from `nums`. If all the elements in `nums` are `0`, return `0`. Note: The deletion operation can only be performed onc... |
def reverse_words(s):
words = []
current_word = ''
for char in s:
if char != ' ':
current_word += char
else:
if current_word:
words.append(current_word)
current_word = ''
if current_word:
words.append(current_word)
... | simplelr_Evol | [
{
"content": "Question:\nImplement a Python function to reverse the words in a given sentence without altering the word order. The function should handle cases with multiple spaces between words by reducing them to a single space in the output.\n\nExample: \nInput: \" The sky is blue \" \nOutput: \"Th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3655,
"level": 1,
"question": "Implement a Python function to reverse the words in a given sentence without altering the word order. The function should handle cases with multiple spaces between words by reducing them to a single space in the output.\n\nExample: \nInput: \" The ... |
def find_min_max(arr):
if not arr:
return None # or raise ValueError("Array is empty")
min_val = max_val = arr[0]
for num in arr[1:]:
if num < min_val:
min_val = num
elif num > max_val:
max_val = num
return (min_val, max_val) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the minimum and maximum values of an array of integers without using any built-in min and max functions but with only one pass through the array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3656,
"level": 1,
"question": "Write a python function to find the minimum and maximum values of an array of integers without using any built-in min and max functions but with only one pass through the array.",
"split": "train"
} |
import numpy as np
def set_zeros(matrix):
# Convert the input matrix to a NumPy array
arr = np.array(matrix)
# Find the indices where elements are zero
zero_indices = np.where(arr == 0)
# Extract unique rows and columns that contain zeros
rows_to_zero = np.unique(zero_indices[0])
... | simplelr_Filter | [
{
"content": "Question:\nI have a matrix of size n x m, and I want to set the entire row and column to 0's if an element in the matrix is 0. How can I do this in Python, preferably using NumPy for efficiency? Additionally, I need the final matrix to be returned as a list of lists. Could you provide me with a co... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3657,
"level": 1,
"question": "I have a matrix of size n x m, and I want to set the entire row and column to 0's if an element in the matrix is 0. How can I do this in Python, preferably using NumPy for efficiency? Additionally, I need the final matrix to be returned as a list of li... |
def get_next_state(current_state, command):
transitions = {
('state1', 'command1'): 'state2',
('state2', 'command2'): 'state3',
('state3', 'command3'): 'state4',
('state4', 'command4'): 'state1',
}
return transitions.get((current_state, command), current_state) | simplelr_Filter | [
{
"content": "Question:\nI have a system that uses a finite state machine. The system has several states and can be in only one state at a time. The system can transition from one state to another by sending a specific command. I want to implement a function that will return the next state of the system based o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3658,
"level": 1,
"question": "I have a system that uses a finite state machine. The system has several states and can be in only one state at a time. The system can transition from one state to another by sending a specific command. I want to implement a function that will return t... |
def maxProfit(prices: list[int]) -> int:
if len(prices) < 2:
return 0
min_price = prices[0]
max_profit = 0
for price in prices[1:]:
current_profit = price - min_price
if current_profit > max_profit:
max_profit = current_profit
if price < min_price:
... | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function to determine the maximum profit that can be achieved by buying and selling one stock over a given time period. The stock prices for each day are provided as an array, where the ith element represents the price of the stock on day i. You can only complete at most one tra... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3659,
"level": 1,
"question": "Write a function to determine the maximum profit that can be achieved by buying and selling one stock over a given time period. The stock prices for each day are provided as an array, where the ith element represents the price of the stock on day i. Yo... |
def run_length_encoding(s: str) -> str:
if not s:
return ""
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(current_char + str(count))
current_char = char
coun... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\nYou are given the task of converting a given string into a format where every substring of repeated characters is replaced by the character followed by the number of times it appears consecutively. This process is known as run-length encoding.\n\nYour function should adher... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3660,
"level": 1,
"question": "### Question\nYou are given the task of converting a given string into a format where every substring of repeated characters is replaced by the character followed by the number of times it appears consecutively. This process is known as run-length enco... |
import random
def roll_die(min_val=None, max_val=None):
if min_val is None and max_val is None:
min_val = 1
max_val = 20
elif min_val is None or max_val is None:
raise ValueError("Both min and max must be specified or both omitted")
if min_val > max_val:
raise ValueError("mi... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that simulates the rolling of a 20-sided die, but with a twist: the function should allow the user to specify a range of numbers (inclusive) that the die can land on. For example, if the user specifies a range of 5 to 15, the function should return a random inte... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3661,
"level": 1,
"question": "Create a Python function that simulates the rolling of a 20-sided die, but with a twist: the function should allow the user to specify a range of numbers (inclusive) that the die can land on. For example, if the user specifies a range of 5 to 15, the f... |
import math
def is_perfect_square(x):
if x < 0:
return False
s = math.isqrt(x)
return s * s == x | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given integer x is a perfect square.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3662,
"level": 1,
"question": "Write a function to check if a given integer x is a perfect square.",
"split": "train"
} |
def prime_factors(n: int) -> list:
if n == 1:
return []
factors = []
i = 2
while i * i <= n:
while n % i == 0:
factors.append(i)
n = n // i
i += 1
if n > 1:
factors.append(n)
return factors
| simplelr_Docs | [
{
"content": "Question:\n#### Problem Statement\n\nWrite a Python function `prime_factors(n: int) -> list` that takes an integer `n` and returns a list of all prime factors of `n`, sorted in ascending order.\n\nA prime factor is a factor of a number that is a prime number. Your function should:\n- Use basic ari... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3663,
"level": 1,
"question": "#### Problem Statement\n\nWrite a Python function `prime_factors(n: int) -> list` that takes an integer `n` and returns a list of all prime factors of `n`, sorted in ascending order.\n\nA prime factor is a factor of a number that is a prime number. You... |
from collections import Counter
def min_operations_to_distinct(s):
counts = Counter(s)
return sum(v - 1 for v in counts.values()) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` of lowercase English letters. You can perform the following operation on the string any number of times: Choose any character in the string and delete the nearest occurrence of that character to its right (if it exists). Your task is to determine the minimum n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3664,
"level": 1,
"question": "You are given a string `s` of lowercase English letters. You can perform the following operation on the string any number of times: Choose any character in the string and delete the nearest occurrence of that character to its right (if it exists). Your... |
import pandas as pd
import pathlib
def process_large_dataset(directory_path):
"""
Process large dataset efficiently and compute required metrics.
Parameters:
directory_path (str): The path to the directory containing parquet files.
Returns:
pd.DataFrame: A DataFrame contai... | simplelr_Docs | [
{
"content": "Question:\nYou are provided with a directory containing multiple parquet files, each containing data for a different year. Your task is to create a summary DataFrame that provides efficient memory usage by selectively loading columns, converting data types, and processing the data in chunks. Speci... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3665,
"level": 1,
"question": "You are provided with a directory containing multiple parquet files, each containing data for a different year. Your task is to create a summary DataFrame that provides efficient memory usage by selectively loading columns, converting data types, and p... |
def Repeat(portion: str, count: int, target: str) -> str:
"""
This function finds the longest prefix of 'portion' that is repeated 'count' times in 'target'.
Args:
portion (str): The string from which prefixes are considered.
count (int): The number of times a prefix should be repeated in 'target'.... | simplelr_Filter | [
{
"content": "Question:\n### Problem Description\nThe `Repeat` function takes three parameters: a string `portion`, an integer `count`, and a string `target`. This function finds the longest prefix of `portion` that is repeated `count` times in `target`.\n\n### Step-by-Step Solution\n1. **Step 1**: Initialize t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3666,
"level": 1,
"question": "### Problem Description\nThe `Repeat` function takes three parameters: a string `portion`, an integer `count`, and a string `target`. This function finds the longest prefix of `portion` that is repeated `count` times in `target`.\n\n### Step-by-Step So... |
def max_product(arr):
sorted_arr = sorted(arr, reverse=True)
return sorted_arr[0] * sorted_arr[1] | simplelr_Apps | [
{
"content": "Question:\nWrite a function to find the maximum product of two elements in an array of integers. The two elements must be different and should come from the array itself.\n\nExample 1:\n\nInput: [3, 4, 5, 2]\nOutput: 20\nExplanation: The maximum product is 4 * 5 = 20.\n\nExample 2:\n\nInput: [1, 5... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3667,
"level": 1,
"question": "Write a function to find the maximum product of two elements in an array of integers. The two elements must be different and should come from the array itself.\n\nExample 1:\n\nInput: [3, 4, 5, 2]\nOutput: 20\nExplanation: The maximum product is 4 * 5 ... |
def find_largest_element(arr):
if not arr:
return None
return max(arr) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the largest element in an array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3668,
"level": 1,
"question": "Write a python function to find the largest element in an array.",
"split": "train"
} |
def is_perfect_square(n):
if n < 1:
return False
low = 1
high = n
while low <= high:
mid = (low + high) // 2
mid_squared = mid * mid
if mid_squared == n:
return True
elif mid_squared < n:
low = mid + 1
else:
high = mid -... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if a given positive integer is a perfect square without using any string conversions, floating-point arithmetic, or bitwise operations. How should the function handle edge cases?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3669,
"level": 1,
"question": "Create a function that checks if a given positive integer is a perfect square without using any string conversions, floating-point arithmetic, or bitwise operations. How should the function handle edge cases?",
"split": "train"
} |
from typing import List
def custom_fibonacci(limit: int) -> List[int]:
"""
Generate a list of Fibonacci numbers up to a specified limit.
:param limit: The upper bound value for the Fibonacci sequence.
:return: A list of Fibonacci numbers up to and including the specified limit.
:raises ValueEr... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Implement a Custom Fibonacci Generator with Constraints\n\n**Scenario**:\nYou are developing a custom Fibonacci number generator for a financial application. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3670,
"level": 1,
"question": "### Question: Implement a Custom Fibonacci Generator with Constraints\n\n**Scenario**:\nYou are developing a custom Fibonacci number generator for a financial application. The Fibonacci sequence is a series of numbers where each number is the sum of th... |
def longest_consecutive_subsequence(nums):
if not nums:
return 0
s = set(nums)
max_length = 0
for num in nums:
if (num - 1) not in s:
current_length = 1
current_num = num
while current_num + 1 in s:
current_length += 1
c... | simplelr_Apps | [
{
"content": "Question:\nGiven a list of unique integers, find the length of the longest subsequence such that all elements of the subsequence are consecutive integers. The consecutive numbers can be in any order in the original list.\n\nExample 1:\nInput: [100, 4, 200, 1, 3, 2]\nOutput: 4\nExplanation:\nThe lo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3671,
"level": 1,
"question": "Given a list of unique integers, find the length of the longest subsequence such that all elements of the subsequence are consecutive integers. The consecutive numbers can be in any order in the original list.\n\nExample 1:\nInput: [100, 4, 200, 1, 3, ... |
from typing import List
def find_common_elements(list1: List[int], list2: List[int]) -> List[int]:
set2 = set(list2)
result = []
added = set()
for num in list1:
if num in set2 and num not in added:
result.append(num)
added.add(num)
return result | simplelr_Package | [
{
"content": "Question:\n**Problem Statement:**\n\nImplement a Python function called `find_common_elements` that takes two lists of integers and returns a list of integers that are common to both lists, without any duplicates. The order of the elements in the final list should correspond to the order they appe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3672,
"level": 1,
"question": "**Problem Statement:**\n\nImplement a Python function called `find_common_elements` that takes two lists of integers and returns a list of integers that are common to both lists, without any duplicates. The order of the elements in the final list shoul... |
from collections import defaultdict
def calculate_average_scores(students):
course_data = defaultdict(lambda: [0, 0]) # [total_score, count]
for student in students:
for course, score in student['courses'].items():
course_data[course][0] += score
course_data[course][1] += 1
... | simplelr_Evol | [
{
"content": "Question:\nImplement a function in Python that processes a list of student dictionaries and calculates the average score for each course. Each dictionary in the list represents a student and has a key `courses` that maps to a dictionary of the courses each student is enrolled in and the scores the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3673,
"level": 1,
"question": "Implement a function in Python that processes a list of student dictionaries and calculates the average score for each course. Each dictionary in the list represents a student and has a key `courses` that maps to a dictionary of the courses each studen... |
import seaborn as sns
import matplotlib.pyplot as plt
def analyze_plotting_context():
tips = sns.load_dataset("tips")
# Scatterplot in notebook context
sns.set_context("notebook")
plt.figure()
scatter_notebook = sns.scatterplot(x="total_bill", y="tip", data=tips)
scatter_notebook.set_title("No... | simplelr_Docs | [
{
"content": "Question:\n### Question\n\nYou are tasked with analyzing the effect of different plotting contexts on a dataset. Write a Python function that:\n\n1. Loads the 'tips' dataset from Seaborn.\n2. Configures the plotting context to \"notebook\" and generates a scatterplot of `total_bill` vs `tip` with ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3674,
"level": 1,
"question": "### Question\n\nYou are tasked with analyzing the effect of different plotting contexts on a dataset. Write a Python function that:\n\n1. Loads the 'tips' dataset from Seaborn.\n2. Configures the plotting context to \"notebook\" and generates a scatter... |
def merge_sorted_arrays(arr1, arr2):
i = j = 0
result = []
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
result.append(arr1[i])
i += 1
else:
result.append(arr2[j])
j += 1
# Add remaining elements from arr1
while i < len(... | simplelr_Apps | [
{
"content": "Question:\nYou are given two arrays, `arr1` and `arr2`, which are initially sorted in non-decreasing order. Write a function to merge these two arrays into a new array, sorted in non-decreasing order.\n\n## Examples\n```\narr1 = [1, 3, 5]\narr2 = [2, 4, 6]\n\nmerged array: [1, 2, 3, 4, 5, 6]\n```\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3675,
"level": 1,
"question": "You are given two arrays, `arr1` and `arr2`, which are initially sorted in non-decreasing order. Write a function to merge these two arrays into a new array, sorted in non-decreasing order.\n\n## Examples\n```\narr1 = [1, 3, 5]\narr2 = [2, 4, 6]\n\nmer... |
import datetime as dt
def generate_dates(start_date, end_date):
start = dt.datetime.strptime(start_date, "%Y-%m-%d")
end = dt.datetime.strptime(end_date, "%Y-%m-%d")
delta = (end - start).days
return [start + dt.timedelta(days=i) for i in range(delta + 1)]
start_date = "2022-01-01"
end_date = "20... | simplelr_Filter | [
{
"content": "Question:\nI have a list of start and end dates, e.g., 2022-01-01 and 2022-01-15. I want to generate all dates between these dates, inclusive. I would also like to convert these to datetime objects as well. \n\nHere is my code:\n```python\nimport datetime as dt\n\ndef generate_dates(start_date,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3676,
"level": 1,
"question": "I have a list of start and end dates, e.g., 2022-01-01 and 2022-01-15. I want to generate all dates between these dates, inclusive. I would also like to convert these to datetime objects as well. \n\nHere is my code:\n```python\nimport datetime as d... |
def reverse_sentence(sentence):
words = sentence.split(' ')
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words)
# Test cases
print(reverse_sentence("Hello World")) # Expected: "olleH dlroW"
print(reverse_sentence("Python is great")) # Expected: "nohtyP si taerg"
print(... | simplelr_Evol | [
{
"content": "Question:\nThe following Python code is intended to reverse a sentence while preserving the order of the words. However, it contains logical errors. Can you identify and fix them?\n\n```python\ndef reverse_sentence(sentence):\n words = sentence.split(' ')\n reversed_sentence = \"\"\n for ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3677,
"level": 1,
"question": "The following Python code is intended to reverse a sentence while preserving the order of the words. However, it contains logical errors. Can you identify and fix them?\n\n```python\ndef reverse_sentence(sentence):\n words = sentence.split(' ')\n ... |
def recursive_binary_search(sorted_list: list, target: int, left: int = 0, right: int = None) -> int:
if right is None:
right = len(sorted_list) - 1
if left > right:
return -1
middle = (left + right) // 2
if sorted_list[middle] == target:
return middle
elif sorted_list[middle... | simplelr_Algorithm | [
{
"content": "Question:\n### Implementing a Recursive Binary Search\n\nYou are tasked with implementing a recursive binary search function in Python. This function should take a sorted list and a target value, returning the index of the target value within the list, or `-1` if the target does not exist in the l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3678,
"level": 1,
"question": "### Implementing a Recursive Binary Search\n\nYou are tasked with implementing a recursive binary search function in Python. This function should take a sorted list and a target value, returning the index of the target value within the list, or `-1` if... |
def sum_of_list(numbers):
"""
Returns the sum of a list of numbers.
Args:
numbers (list): A list of numbers.
Returns:
int or float: The sum of the numbers in the list.
"""
return sum(numbers)
# Example usage:
if __name__ == "__main__":
numbers_list = [1, 2, 3, 4, 5... | simplelr_Filter | [
{
"content": "Question:\nIt seems like you're familiar with Python, could you provide a simple Python code snippet that demonstrates how to create a function that takes a list of numbers and returns the sum of those numbers?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3679,
"level": 1,
"question": "It seems like you're familiar with Python, could you provide a simple Python code snippet that demonstrates how to create a function that takes a list of numbers and returns the sum of those numbers?",
"split": "train"
} |
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1 # if target is not found
# E... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to implement Binary Search. What is Binary Search and how does it work?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3680,
"level": 1,
"question": "Write a function to implement Binary Search. What is Binary Search and how does it work?",
"split": "train"
} |
def is_sentence_palindrome(s: str) -> bool:
left = 0
right = len(s) - 1
while left < right:
# Move left pointer to the next alphanumeric character
while left < right and not s[left].isalnum():
left += 1
# Move right pointer to the previous alphanumeric character
w... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Description:\nYou are tasked with the function `is_sentence_palindrome(s)` that checks if a given sentence is a palindrome. A sentence palindrome is a string that reads the same backward as forward, considering only alphanumeric characters and ignoring cases.\n\n#### Your Task:\n1.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3681,
"level": 1,
"question": "#### Description:\nYou are tasked with the function `is_sentence_palindrome(s)` that checks if a given sentence is a palindrome. A sentence palindrome is a string that reads the same backward as forward, considering only alphanumeric characters and ign... |
def remove_duplicates(nums):
seen = set()
unique_list = []
for num in nums:
if num not in seen:
unique_list.append(num)
seen.add(num)
return unique_list | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to remove duplicates from a list of numbers while preserving the original order. The function should take a list of numbers as input and return a new list with only the unique elements, maintaining their original sequence. For example, if the input is `[4, 5, 4, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3682,
"level": 1,
"question": "Write a Python function to remove duplicates from a list of numbers while preserving the original order. The function should take a list of numbers as input and return a new list with only the unique elements, maintaining their original sequence. For e... |
from typing import List, Dict
def max_concurrent_processes(events: List[Dict[str, int]]) -> int:
event_list = []
for event in events:
start = event['start']
end = event['end']
event_list.append((start, 1))
event_list.append((end, -1))
# Sort by time, and for same times,... | simplelr_Package | [
{
"content": "Question:\nCreate a function that takes a list of events representing the lifetimes of various processes on a system and returns the maximum number of concurrent processes that were running at any given time. Each event in the list is represented as a dictionary with the following structure:\n\n``... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3683,
"level": 1,
"question": "Create a function that takes a list of events representing the lifetimes of various processes on a system and returns the maximum number of concurrent processes that were running at any given time. Each event in the list is represented as a dictionary ... |
def append_zeros(n, num_zeros):
return n * (10 ** num_zeros) | simplelr_Filter | [
{
"content": "Question:\nHere's a Python script that appends a specified number of zeros to the end of a given integer:\n```python\ndef append_zeros(n, num_zeros):\n s = str(n)\n zeroes = '0' * num_zeros\n result = s + zeroes\n return int(result)\n```\nHowever, the type of the input integer can be e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3684,
"level": 1,
"question": "Here's a Python script that appends a specified number of zeros to the end of a given integer:\n```python\ndef append_zeros(n, num_zeros):\n s = str(n)\n zeroes = '0' * num_zeros\n result = s + zeroes\n return int(result)\n```\nHowever, the... |
def largest_rectangle_area(heights):
stack = [-1]
max_area = 0
n = len(heights)
for i in range(n):
while stack[-1] != -1 and heights[i] < heights[stack[-1]]:
top = stack.pop()
if stack:
width = i - stack[-1] - 1
else:
width = i
... | simplelr_Taco | [
{
"content": "Question:\nV: Largest Rectangle in Histogram\n\nProblem Statement\n\nGiven an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.\n\nFor example, if you have heights = [2,1,5,6,2,3], the larg... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3685,
"level": 1,
"question": "V: Largest Rectangle in Histogram\n\nProblem Statement\n\nGiven an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.\n\nFor example, if you hav... |
def sum_of_all_subarrays(arr):
n = len(arr)
total = 0
for i in range(n):
contribution = arr[i] * (i + 1) * (n - i)
total += contribution
return total | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `arr` of length `n`. A **subarray** of `arr` is a contiguous non-empty sequence of elements within `arr`. You need to determine the sum of all possible subarrays of `arr`. Return the result as a single integer. For example, if `arr = [1, 2, 3]... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3686,
"level": 1,
"question": "You are given a **0-indexed** integer array `arr` of length `n`. A **subarray** of `arr` is a contiguous non-empty sequence of elements within `arr`. You need to determine the sum of all possible subarrays of `arr`. Return the result as a single intege... |
def list_differences(list1, list2):
result = []
min_length = min(len(list1), len(list2))
for i in range(min_length):
result.append(list1[i] - list2[i])
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in two lists of numbers and returns the list of differences between corresponding elements. If the lists differ in length, the function should return the difference list only up to the length of the shorter list.\nAnswer:\nLet's think step by step.\n",
"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3687,
"level": 1,
"question": "Create a function that takes in two lists of numbers and returns the list of differences between corresponding elements. If the lists differ in length, the function should return the difference list only up to the length of the shorter list.",
"split... |
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return [] | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums` and an integer `target`, return the indices of the two numbers in the array that add up to exactly `target`. Each input would have exactly one solution, and you may not use the same element twice. \n\nFor example, given nums = `[2, 7, 11, 15]` and targe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3688,
"level": 1,
"question": "Given an array of integers `nums` and an integer `target`, return the indices of the two numbers in the array that add up to exactly `target`. Each input would have exactly one solution, and you may not use the same element twice. \n\nFor example, give... |
def nim_game(n: int) -> str:
if n % 4 == 0:
return "You lose"
else:
return "You win" | simplelr_Apps | [
{
"content": "Question:\nYour task is to write a function that simulates a simplified version of the game of Nim. In this version, you start with a pile of n stones and take turns with your opponent removing between 1 to 3 stones inclusive from the pile on each turn. The player to remove the last stone wins. Yo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3689,
"level": 1,
"question": "Your task is to write a function that simulates a simplified version of the game of Nim. In this version, you start with a pile of n stones and take turns with your opponent removing between 1 to 3 stones inclusive from the pile on each turn. The playe... |
from typing import List
def product_except_self(nums: List[int]) -> List[int]:
n = len(nums)
# Initialize left and right product arrays with 1s
left_products = [1] * n
right_products = [1] * n
# Compute left products
for i in range(1, n):
left_products[i] = left_products[i - 1... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge: Product of Array Except Self\n\n#### Problem Statement\n\nYou are given an array of integers `nums`. Write a function `product_except_self(nums: List[int]) -> List[int]` that returns an array `output` such that `output[i]` is equal to the product of all the element... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3690,
"level": 1,
"question": "### Coding Challenge: Product of Array Except Self\n\n#### Problem Statement\n\nYou are given an array of integers `nums`. Write a function `product_except_self(nums: List[int]) -> List[int]` that returns an array `output` such that `output[i]` is equa... |
def remove_duplicates(lst):
seen = set()
result = []
for num in lst:
if num not in seen:
result.append(num)
seen.add(num)
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns a new list with all duplicates removed. The order of the elements in the returned list should be the same as the order in which they first appeared in the original list. Use the `Set` ADT to implement this function effici... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3691,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns a new list with all duplicates removed. The order of the elements in the returned list should be the same as the order in which they first appeared in the original list. Use the `Set` AD... |
def diagonal_sum(arr):
num_rows = len(arr)
if num_rows == 0:
return -1
for row in arr:
if len(row) != num_rows:
return -1
sum_diag = 0
for i in range(num_rows):
sum_diag += arr[i][i]
return sum_diag | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a two-dimensional array of integers as an argument and returns the diagonal sum of the array. The diagonal sum is the sum of all elements on the main diagonal (from top left to bottom right) of the array. If the array is not square (i.e., the number of rows ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3692,
"level": 1,
"question": "Create a function that takes a two-dimensional array of integers as an argument and returns the diagonal sum of the array. The diagonal sum is the sum of all elements on the main diagonal (from top left to bottom right) of the array. If the array is no... |
def count_character_occurrences(s, char):
count = 0
for c in s:
if c == char:
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\nGiven a string, find the number of times a given character appears in the string. However, you are not allowed to use any built-in functions or methods that directly count the occurrences of the character in the string. Additionally, the solution must have a time complexity of O(n), whe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3693,
"level": 1,
"question": "Given a string, find the number of times a given character appears in the string. However, you are not allowed to use any built-in functions or methods that directly count the occurrences of the character in the string. Additionally, the solution must ... |
def iterative_factorial(n: int) -> int:
"""
Given a non-negative integer n, returns the factorial of the number using iterative approach.
Args:
n: int - A non-negative integer.
Returns:
int - The factorial of the given number.
Raises:
TypeError: If the input is not an inte... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nImplement a function that calculates factorial using iterative (non-recursive) approach. Factorial of a non-negative integer n is the product of all positive integers less than or equal to n. This functionality is widely used in combinatorics, probability, and s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3694,
"level": 1,
"question": "### Problem Statement\n\nImplement a function that calculates factorial using iterative (non-recursive) approach. Factorial of a non-negative integer n is the product of all positive integers less than or equal to n. This functionality is widely used i... |
from typing import List
def max_water_container(heights: List[int]) -> int:
left = 0
right = len(heights) - 1
max_area = 0
while left < right:
width = right - left
height = min(heights[left], heights[right])
current_area = width * height
if current_area > max_area:
... | simplelr_Code_Contests | [
{
"content": "Question:\nYou are given a list of positive integers representing the heights of buildings in a row. The goal is to find two buildings such that, together with the ground, they can form the container that holds the most water.\n\nEach building's width is 1 unit, and the two lines representing the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3695,
"level": 1,
"question": "You are given a list of positive integers representing the heights of buildings in a row. The goal is to find two buildings such that, together with the ground, they can form the container that holds the most water.\n\nEach building's width is 1 unit, ... |
import re
from typing import List
def most_frequent_word(sentence: str, banned: List[str]) -> str:
# Convert banned words to a set of lowercase strings for quick lookup
banned_set = {word.lower() for word in banned}
# Extract all words, including those with apostrophes
words = re.findall(r"[a-zA-Z... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Summary\nWrite a function that takes a sentence and a set of banned words, then returns the most frequent word that is not banned. The function should ignore punctuation and assume that words are case insensitive.\n\n### Function Definition\nWrite a function `most_frequent_w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3696,
"level": 1,
"question": "### Problem Summary\nWrite a function that takes a sentence and a set of banned words, then returns the most frequent word that is not banned. The function should ignore punctuation and assume that words are case insensitive.\n\n### Function Definition... |
def search_in_rotated_array(nums, target):
if not nums:
return False
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return True
# Check if the left half is sorted
if nums[left] <= nums[mid]:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` where the elements are sorted in ascending order, and an integer `target`. Your task is to find whether the `target` exists in the array or not. The catch is that the array is rotated at some unknown pivot (i.e., elements might be shifted left or r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3697,
"level": 1,
"question": "You are given an integer array `nums` where the elements are sorted in ascending order, and an integer `target`. Your task is to find whether the `target` exists in the array or not. The catch is that the array is rotated at some unknown pivot (i.e., ... |
def longest_domino_chain(n, dominoes):
if n == 0:
return 0
if n == 1:
return 1
# Precompute the two possible placements for each domino
placements = []
for domino in dominoes:
a, b = domino
placements.append([(a, b), (b, a)])
max_length = 1
prev = [1... | simplelr_Taco | [
{
"content": "Question:\nPetya is fascinated by domino chains. A domino chain is a sequence of dominoes arranged end-to-end so that the number of dots on adjacent ends matches.\n\nPetya wants to determine the maximum length of a contiguous sequence in an array of dominoes that forms a valid chain. Each domino c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3698,
"level": 1,
"question": "Petya is fascinated by domino chains. A domino chain is a sequence of dominoes arranged end-to-end so that the number of dots on adjacent ends matches.\n\nPetya wants to determine the maximum length of a contiguous sequence in an array of dominoes that... |
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1) | simplelr_Filter | [
{
"content": "Question:\nI need to write a Python function that calculates the factorial of a given number. The factorial of a number \\( n \\) is the product of all positive integers less than or equal to \\( n \\). For example, the factorial of 5 is \\( 5 \\times 4 \\times 3 \\times 2 \\times 1 = 120 \\). How... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3699,
"level": 1,
"question": "I need to write a Python function that calculates the factorial of a given number. The factorial of a number \\( n \\) is the product of all positive integers less than or equal to \\( n \\). For example, the factorial of 5 is \\( 5 \\times 4 \\times 3... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.