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 has_overlap(intervals: list) -> bool:
"""
Determines if there is any overlap between given intervals.
:param intervals: A list of tuples, where each tuple consists of start and end times (both integers).
:return: Boolean value, True if any two intervals overlap, False otherwise.
"""
if not i... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question: Time Interval Overlap Detection\n\n**Background**: \nIn scheduling or booking systems, it is often necessary to check for overlapping time intervals to prevent double-booking or to optimize resource allocation. An interval is represented as a tuple `(start, end)` wh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5300,
"level": 1,
"question": "### Coding Question: Time Interval Overlap Detection\n\n**Background**: \nIn scheduling or booking systems, it is often necessary to check for overlapping time intervals to prevent double-booking or to optimize resource allocation. An interval is repre... |
def last_occurrences(nums):
"""
This function finds the index of the last occurrence of each integer in the given list.
Args:
nums (list): A list of integers.
Returns:
dict: A dictionary where the keys are the unique integers from the list and
the values are their... | simplelr_Filter | [
{
"content": "Question:\nI have an array of integers. I want to find the index of last occurrence of an integer in the array.\n\nExample:\n\nInput: nums = [1, 2, 3, 2, 4, 2]\nOutput: {1: 0, 2: 5, 3: 2, 4: 4}\n\nIn this example, the output is a dictionary where the keys are the unique integers in the array and t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5301,
"level": 1,
"question": "I have an array of integers. I want to find the index of last occurrence of an integer in the array.\n\nExample:\n\nInput: nums = [1, 2, 3, 2, 4, 2]\nOutput: {1: 0, 2: 5, 3: 2, 4: 4}\n\nIn this example, the output is a dictionary where the keys are the... |
def min_trucks(boxes, truck_limit):
boxes_sorted = sorted(boxes, reverse=True)
trucks = []
for box in boxes_sorted:
placed = False
for i in range(len(trucks)):
if trucks[i] + box <= truck_limit:
trucks[i] += box
placed = True
break
... | simplelr_Taco | [
{
"content": "Question:\nA logistics company needs to optimize the process of loading boxes onto trucks. You are given a list of boxes, where each box has a weight. Each truck can carry boxes up to a certain maximum weight limit. The objective is to determine the minimum number of trucks required to load all th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5302,
"level": 1,
"question": "A logistics company needs to optimize the process of loading boxes onto trucks. You are given a list of boxes, where each box has a weight. Each truck can carry boxes up to a certain maximum weight limit. The objective is to determine the minimum numbe... |
def check_password(password):
# Check if password is at least 8 characters long
if len(password) < 8:
return False
# Check for at least one uppercase letter
if not any(c.isupper() for c in password):
return False
# Check for at least one lowercase letter
if not any(c.islower() fo... | simplelr_Filter | [
{
"content": "Question:\nThis is a question for a programming environment like Jupyter Notebook:\n\nI need to define a function called `check_password` that takes a password as input and returns `True` if the password meets the following criteria:\n\n* At least 8 characters long\n* Contains at least one upperca... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5303,
"level": 1,
"question": "This is a question for a programming environment like Jupyter Notebook:\n\nI need to define a function called `check_password` that takes a password as input and returns `True` if the password meets the following criteria:\n\n* At least 8 characters lo... |
def fibonacci_sequence(n):
"""
This function generates the Fibonacci sequence up to a given number of terms.
Args:
n: The number of terms to generate.
Returns:
A list containing the Fibonacci sequence up to n terms.
"""
if n <= 0:
return []
fib = [1]
i... | simplelr_Filter | [
{
"content": "Question:\nThe following is the definition of a **Fibonacci sequence**:\n\n\"A sequence of numbers where each subsequent number is the sum of the two preceding ones.\"\n\n**Examples:**\n* 1, 1, 2, 3, 5, 8, 13, 21, 34...\n\nWrite a program in Python to generate the Fibonacci sequence up to a given ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5304,
"level": 1,
"question": "The following is the definition of a **Fibonacci sequence**:\n\n\"A sequence of numbers where each subsequent number is the sum of the two preceding ones.\"\n\n**Examples:**\n* 1, 1, 2, 3, 5, 8, 13, 21, 34...\n\nWrite a program in Python to generate th... |
def unobstructedTowers(towers):
max_height = float('-inf')
count = 0
for height in towers:
if height > max_height:
count += 1
max_height = height
return count
| simplelr_Taco | [
{
"content": "Question:\n# Task\n\nGiven a **list of integers** representing the heights of a series of towers, imagine that each tower casts a shadow to its right that covers every shorter or equally tall tower until a taller tower blocks the shadow. **Determine the number of towers that remain completely unob... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5305,
"level": 1,
"question": "# Task\n\nGiven a **list of integers** representing the heights of a series of towers, imagine that each tower casts a shadow to its right that covers every shorter or equally tall tower until a taller tower blocks the shadow. **Determine the number of... |
def extract_first_letters(s):
words = s.split()
first_letters = [word[0] for word in words]
return ''.join(first_letters) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to extract the first letter of each word from a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5306,
"level": 1,
"question": "Write a python function to extract the first letter of each word from a string.",
"split": "train"
} |
def double_char(s):
return ''.join(c * 2 for c in s) | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a string and returns a new string with each character doubled. For example, \"cat\" would become \"ccaatt\". Complete the function which takes one argument `s` which is the string to be doubled.\n\n## Example\n\n```python\ndouble_char(\"hello\") == \"hheellll... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5307,
"level": 1,
"question": "Write a function that takes a string and returns a new string with each character doubled. For example, \"cat\" would become \"ccaatt\". Complete the function which takes one argument `s` which is the string to be doubled.\n\n## Example\n\n```python\nd... |
def remove_stop_words(stop_words, text):
stop_set = set(stop_words)
words = text.split()
filtered_words = [word for word in words if word not in stop_set]
return ' '.join(filtered_words) | simplelr_Codeforces | [
{
"content": "Question:\nYou are developing a new search engine tool that processes text documents to extract and index keywords. To improve its performance, you need to implement a custom stop-word removal system. \n\nA stop-word is a commonly used word (such as \"is\", \"the\", \"in\") that a search engine ha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5308,
"level": 1,
"question": "You are developing a new search engine tool that processes text documents to extract and index keywords. To improve its performance, you need to implement a custom stop-word removal system. \n\nA stop-word is a commonly used word (such as \"is\", \"the... |
def is_subsequence(s: str, t: str) -> bool:
i = j = 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
i += 1
j += 1
return i == len(s) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings `s` and `t`. You need to determine if `s` can be transformed into `t` by deleting some (possibly zero) characters from `s` without changing the order of the remaining characters. \n\nReturn _true_ if it is possible to transform `s` into `t`, otherwise return _f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5309,
"level": 1,
"question": "You are given two strings `s` and `t`. You need to determine if `s` can be transformed into `t` by deleting some (possibly zero) characters from `s` without changing the order of the remaining characters. \n\nReturn _true_ if it is possible to transfor... |
def exchange_even_odd_elements(arr):
for i in range(0, len(arr), 2):
if i + 1 < len(arr):
arr[i], arr[i+1] = arr[i+1], arr[i]
return arr | simplelr_Filter | [
{
"content": "Question:\nExchange all the even indexed elements with the next odd indexed element in a given list, ensuring that the operation does not affect the original ordering of the elements. Additionally, use an auxiliary space of O(1) and keep the time complexity to O(n).\nAnswer:\nLet's think step by s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5310,
"level": 1,
"question": "Exchange all the even indexed elements with the next odd indexed element in a given list, ensuring that the operation does not affect the original ordering of the elements. Additionally, use an auxiliary space of O(1) and keep the time complexity to O(... |
import string
def contains_all_letters(s):
required = set(string.ascii_lowercase)
letters = {c.lower() for c in s if c.isalpha()}
return required.issubset(letters) | simplelr_Apps | [
{
"content": "Question:\n# Letter Distribution Checker\n\nCharlie is working on a project that involves analyzing text. One of the tasks requires checking if all the letters of the alphabet are present in a given string. Charlie asks you to write a program that will help him with this task.\n\nYour task is to c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5311,
"level": 1,
"question": "# Letter Distribution Checker\n\nCharlie is working on a project that involves analyzing text. One of the tasks requires checking if all the letters of the alphabet are present in a given string. Charlie asks you to write a program that will help him w... |
def char_indices(s):
result = {}
for index, char in enumerate(s):
if char.isalpha():
lower_char = char.lower()
if lower_char in result:
result[lower_char].append(index)
else:
result[lower_char] = [index]
return result | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes in a string as input and returns a dictionary where the keys are the unique characters in the string and the values are lists containing the indices of each occurrence of the character in the string. The function should ignore any characters that are ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5312,
"level": 1,
"question": "Create a Python function that takes in a string as input and returns a dictionary where the keys are the unique characters in the string and the values are lists containing the indices of each occurrence of the character in the string. The function sho... |
def is_tree(n, edges):
if len(edges) != n - 1:
return False
# Build adjacency list
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
# BFS to check for cycles
visited = [False] * n
from collections import deque
queue = deque()
q... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a positive integer `n` representing the number of nodes of an **undirected connected graph**. The nodes are numbered from `0` to `n - 1` (**inclusive**). You are also given a 2D integer array `edges`, where `edges[i] = [u, v]` denotes that there is an **undirected** edge b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5313,
"level": 1,
"question": "You are given a positive integer `n` representing the number of nodes of an **undirected connected graph**. The nodes are numbered from `0` to `n - 1` (**inclusive**). You are also given a 2D integer array `edges`, where `edges[i] = [u, v]` denotes tha... |
def max_depth(node):
if node is None:
return 0
left_depth = max_depth(node.get('left', None))
right_depth = max_depth(node.get('right', None))
return 1 + max(left_depth, right_depth) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum depth of a binary tree. The binary tree is represented using nested dictionaries, where each dictionary represents a node with optional \"left\" and \"right\" children.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5314,
"level": 1,
"question": "Write a python function to find the maximum depth of a binary tree. The binary tree is represented using nested dictionaries, where each dictionary represents a node with optional \"left\" and \"right\" children.",
"split": "train"
} |
from itertools import combinations
def generate_combinations(lst):
result = []
for r in range(1, len(lst) + 1):
result.extend(combinations(lst, r))
return result | simplelr_Filter | [
{
"content": "Question:\nHey, I'm trying to create a Python function that generates all possible combinations of elements in a list, including combinations of different lengths. How can I achieve this using Python's `itertools` module?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5315,
"level": 1,
"question": "Hey, I'm trying to create a Python function that generates all possible combinations of elements in a list, including combinations of different lengths. How can I achieve this using Python's `itertools` module?",
"split": "train"
} |
def max_length_subarray_with_one_zero(bins):
left = 0
zero_count = 0
max_length = 0
for right in range(len(bins)):
if bins[right] == 0:
zero_count += 1
# If zero_count exceeds 1, move left pointer to reduce the window
while zero_count > 1:
if bins[left] ==... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** binary integer array `bins` where each element is either `0` or `1`. Your goal is to find the maximum length of a contiguous subarray that contains **at most one** `0`. Return _the length of the longest such subarray in_ `bins`.\nAnswer:\nLet's think step b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5316,
"level": 1,
"question": "You are given a **0-indexed** binary integer array `bins` where each element is either `0` or `1`. Your goal is to find the maximum length of a contiguous subarray that contains **at most one** `0`. Return _the length of the longest such subarray in_ `... |
def merge_and_sort(list1, list2):
merged = []
# Append elements from list1 with flag 0
for num in list1:
merged.append((num, 0))
# Append elements from list2 with flag 1
for num in list2:
merged.append((num, 1))
# Sort the merged list using the custom key
sorted_merged = sort... | simplelr_Taco | [
{
"content": "Question:\n# Merge and Sort Two Lists by Specific Rule\n\nYour task is to merge two lists of integers and sort the merged list based on the following rule: \nThe list should be sorted primarily by the descending order of elements, and if two elements are equal, they should be sorted based on which... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5317,
"level": 1,
"question": "# Merge and Sort Two Lists by Specific Rule\n\nYour task is to merge two lists of integers and sort the merged list based on the following rule: \nThe list should be sorted primarily by the descending order of elements, and if two elements are equal, t... |
def is_palindrome(s):
s = s.lower()
left = 0
right = len(s) - 1
while left < right:
if not s[left].isalnum():
left += 1
continue
if not s[right].isalnum():
right -= 1
continue
if s[left] != s[right]:
return False
... | simplelr_Evol | [
{
"content": "Question:\nAnalyze the given Python function, correcting any potential inefficiencies or errors. Additionally, enhance the function by incorporating a feature that verifies if the input string is a palindrome, ignoring case, spaces, and punctuation.\n```python\nimport string\n\ndef is_palindrome(s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5318,
"level": 1,
"question": "Analyze the given Python function, correcting any potential inefficiencies or errors. Additionally, enhance the function by incorporating a feature that verifies if the input string is a palindrome, ignoring case, spaces, and punctuation.\n```python\ni... |
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1 | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are given a unsorted list of integers and a target integer. Implement the linear search algorithm to find the index of the target integer in the list. If the target is not found, return -1.\n\n### Input Format\n* **arr**: An unsorted list of integers (1 ≤ len(... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5319,
"level": 1,
"question": "### Problem Statement\nYou are given a unsorted list of integers and a target integer. Implement the linear search algorithm to find the index of the target integer in the list. If the target is not found, return -1.\n\n### Input Format\n* **arr**: An ... |
def subarray_sum(nums, k):
prefix_counts = {0: 1}
current_sum = 0
result = 0
for num in nums:
current_sum += num
if (current_sum - k) in prefix_counts:
result += prefix_counts[current_sum - k]
prefix_counts[current_sum] = prefix_counts.get(current_sum, 0) + 1
retu... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums` and a positive integer `k`, write a function to calculate the number of contiguous subarrays that sum to `k`. The function should return an integer that represents the count of such subarrays. Ensure that your solution handles both positive and negative... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5320,
"level": 1,
"question": "Given an array of integers `nums` and a positive integer `k`, write a function to calculate the number of contiguous subarrays that sum to `k`. The function should return an integer that represents the count of such subarrays. Ensure that your solution... |
import heapq
from collections import Counter
def reorganize_string(s):
count = Counter(s)
max_freq = max(count.values())
n = len(s)
if max_freq > (n + 1) // 2:
return ""
heap = [(-freq, char) for char, freq in count.items()]
heapq.heapify(heap)
result = []
last_ch... | simplelr_Apps | [
{
"content": "Question:\nYou are given a string containing digits, lowercase letters, and uppercase letters. Your task is to write a function to reformat the string in such a way that no two adjacent characters are the same. If a valid reordering is not possible, return an empty string.\n\nYour function should ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5321,
"level": 1,
"question": "You are given a string containing digits, lowercase letters, and uppercase letters. Your task is to write a function to reformat the string in such a way that no two adjacent characters are the same. If a valid reordering is not possible, return an emp... |
def shuffle_string(s, indices):
shuffle_str_list = [""] * len(s)
for i in range(len(s)):
shuffle_str_list[indices[i]] = s[i]
return "".join(shuffle_str_list) | simplelr_Evol | [
{
"content": "Question:\nGiven an erroneous code snippet, your task is to debug and modify it to solve the following problem:\n\nYou are given a string `s` consisting of lowercase alphabets and an integer array `indices` where `indices[i]` represents the correct position of the character `s[i]` once the string ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5322,
"level": 1,
"question": "Given an erroneous code snippet, your task is to debug and modify it to solve the following problem:\n\nYou are given a string `s` consisting of lowercase alphabets and an integer array `indices` where `indices[i]` represents the correct position of th... |
import importlib
def dynamic_function_call(module_name: str, function_name: str, *args: int) -> int:
module = importlib.import_module(module_name)
func = getattr(module, function_name)
return func(*args)
| simplelr_Docs | [
{
"content": "Question:\n**Objective:**\nWrite a Python function that demonstrates an understanding of embedding Python and dealing with dynamic function calls and data conversions.\n\n**Problem Statement:**\n\nYou need to write a Python function that mimics the behavior of calling a function from a Python scri... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5323,
"level": 1,
"question": "**Objective:**\nWrite a Python function that demonstrates an understanding of embedding Python and dealing with dynamic function calls and data conversions.\n\n**Problem Statement:**\n\nYou need to write a Python function that mimics the behavior of ca... |
from typing import List
def unique_elements(nums: List[int]) -> List[int]:
seen = set()
unique = []
for num in nums:
if num not in seen:
unique.append(num)
seen.add(num)
return unique | simplelr_Algorithm | [
{
"content": "Question:\n### Question Description\n\n#### Context\nProcessing collections of numerical data often involves identifying and extracting significant elements within the data. One common task is to find the unique elements within a list of numbers.\n\n#### Task\nYou are required to design a function... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5324,
"level": 1,
"question": "### Question Description\n\n#### Context\nProcessing collections of numerical data often involves identifying and extracting significant elements within the data. One common task is to find the unique elements within a list of numbers.\n\n#### Task\nYo... |
def min_operations(source: str, target: str) -> int:
n = len(source)
m = len(target)
# Create a DP table with (n+1) rows and (m+1) columns
dp = [[0] * (m + 1) for _ in range(n + 1)]
# Initialize the first row and column
for i in range(n + 1):
dp[i][0] = i
for j in range(m +... | simplelr_Codeforces | [
{
"content": "Question:\nWrite a function that receives two strings and returns the minimum number of operations required to convert the first string into the second string. There are three possible operations:\n\n1. Insert a character\n2. Remove a character\n3. Replace a character\n\nThe function signature sho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5325,
"level": 1,
"question": "Write a function that receives two strings and returns the minimum number of operations required to convert the first string into the second string. There are three possible operations:\n\n1. Insert a character\n2. Remove a character\n3. Replace a char... |
import math
from decimal import Decimal, getcontext, ROUND_HALF_UP
def calculate_sqrt(X: int, N: int) -> str:
if X == 0:
return f"0.{'0'*N}"
getcontext().rounding = ROUND_HALF_UP
getcontext().prec = N + 20 # Set precision high enough for accurate computation
X_dec = Decimal(X)
a = math.isq... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nDevelop a function to approximate the square root of a given non-negative integer using the **Babylonian (or Heron's) method**. This classical algorithm iteratively estimates the square root by improving on a guess until the desired level of precision is achieve... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5326,
"level": 1,
"question": "### Problem Statement\n\nDevelop a function to approximate the square root of a given non-negative integer using the **Babylonian (or Heron's) method**. This classical algorithm iteratively estimates the square root by improving on a guess until the de... |
import random
def is_probable_prime(n: int, k: int) -> bool:
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0:
return False
# Decompose n-1 into d * 2^s
d = n - 1
s = 0
while d % 2 == 0:
d //= 2
s += 1
for _ in range(k):
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question:\nImplement a function to determine if a given number is a probable prime using the Rabin-Miller primality test. You must ensure your solution considers edge cases and optimizes the number of iterations (k) to balance execution time and accuracy.\n\n#### Function Signature:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5327,
"level": 1,
"question": "### Question:\nImplement a function to determine if a given number is a probable prime using the Rabin-Miller primality test. You must ensure your solution considers edge cases and optimizes the number of iterations (k) to balance execution time and ac... |
def longest_contiguous_subsequence(arr: list[int]) -> tuple[int, int, int]:
"""
Find the length and starting position of the longest contiguous subsequence with the same value.
Parameters:
- arr: A list of integers containing the sequence to process.
Returns:
- A tuple containing three... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\nYou are developing a feature for a data processing tool that requires summarizing information about a sequence of numbers. Specifically, you need to create a function that finds the length and starting position of the longest contiguous subsequence with the same ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5328,
"level": 1,
"question": "### Problem Statement:\nYou are developing a feature for a data processing tool that requires summarizing information about a sequence of numbers. Specifically, you need to create a function that finds the length and starting position of the longest co... |
from typing import List, Tuple, Dict
def categorize_transactions(transactions: List[Tuple[float, str]]) -> Dict[str, float]:
result = {}
for amount, category in transactions:
if category in result:
result[category] += amount
else:
result[category] = amount
return res... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario:\nYou are developing a software tool that integrates with financial systems, focused on transaction processing. A common task involves categorizing and summing up the transactions by category, ensuring the process is efficient even for lar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5329,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario:\nYou are developing a software tool that integrates with financial systems, focused on transaction processing. A common task involves categorizing and summing up the transactions by category, ensuring th... |
string_list = ['hello', 'world', 'python', 'programming', 'reverse']
def reverse_strings(lst):
for s in lst:
reversed_s = s[::-1]
print(f"{s} -> {reversed_s}")
# Example usage
reverse_strings(string_list) | simplelr_Package | [
{
"content": "Question:\n---\nWrite a function named `reverse_strings` that reverses each string in a list and prints the results. \n\nHere's what you need to do:\n\n1. Define a list of strings named `string_list` containing at least 5 different strings. For example, `['hello', 'world', 'python', 'programming',... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5330,
"level": 1,
"question": "---\nWrite a function named `reverse_strings` that reverses each string in a list and prints the results. \n\nHere's what you need to do:\n\n1. Define a list of strings named `string_list` containing at least 5 different strings. For example, `['hello'... |
from collections import Counter
def frequency_count(numbers):
return Counter(numbers) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a list of numbers and returns a dictionary containing the frequency of each number in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5331,
"level": 1,
"question": "Create a Python function that takes a list of numbers and returns a dictionary containing the frequency of each number in the list.",
"split": "train"
} |
def evaluate_expression(s):
tokens = s.split()
# Convert number tokens to integers
tokens = [int(t) if isinstance(t, str) and t.isdigit() else t for t in tokens]
# First pass: evaluate * and /
first_pass = [tokens[0]]
for i in range(1, len(tokens), 2):
op = tokens[i]
num = t... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` which represents a valid mathematical expression containing operators `+`, `-`, `*`, `/` and non-negative integers. Operators and operands are separated by spaces. Execute the expression and return the result as an integer. Note that the division should trunca... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5332,
"level": 1,
"question": "You are given a string `s` which represents a valid mathematical expression containing operators `+`, `-`, `*`, `/` and non-negative integers. Operators and operands are separated by spaces. Execute the expression and return the result as an integer. N... |
def decode_string(s: str) -> str:
stack = []
current_str = ""
current_num = 0
for c in s:
if c.isdigit():
current_num = current_num * 10 + int(c)
elif c == "[":
stack.append((current_str, current_num))
current_str = ""
current_num = 0
... | simplelr_Data_Structure | [
{
"content": "Question:\nAs a part of understanding complex string manipulations and stack usage, you are tasked with implementing a function to decode a given encoded string. The encoded string follows a specific format where encoding is done as `k[encoded_string]`, meaning the `encoded_string` appears exactly... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5333,
"level": 1,
"question": "As a part of understanding complex string manipulations and stack usage, you are tasked with implementing a function to decode a given encoded string. The encoded string follows a specific format where encoding is done as `k[encoded_string]`, meaning t... |
from typing import List, Tuple
def find_pairs(arr: List[int], target: int) -> List[Tuple[int, int]]:
seen = set()
pairs = set()
for num in arr:
complement = target - num
if complement in seen:
pair = tuple(sorted((complement, num)))
pairs.add(pair)
seen.add(n... | simplelr_Codeforces | [
{
"content": "Question:\nWrite a function that takes an integer array and a target integer value, and finds all unique pairs of integers in the array that sum up to the target value. Each pair should be returned as a tuple, and the output should be a list of tuples. The pairs should be listed in ascending order... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5334,
"level": 1,
"question": "Write a function that takes an integer array and a target integer value, and finds all unique pairs of integers in the array that sum up to the target value. Each pair should be returned as a tuple, and the output should be a list of tuples. The pairs ... |
import itertools
def unscramble_sentence(scrambled: str) -> list:
words = scrambled.split()
seen = set()
sentences = []
for p in itertools.permutations(words):
sentence = ' '.join(p)
if sentence not in seen:
sentences.append(sentence)
seen.add(sentence)
retur... | simplelr_Algorithm | [
{
"content": "Question:\n### Scrambled Sentence Unscrambler\n\nIn many text processing applications, it is sometimes necessary to restore the original sentence from a scrambled one. You are tasked with writing a function `unscramble_sentence` that takes a scrambled sentence where only the words are scrambled bu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5335,
"level": 1,
"question": "### Scrambled Sentence Unscrambler\n\nIn many text processing applications, it is sometimes necessary to restore the original sentence from a scrambled one. You are tasked with writing a function `unscramble_sentence` that takes a scrambled sentence wh... |
import math
def convert_radians_to_degrees(radians):
return math.degrees(radians) | simplelr_Filter | [
{
"content": "Question:\nHere's a code that converts radians to degrees:\n```python\nimport math\n\ndef convert_radians_to_degrees(radians):\n return math.degrees(radians)\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5336,
"level": 1,
"question": "Here's a code that converts radians to degrees:\n```python\nimport math\n\ndef convert_radians_to_degrees(radians):\n return math.degrees(radians)",
"split": "train"
} |
def find_outstanding_scores(nums):
if not nums:
return []
sorted_nums = sorted(nums)
n = len(sorted_nums)
if n % 2 == 1:
median = sorted_nums[n // 2]
else:
median = (sorted_nums[n // 2 - 1] + sorted_nums[n // 2]) / 2
result = [x for x in nums if x > median]
result.sor... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums` representing the score of a player in multiple games, a score is regarded as **outstanding** if it is strictly greater than the median score of the entire list. Your task is to return a list of all outstanding scores from `nums` in ascending order.\n\nThe m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5337,
"level": 1,
"question": "Given an integer array `nums` representing the score of a player in multiple games, a score is regarded as **outstanding** if it is strictly greater than the median score of the entire list. Your task is to return a list of all outstanding scores from ... |
def sieve_of_eratosthenes(n):
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0], sieve[1] = False, False
for i in range(2, int(n ** 0.5) + 1):
if sieve[i]:
for j in range(i * i, n + 1, i):
sieve[j] = False
primes = [i for i, is_prime in enumerate(sieve... | simplelr_Apps | [
{
"content": "Question:\n## Your Task\nWrite a function that takes a positive integer `n` and returns the list of all prime numbers up to `n` (inclusive).\n\nA prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.\n\n### Input\n- An integer `n` (1 ≤ n ≤ 10^6)\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5338,
"level": 1,
"question": "## Your Task\nWrite a function that takes a positive integer `n` and returns the list of all prime numbers up to `n` (inclusive).\n\nA prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.\n\n### Input\n... |
def rabin_karp(pattern: str, text: str) -> int:
if not pattern or not text:
return -1
n = len(pattern)
m = len(text)
if n == 0 or m == 0 or n > m:
return -1
base = 256
mod = 10**9 + 7
# Compute the hash of the pattern
pattern_hash = 0
for c in pattern:
patte... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question:\nYou are given a text and a pattern. Implement a function `rabin_karp(pattern, text)` that returns the starting index of the first occurrence of the pattern in the text using the Rabin-Karp algorithm. If the pattern is not found in the text, return -1.\n\n### Function Sign... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5339,
"level": 1,
"question": "### Question:\nYou are given a text and a pattern. Implement a function `rabin_karp(pattern, text)` that returns the starting index of the first occurrence of the pattern in the text using the Rabin-Karp algorithm. If the pattern is not found in the te... |
def are_anagrams(string1, string2):
str1 = string1.lower()
str2 = string2.lower()
if len(str1) != len(str2):
return False
return sorted(str1) == sorted(str2) | simplelr_Filter | [
{
"content": "Question:\n### WORK IN PROGRESS\nCurrent project: AlgoDaily. Project Goal: Write an algorithm that determines whether two given strings are anagrams of each other. This algorithm should be case-insensitive.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5340,
"level": 1,
"question": "### WORK IN PROGRESS\nCurrent project: AlgoDaily. Project Goal: Write an algorithm that determines whether two given strings are anagrams of each other. This algorithm should be case-insensitive.",
"split": "train"
} |
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a number and returns its factorial. Implement the function using recursion in Python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5341,
"level": 1,
"question": "Create a function that takes a number and returns its factorial. Implement the function using recursion in Python.",
"split": "train"
} |
def largestPrime(n):
if n < 2:
return None
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for current in range(2, int(n ** 0.5) + 1):
if sieve[current]:
for multiple in range(current * current, n + 1, current):
sieve[multiple] = False
for i in range(... | simplelr_Taco | [
{
"content": "Question:\nGiven a positive integer n, find the largest prime number less than or equal to n.\n\nExample 1:\nInput:\nn = 10\nOutput:\n7\nExplanation:\nThe prime numbers less than or equal to 10 are 2, 3, 5, and 7. The largest prime number is 7.\n\nExample 2:\nInput:\nn = 20\nOutput:\n19\nExplanati... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5342,
"level": 1,
"question": "Given a positive integer n, find the largest prime number less than or equal to n.\n\nExample 1:\nInput:\nn = 10\nOutput:\n7\nExplanation:\nThe prime numbers less than or equal to 10 are 2, 3, 5, and 7. The largest prime number is 7.\n\nExample 2:\nInp... |
def sort_dicts_by_key(dict_list, key):
return sorted(dict_list, key=lambda x: (key not in x, x.get(key, None))) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of dictionaries and a key, and returns a new list with the dictionaries sorted by the specified key. If a dictionary does not contain the key, it should be placed at the end of the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5343,
"level": 1,
"question": "Write a Python function that takes a list of dictionaries and a key, and returns a new list with the dictionaries sorted by the specified key. If a dictionary does not contain the key, it should be placed at the end of the list.",
"split": "train"
} |
import csv
def csv_to_dict_list(filename, has_headers=True, delimiter=','):
"""
Converts a CSV file into a list of dictionaries.
Args:
filename: Path to the CSV file.
has_headers: Boolean indicating if the CSV has headers. Defaults to True.
delimiter: Character used to separate... | simplelr_Filter | [
{
"content": "Question:\nHello, I'm trying to write a Python script that can take a file containing multiple lines of CSV data and convert it into a list of dictionaries, where each dictionary represents a row in the CSV file. The CSV file might not have headers, and I need to handle this case by generating def... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5344,
"level": 1,
"question": "Hello, I'm trying to write a Python script that can take a file containing multiple lines of CSV data and convert it into a list of dictionaries, where each dictionary represents a row in the CSV file. The CSV file might not have headers, and I need to... |
def cumulative_sum(input_list):
current_sum = 0
result = []
for num in input_list:
current_sum += num
result.append(current_sum)
return result
# Example usage:
input_list = [5, 10, 15, 20]
print(cumulative_sum(input_list)) # Output: [5, 15, 30, 50] | simplelr_Evol | [
{
"content": "Question:\nWrite a function in Python that takes a list of integers and returns a new list where each element is the cumulative sum of the elements up to that index. For example, given the input list `[1, 2, 3, 4]`, the output should be `[1, 3, 6, 10]`. You are not allowed to use the itertools.acc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5345,
"level": 1,
"question": "Write a function in Python that takes a list of integers and returns a new list where each element is the cumulative sum of the elements up to that index. For example, given the input list `[1, 2, 3, 4]`, the output should be `[1, 3, 6, 10]`. You are n... |
def count_subarrays_with_product_less_than_k(arr, k):
if k <= 0:
return 0
n = len(arr)
left = 0
product = 1
count = 0
for right in range(n):
product *= arr[right]
while product >= k and left <= right:
product = product // arr[left]
left += 1
... | simplelr_Apps | [
{
"content": "Question:\nImplement a function that calculates the number of contiguous subarrays such that the product of their elements is less than a given integer k. \n\nThe function should take a list of positive integers and the integer k as inputs and return the count of such subarrays. The function shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5346,
"level": 1,
"question": "Implement a function that calculates the number of contiguous subarrays such that the product of their elements is less than a given integer k. \n\nThe function should take a list of positive integers and the integer k as inputs and return the count of... |
def second_smallest(numbers):
unique = sorted(set(numbers))
if len(unique) < 2:
return None
return unique[1] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that takes a list of numbers as input and returns the second smallest number in the list. Ensure your program can handle a list of any length, but it should return `None` if the list has less than two unique numbers.\nAnswer:\nLet's think step by step.\n",
"ro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5347,
"level": 1,
"question": "Write a Python program that takes a list of numbers as input and returns the second smallest number in the list. Ensure your program can handle a list of any length, but it should return `None` if the list has less than two unique numbers.",
"split":... |
import re
def is_valid_palindrome(s):
# Remove non-alphanumeric characters
cleaned = re.sub(r'[^A-Za-z0-9]', '', s)
# Convert to lowercase
cleaned = cleaned.lower()
# Check if cleaned string equals its reverse
return cleaned == cleaned[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given string is a valid palindrome, considering only alphanumeric characters and ignoring cases. For example, the string \"A man, a plan, a canal, Panama\" should return True.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5348,
"level": 1,
"question": "Write a function to check if a given string is a valid palindrome, considering only alphanumeric characters and ignoring cases. For example, the string \"A man, a plan, a canal, Panama\" should return True.",
"split": "train"
} |
def find_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Test the function
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
print(f'Is {num} a prime number? {find_prime(num)}') | simplelr_Filter | [
{
"content": "Question:\nI would like to find out if a numerical value is prime or not without using any built-in functions or libraries.\n\nHere is my code in Python:\n\n```python\ndef find_prime(n):\n if n <= 1:\n return False\n for i in range(2, n):\n if n % i == 0:\n return Fa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5349,
"level": 1,
"question": "I would like to find out if a numerical value is prime or not without using any built-in functions or libraries.\n\nHere is my code in Python:\n\n```python\ndef find_prime(n):\n if n <= 1:\n return False\n for i in range(2, n):\n if... |
import bisect
def longest_monotonic_increasing_subsequence(prices: list[int]) -> int:
if not prices:
return 0
tails = []
for x in prices:
idx = bisect.bisect_left(tails, x)
if idx == len(tails):
tails.append(x)
else:
tails[idx] = x
return len(tail... | simplelr_Algorithm | [
{
"content": "Question:\nA sequence of numbers is considered \"monotonically increasing\" if each number is greater than or equal to the number preceding it. Given a list of potential price changelogs represented as integers, your task is to determine the longest monotonically increasing subsequence within this... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5350,
"level": 1,
"question": "A sequence of numbers is considered \"monotonically increasing\" if each number is greater than or equal to the number preceding it. Given a list of potential price changelogs represented as integers, your task is to determine the longest monotonically... |
def find_last_occurrence(lst, target):
for i in range(len(lst)-1, -1, -1):
if lst[i] == target:
return i
return -1 | simplelr_Filter | [
{
"content": "Question:\nDevelop a Python function that takes a list of integers and a target integer, then returns the position of the last occurrence of the target integer in the list. If the target integer is not found, return -1. Additionally, write test cases to verify the correctness of your function.\nAn... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5351,
"level": 1,
"question": "Develop a Python function that takes a list of integers and a target integer, then returns the position of the last occurrence of the target integer in the list. If the target integer is not found, return -1. Additionally, write test cases to verify th... |
def smallest_lexicographic_string(n, s):
z = s.count('0')
num_0 = min(z, n)
num_1 = n - num_0
return '0' * num_0 + '1' * num_1 | simplelr_Filter | [
{
"content": "Question:\nGiven an integer n and a binary string s, we define a new string t by rearranging the characters of s to create the lexicographically smallest string possible. If the length of the string t is greater than n, we remove characters from the end of t to make it of length n. Write a program... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5352,
"level": 1,
"question": "Given an integer n and a binary string s, we define a new string t by rearranging the characters of s to create the lexicographically smallest string possible. If the length of the string t is greater than n, we remove characters from the end of t to m... |
def operation_calculator(operations):
try:
result = eval(operations)
except ZeroDivisionError:
return "Invalid operation"
# Check if the result is a float and an integer value
if isinstance(result, float) and result.is_integer():
return int(result)
return result | simplelr_Apps | [
{
"content": "Question:\n## Task\n\nImplement an operation-based calculator function, `operation_calculator`, that performs a series of operations specified in a string to compute the result.\n\nThe function, `operation_calculator`, takes a single parameter, `operations`, which is a string comprised of digits (... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5353,
"level": 1,
"question": "## Task\n\nImplement an operation-based calculator function, `operation_calculator`, that performs a series of operations specified in a string to compute the result.\n\nThe function, `operation_calculator`, takes a single parameter, `operations`, whic... |
from typing import List, Set, Tuple
def generate_subsets(nums: List[int]) -> Set[Tuple[int]]:
n = len(nums)
result = set()
for i in range(2 ** n):
subset = []
for j in range(n):
if (i >> j) & 1:
subset.append(nums[j])
result.add(tuple(subset))
return ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Context\nA leetcode problem involves generating all possible subsets of a given list of distinct integers. This problem assesses your understanding of bit manipulation and the ability to generate power sets efficiently.\n\n### Task\nWrite a function `generate_subsets(nums)` that tak... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5354,
"level": 1,
"question": "### Context\nA leetcode problem involves generating all possible subsets of a given list of distinct integers. This problem assesses your understanding of bit manipulation and the ability to generate power sets efficiently.\n\n### Task\nWrite a functio... |
def first_non_repeating_character(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_Leetcode | [
{
"content": "Question:\nWrite a function that takes a string containing only lowercase letters and returns the first non-repeating character. If there is no non-repeating character, return an empty string `\" \"`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5355,
"level": 1,
"question": "Write a function that takes a string containing only lowercase letters and returns the first non-repeating character. If there is no non-repeating character, return an empty string `\" \"`.",
"split": "train"
} |
from collections import Counter
def most_common_element(lst):
if not lst:
return None
counts = Counter(lst)
return counts.most_common(1)[0][0] | simplelr_Filter | [
{
"content": "Question:\nCan you help me create a Python function that finds the most common element in a list of integers?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5356,
"level": 1,
"question": "Can you help me create a Python function that finds the most common element in a list of integers?",
"split": "train"
} |
def rob(nums: list[int]) -> int:
if not nums:
return 0
if len(nums) == 1:
return nums[0]
prev_prev = nums[0]
prev = max(nums[0], nums[1])
for i in range(2, len(nums)):
current = max(prev, prev_prev + nums[i])
prev_prev, prev = prev, current
return prev
| simplelr_Taco | [
{
"content": "Question:\nGiven an array \"nums\" containing n integers where the element at index i represents the amount of money in the i-th house, you are a thief planning to rob houses along a street. However, you cannot rob two adjacent houses because the security system will alert the police. Your goal is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5357,
"level": 1,
"question": "Given an array \"nums\" containing n integers where the element at index i represents the amount of money in the i-th house, you are a thief planning to rob houses along a street. However, you cannot rob two adjacent houses because the security system ... |
def can_sum_to_target(numbers, target):
seen = set()
for num in numbers:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of integers and a target integer. Your function should return True if the target integer can be obtained by summing any two different integers from the list. Otherwise, return False.\n\n```python\ndef can_sum_to_target(numbers, target):\n pass\n```\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5358,
"level": 1,
"question": "Write a function that takes a list of integers and a target integer. Your function should return True if the target integer can be obtained by summing any two different integers from the list. Otherwise, return False.\n\n```python\ndef can_sum_to_targe... |
def strip_whitespace(lst):
return [s.strip() for s in lst] | simplelr_Filter | [
{
"content": "Question:\nI need to make a method that can take a list of strings as input and return a new list that contains the same strings but with leading and trailing whitespace removed.\n\nHere is what I have so far:\n```\ndef strip_whitespace(lst):\n new_list = []\n for string in lst:\n str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5359,
"level": 1,
"question": "I need to make a method that can take a list of strings as input and return a new list that contains the same strings but with leading and trailing whitespace removed.\n\nHere is what I have so far:\n```\ndef strip_whitespace(lst):\n new_list = []\n... |
def reverse_sentence(sentence):
words = sentence.split()
reversed_words = []
for i in range(len(words)-1, -1, -1):
reversed_words.append(words[i])
return ' '.join(reversed_words) | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a sentence as input and returns the sentence reversed at the word level while preserving the order of characters within each word. Do not use any built-in reversing functions. Handle punctuation correctly as part of the word it is attached to.\n\nExample: \nI... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5360,
"level": 1,
"question": "Write a function that takes a sentence as input and returns the sentence reversed at the word level while preserving the order of characters within each word. Do not use any built-in reversing functions. Handle punctuation correctly as part of the word... |
def num_decodings(enc_mes: str) -> int:
n = len(enc_mes)
if n == 0:
return 0
dp = [0] * (n + 1)
dp[0] = 1 # Base case: empty string has one way to decode
for i in range(1, n + 1):
# Check single digit decoding
if enc_mes[i-1] != '0':
dp[i] += dp[i-1]
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Decoding Encrypted Messages\n\n#### Problem Statement\nA message containing letters from A-Z is encoded to numbers using the following mapping:\n\n```\n'A' -> 1\n'B' -> 2\n...\n'Z' -> 26\n```\n\nGiven an encoded message containing digits, determine the total number of ways to decode... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5361,
"level": 1,
"question": "### Decoding Encrypted Messages\n\n#### Problem Statement\nA message containing letters from A-Z is encoded to numbers using the following mapping:\n\n```\n'A' -> 1\n'B' -> 2\n...\n'Z' -> 26\n```\n\nGiven an encoded message containing digits, determine... |
def roman_to_int(s):
roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
values = [roman_map[c] for c in s]
total = sum(values)
for i in range(len(values) - 1):
if values[i] < values[i + 1]:
total -= 2 * values[i]
return total
| simplelr_Taco | [
{
"content": "Question:\nWrite a program to check if a string is a valid Roman numeral and convert it to an integer.\n\nRoman numerals are represented by seven different symbols: I, V, X, L, C, D, and M.\n\n| Symbol | Value |\n|--------|-------|\n| I | 1 |\n| V | 5 |\n| X | 10 |\n| L ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5362,
"level": 1,
"question": "Write a program to check if a string is a valid Roman numeral and convert it to an integer.\n\nRoman numerals are represented by seven different symbols: I, V, X, L, C, D, and M.\n\n| Symbol | Value |\n|--------|-------|\n| I | 1 |\n| V |... |
def merge_events(events: list[tuple[int, int]]) -> list[tuple[int, int]]:
sorted_events = sorted(events)
if not sorted_events:
return []
merged = [sorted_events[0]]
for event in sorted_events[1:]:
current_start, current_end = event
last_start, last_end = merged[-1]
if cur... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given a list of events, where each event is represented as a tuple containing the start time and end time (inclusive). Write a function `merge_events` that merges overlapping events and returns the consolidated list of events.\n\n#### Function Signature\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5363,
"level": 1,
"question": "### Problem Statement\n\nYou are given a list of events, where each event is represented as a tuple containing the start time and end time (inclusive). Write a function `merge_events` that merges overlapping events and returns the consolidated list of ... |
import math
def find_next_perfect_square(n: int) -> int:
s = math.isqrt(n)
if s * s == n:
return (s + 1) ** 2
else:
return -1 | simplelr_Data_Structure | [
{
"content": "Question:\nPerfect Square Detection and Successor Computation\n\n#### Context:\nConsider you are tasked with designing a mathematical utility that involves detecting perfect squares and determining subsequent perfect squares for educational software.\n\n#### Problem Statement:\nWrite a function `f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5364,
"level": 1,
"question": "Perfect Square Detection and Successor Computation\n\n#### Context:\nConsider you are tasked with designing a mathematical utility that involves detecting perfect squares and determining subsequent perfect squares for educational software.\n\n#### Prob... |
def process_operations(n, operations):
collection = set()
results = []
for operation in operations:
parts = operation.split()
op = parts[0]
num = int(parts[1])
if op == "add":
collection.add(num)
elif op == "remove":
collection.discard(num)
... | simplelr_Code_Contests | [
{
"content": "Question:\nProblem\n\nAlice is building a custom collection of unique numbers, a set-like structure where each number can only appear once. She wants to perform a series of operations on this collection. The operations include adding a number, removing a number, and checking whether a number is in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5365,
"level": 1,
"question": "Problem\n\nAlice is building a custom collection of unique numbers, a set-like structure where each number can only appear once. She wants to perform a series of operations on this collection. The operations include adding a number, removing a number, ... |
import pandas as pd
import matplotlib.pyplot as plt
def analyze_activities(file_path):
try:
# Attempt to read the CSV file
df = pd.read_csv(file_path)
except FileNotFoundError:
print("Error: The file was not found.")
return None
except pd.errors.EmptyDataError:
print... | simplelr_Package | [
{
"content": "Question:\nYou are working with a dataset that keeps track of user activities on a website. The dataset consists of a CSV file named 'activities.csv'. This file contains multiple entries with the following columns: 'UserId', 'Activity', 'Timestamp'. Your goal is to identify active users and visual... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5366,
"level": 1,
"question": "You are working with a dataset that keeps track of user activities on a website. The dataset consists of a CSV file named 'activities.csv'. This file contains multiple entries with the following columns: 'UserId', 'Activity', 'Timestamp'. Your goal is ... |
import heapq
from typing import List
def trapRainWater(heights: List[List[int]]) -> int:
if not heights or len(heights) < 3 or len(heights[0]) < 3:
return 0
m = len(heights)
n = len(heights[0])
visited = [[False for _ in range(n)] for _ in range(m)]
heap = []
dirs = [(-1, 0), (1, 0), (0... | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function that, given an m × n grid filled with integers representing building heights, finds the maximum amount of water that can be trapped after raining.\n\nWater can only be trapped if there are buildings on both the left and right side of a given cell that are taller than th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5367,
"level": 1,
"question": "Write a function that, given an m × n grid filled with integers representing building heights, finds the maximum amount of water that can be trapped after raining.\n\nWater can only be trapped if there are buildings on both the left and right side of a... |
def sum_of_cubes(lst):
total = 0
for num in lst:
if isinstance(num, int):
total += num ** 3
return total | simplelr_Apps | [
{
"content": "Question:\n*** Sum of Cubes ***\n\nWrite a function that takes a list of integers and returns the sum of the cubes of those integers. The function should handle both positive and negative numbers and ignore non-integer elements.\n\nInput: A list of integers.\nOutput: An integer representing the su... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5368,
"level": 1,
"question": "*** Sum of Cubes ***\n\nWrite a function that takes a list of integers and returns the sum of the cubes of those integers. The function should handle both positive and negative numbers and ignore non-integer elements.\n\nInput: A list of integers.\nOut... |
def celsius_to_fahrenheit(temperature_celsius):
return temperature_celsius * 9/5 + 32 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert temperatures from Celsius to Fahrenheit. The function should take one parameter temperature_celsius and return the temperature in Fahrenheit.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5369,
"level": 1,
"question": "Write a python function to convert temperatures from Celsius to Fahrenheit. The function should take one parameter temperature_celsius and return the temperature in Fahrenheit.",
"split": "train"
} |
from typing import Dict, List, Tuple
def bellman_ford_with_path(graph: Dict[str, Dict[str, int]], source: str, destination: str) -> Tuple[bool, List[str]]:
nodes = list(graph.keys())
num_nodes = len(nodes)
distance = {node: float('inf') for node in nodes}
distance[source] = 0
predecessor = {no... | simplelr_Data_Structure | [
{
"content": "Question:\n### Bellman-Ford Path Reconstruction\n\n#### Context\nYou are given a directed weighted graph representing a transport network with cities represented as nodes and routes with travel times, which can include negative values, represented as edges. You are tasked to determine the shortest... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5370,
"level": 1,
"question": "### Bellman-Ford Path Reconstruction\n\n#### Context\nYou are given a directed weighted graph representing a transport network with cities represented as nodes and routes with travel times, which can include negative values, represented as edges. You a... |
def aggregate_dicts(list_of_dicts):
result_dict = {}
for dictionary in list_of_dicts:
for key, value in dictionary.items():
if key in result_dict:
result_dict[key].append(value)
else:
result_dict[key] = [value]
return result_dict | simplelr_Filter | [
{
"content": "Question:\nHow can I design a Python function that efficiently converts a list of dictionaries into a single dictionary, where each key from the list of dictionaries becomes a key in the resulting dictionary with values being lists that aggregate the values from all the dictionaries in the input l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5371,
"level": 1,
"question": "How can I design a Python function that efficiently converts a list of dictionaries into a single dictionary, where each key from the list of dictionaries becomes a key in the resulting dictionary with values being lists that aggregate the values from ... |
from typing import List, Tuple
def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if not intervals:
return []
# Sort intervals based on the start time
sorted_intervals = sorted(intervals, key=lambda x: x[0])
# Initialize the merged list with the first inte... | simplelr_Apps | [
{
"content": "Question:\nYou are given a collection of intervals on a number line, each represented by a tuple with a start and end point `(start, end)`. Write a function to merge all overlapping intervals and return the resulting collection of merged intervals. Two intervals overlap if they share at least one ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5372,
"level": 1,
"question": "You are given a collection of intervals on a number line, each represented by a tuple with a start and end point `(start, end)`. Write a function to merge all overlapping intervals and return the resulting collection of merged intervals. Two intervals ... |
from collections import deque
from collections import defaultdict
def min_words_to_form_target(words, target):
if not target:
return 0
if not words:
return -1
mod = 10**18 + 3
base = 911382629
target_len = len(target)
s = target
# Precompute prefix hashes and power array ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of words `words` and a target word `target`. The target word can be formed by concatenating words from the list `words`, where each word in `words` can be used multiple times. Return the minimum number of words required to form the target word. If it is not possible... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5373,
"level": 1,
"question": "You are given a list of words `words` and a target word `target`. The target word can be formed by concatenating words from the list `words`, where each word in `words` can be used multiple times. Return the minimum number of words required to form the... |
def max_items_with_discount(prices: list[int], discount_limit: int, budget: int) -> int:
discounted_cents = [p * (100 - discount_limit) for p in prices]
discounted_cents.sort()
budget_cents = budget * 100
total = 0
count = 0
for price in discounted_cents:
if total + price <= bu... | simplelr_Taco | [
{
"content": "Question:\nYou are given an array prices where prices[i] is the price of the i-th item in a shop. You are also given a parameter discount_limit which determines the maximum percentage discount that can be applied to any item in the shop and an integer budget which is the amount of money you are wi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5374,
"level": 1,
"question": "You are given an array prices where prices[i] is the price of the i-th item in a shop. You are also given a parameter discount_limit which determines the maximum percentage discount that can be applied to any item in the shop and an integer budget whic... |
from typing import List
def most_frequent_even(nums: List[int]) -> int:
evens = {}
for num in nums:
if num % 2 == 0:
if num in evens:
evens[num] += 1
else:
evens[num] = 1
if not evens:
return None
max_freq = max(evens.values())
... | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function `most_frequent_even` that receives a list of integers and returns the most frequent even number in the list. If there are multiple most frequent even numbers with the same frequency, return the smallest one. If there are no even numbers in the list, return None.\n\n### ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5375,
"level": 1,
"question": "Write a function `most_frequent_even` that receives a list of integers and returns the most frequent even number in the list. If there are multiple most frequent even numbers with the same frequency, return the smallest one. If there are no even number... |
def spiralOrder(matrix):
if not matrix:
return []
result = []
top = 0
bottom = len(matrix) - 1
left = 0
right = len(matrix[0]) - 1
while top <= bottom and left <= right:
# Traverse from left to right on top row
for i in range(left, right + 1):
result.... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a `m x n` matrix `matrix` of integers, return _a list of all elements of the matrix in spiral order_. The spiral order starts from the top-left corner of the matrix and proceeds to the right, then down, then left, and then up, repeating the same pattern until all elements are trav... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5376,
"level": 1,
"question": "Given a `m x n` matrix `matrix` of integers, return _a list of all elements of the matrix in spiral order_. The spiral order starts from the top-left corner of the matrix and proceeds to the right, then down, then left, and then up, repeating the same ... |
def reverse_integer(x):
# Determine the sign
sign = -1 if x < 0 else 1
# Work with the absolute value
num = abs(x)
# Reverse the digits
reversed_num = int(str(num)[::-1])
# Apply the sign
reversed_num = sign * reversed_num
# Check for overflow
if reversed_num < -2**31 or reversed... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse an integer number. The function should handle the case where reversing the number results in an integer overflow. If overflow is detected, the function should return 0. Assume that the input is a 32-bit signed integer.\nAnswer:\nLet's think step by ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5377,
"level": 1,
"question": "Write a python function to reverse an integer number. The function should handle the case where reversing the number results in an integer overflow. If overflow is detected, the function should return 0. Assume that the input is a 32-bit signed integer... |
def can_sum_to_target(arr: list, target: int) -> bool:
mask = 1 # Initially, sum 0 is possible.
for num in arr:
if num == target:
return True
if num > target:
continue
# Update the mask to include new possible sums
mask |= mask << num
# Ensure we ... | simplelr_Taco | [
{
"content": "Question:\nGiven an array of positive integers and a target value, write a function that determines whether any combination of elements in the array (without repetition) adds up to the target value.\n\nFunction Signature:\n```python\ndef can_sum_to_target(arr: list, target: int) -> bool:\n```\n\nI... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5378,
"level": 1,
"question": "Given an array of positive integers and a target value, write a function that determines whether any combination of elements in the array (without repetition) adds up to the target value.\n\nFunction Signature:\n```python\ndef can_sum_to_target(arr: li... |
def min_operations(s1, s2):
m = len(s1)
n = len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
else:
if s1[i-1]... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given two strings, s1 and s2, consisting of lowercase English letters. Your task is to determine the minimum number of operations required to transform s1 into s2. You can perform the following operations on s1:\n\n1. Insert a character.\n2. Delete a character.\n3. Replace a cha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5379,
"level": 1,
"question": "You are given two strings, s1 and s2, consisting of lowercase English letters. Your task is to determine the minimum number of operations required to transform s1 into s2. You can perform the following operations on s1:\n\n1. Insert a character.\n2. De... |
def find_extremes(numbers, index=0, current_min=None, current_max=None):
if not numbers:
return (None, None)
if index == 0 and current_min is None:
current_min = current_max = numbers[0]
return find_extremes(numbers, index + 1, current_min, current_max)
if index >= len(numbers):
... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that returns the largest and smallest number in a list using Python. The function should take two parameters: `numbers`, which is a list of integers, and `index`, which is the current index in the list that is being processed. The function should recursively call itsel... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5380,
"level": 1,
"question": "Create a function that returns the largest and smallest number in a list using Python. The function should take two parameters: `numbers`, which is a list of integers, and `index`, which is the current index in the list that is being processed. The fun... |
def contains_special_characters(s):
for char in s:
if not char.isalnum():
return True
return False | simplelr_Filter | [
{
"content": "Question:\nCan you create a Python function that checks if a given string contains any special characters? The function should return `True` if the string contains at least one special character and `False` otherwise. Special characters are defined as any character that is not a letter or a digit.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5381,
"level": 1,
"question": "Can you create a Python function that checks if a given string contains any special characters? The function should return `True` if the string contains at least one special character and `False` otherwise. Special characters are defined as any charact... |
def rotate_matrix_90_clockwise(matrix):
return [list(row[::-1]) for row in zip(*matrix)] | simplelr_Apps | [
{
"content": "Question:\nWrite a function that rotates a square matrix 90 degrees clockwise. The matrix will be represented by a two-dimensional array where the input will be an array of rows, and each row is an array of numbers. You can assume the input matrix will always be square (i.e., the number of rows is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5382,
"level": 1,
"question": "Write a function that rotates a square matrix 90 degrees clockwise. The matrix will be represented by a two-dimensional array where the input will be an array of rows, and each row is an array of numbers. You can assume the input matrix will always be ... |
import torch
def denoise_signal(signal: torch.Tensor, k: int) -> torch.Tensor:
fft_signal = torch.fft.fft(signal)
magnitudes = torch.abs(fft_signal)
_, indices = torch.topk(magnitudes, k, largest=True)
mask = torch.zeros_like(magnitudes, dtype=torch.bool).scatter_(0, indices, True)
fft_filtered = f... | simplelr_Docs | [
{
"content": "Question:\n### FFT and Signal Processing with PyTorch\n\nIn this task, you will work with the Fast Fourier Transform (FFT) functions provided by the `torch.fft` module to analyze and filter a noisy signal.\n\n#### Problem Statement\n\nYou are provided with a 1D tensor representing a noisy signal. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5383,
"level": 1,
"question": "### FFT and Signal Processing with PyTorch\n\nIn this task, you will work with the Fast Fourier Transform (FFT) functions provided by the `torch.fft` module to analyze and filter a noisy signal.\n\n#### Problem Statement\n\nYou are provided with a 1D t... |
def process_data(data):
# Remove duplicates by converting to a set and then back to a list
unique_data = list(set(data))
# Sort the unique list in descending order
sorted_data = sorted(unique_data, reverse=True)
# Split into even and odd numbers
even = [num for num in sorted_data if num % 2 == 0... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nDesign a function `process_data` that manipulates a list of integers based on specific criteria. Your task is to implement functionality that demonstrates the use of built-in data types, functions, and understanding of Python core features.\n\n#### Problem Statement:\nW... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5384,
"level": 1,
"question": "#### Objective:\nDesign a function `process_data` that manipulates a list of integers based on specific criteria. Your task is to implement functionality that demonstrates the use of built-in data types, functions, and understanding of Python core feat... |
def tournament_schedule(N):
total = N * (N - 1) // 2
matches = []
for i in range(1, N):
for j in range(i + 1, N + 1):
matches.append((i, j))
return total, matches
| simplelr_Taco | [
{
"content": "Question:\nYou are organizing a tournament where N players will compete against each other. Each player will play against every other player exactly once. You want to determine two things: \n1. The total number of matches that will be played in the tournament.\n2. The unique schedule of matches fo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5385,
"level": 1,
"question": "You are organizing a tournament where N players will compete against each other. Each player will play against every other player exactly once. You want to determine two things: \n1. The total number of matches that will be played in the tournament.\n2... |
def hexdump_to_binary(hex_string, output_filename):
# Remove all whitespace from the hex string
hex_string = hex_string.replace(" ", "").replace("\n", "")
try:
# Convert hex string to bytes
binary_data = bytes.fromhex(hex_string)
# Write bytes to the output file
with open(out... | simplelr_Filter | [
{
"content": "Question:\nI have a hexdump of a file, and I want to convert it into a binary file. How would I do this using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5386,
"level": 1,
"question": "I have a hexdump of a file, and I want to convert it into a binary file. How would I do this using Python?",
"split": "train"
} |
from __future__ import absolute_import, division, print_function
import io
def process_file(input_file, output_file):
# Read the input file using io.open for consistent handling
with io.open(input_file, 'r', encoding='utf-8') as f:
content = f.read()
# Process the content
processed_content... | simplelr_Docs | [
{
"content": "Question:\n**Coding Assessment Question:**\n\n### Objective\nWrite a Python function that demonstrates the process of porting code from Python 2 to Python 3, focusing on handling text versus binary data and ensuring compatibility with both versions.\n\n### Problem Statement\nYou are given a simple... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5387,
"level": 1,
"question": "**Coding Assessment Question:**\n\n### Objective\nWrite a Python function that demonstrates the process of porting code from Python 2 to Python 3, focusing on handling text versus binary data and ensuring compatibility with both versions.\n\n### Proble... |
def is_divisible_by_3(s):
total = 0
n = len(s)
for i in range(n):
if s[i] == '1':
pos = n - 1 - i
if pos % 2 == 0:
total += 1
else:
total += 2
return total % 3 == 0 | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` which represents a binary number (a string consisting only of the characters '0' and '1'). Determine if the binary number is divisible by 3. Return `True` if it is divisible by 3, otherwise return `False`.\nAnswer:\nLet's think step by step.\n",
"role": "u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5388,
"level": 1,
"question": "You are given a string `s` which represents a binary number (a string consisting only of the characters '0' and '1'). Determine if the binary number is divisible by 3. Return `True` if it is divisible by 3, otherwise return `False`.",
"split": "train... |
def sum_of_squares(n):
if n <= 1:
return 0
return ( (n - 1) * n * (2 * n - 1) ) // 6 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a positive integer n and returns the sum of the squares of all positive integers less than n.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5389,
"level": 1,
"question": "Create a function that takes a positive integer n and returns the sum of the squares of all positive integers less than n.",
"split": "train"
} |
from collections import Counter
def top_k_frequent_elements(nums, k):
count = Counter(nums)
items = list(count.items())
# Sort by frequency in descending order; for same frequencies, the order is arbitrary
sorted_items = sorted(items, key=lambda x: x[1], reverse=True)
# Extract the top k elements
... | simplelr_Apps | [
{
"content": "Question:\nYou are given an integer array, `nums`, of length `n` and an integer, `k`, with `1 ≤ k ≤ n`. Write a function to find the `k` most frequent elements in the array and return them in an array sorted by their frequency from highest to lowest. If multiple elements have the same frequency, r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5390,
"level": 1,
"question": "You are given an integer array, `nums`, of length `n` and an integer, `k`, with `1 ≤ k ≤ n`. Write a function to find the `k` most frequent elements in the array and return them in an array sorted by their frequency from highest to lowest. If multiple ... |
def compressString(s):
# Check if the input is not a string
if not isinstance(s, str):
return 'Input is not a string'
# Check if all characters are alphabetic
for char in s:
if not char.isalpha():
return 'Only alphabetic characters allowed'
# Handle empty string... | simplelr_Taco | [
{
"content": "Question:\nDesign a function named `compressString` that takes a string as input and returns a compressed version by replacing consecutive repeating characters with the character followed by the number of repetitions.\n\nIf the input string contains any non-alphabetic characters, return 'Only alph... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5391,
"level": 1,
"question": "Design a function named `compressString` that takes a string as input and returns a compressed version by replacing consecutive repeating characters with the character followed by the number of repetitions.\n\nIf the input string contains any non-alpha... |
def cube_numbers(numbers):
return [n ** 3 for n in numbers]
# Example usage:
input_list = [1, 2, 3, 4]
result = cube_numbers(input_list)
print("The list of cubes is:", result) | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes a list of integers as input and returns a new list containing the cubes of the original integers. Ensure that your function preserves the order of elements from the original list. For example, given the input list [1, 2, 3, 4], the output should be [1,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5392,
"level": 1,
"question": "Write a Python function that takes a list of integers as input and returns a new list containing the cubes of the original integers. Ensure that your function preserves the order of elements from the original list. For example, given the input list [1,... |
def max_temperatures(temperatures, queries):
n = len(temperatures)
if n == 0:
return []
# Precompute log_table
log_table = [0] * (n + 1)
for i in range(2, n + 1):
log_table[i] = log_table[i // 2] + 1
log_max = log_table[n] + 1 # Maximum level needed
# Build sp... | simplelr_Codeforces | [
{
"content": "Question:\n0Anusha is developing a new module for a weather forecasting system. She needs to ensure that for every range of days, she can quickly determine the maximum temperature recorded within that range. To achieve this, she decides to preprocess the temperature data for efficient range querie... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5393,
"level": 1,
"question": "0Anusha is developing a new module for a weather forecasting system. She needs to ensure that for every range of days, she can quickly determine the maximum temperature recorded within that range. To achieve this, she decides to preprocess the temperat... |
def fibonacci(n):
# Check if n is a non-negative integer or a float equal to an integer
if isinstance(n, int):
if n < 0:
return "Input should be a non-negative integer"
elif isinstance(n, float):
if n.is_integer() and n >= 0:
n = int(n)
else:
retur... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the nth Fibonacci number. The function should use a looping structure and not recursion. The nth Fibonacci number is defined as F(n) = F(n-1) + F(n-2) with initial conditions F(0) = 0 and F(1) = 1. Your function should handle negative inputs by returning ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5394,
"level": 1,
"question": "Write a python function to find the nth Fibonacci number. The function should use a looping structure and not recursion. The nth Fibonacci number is defined as F(n) = F(n-1) + F(n-2) with initial conditions F(0) = 0 and F(1) = 1. Your function should h... |
def map_lists_to_dict(list1, list2):
if len(list1) != len(list2):
return "Error: Lists are not of equal length."
result = {}
for a, b in zip(list1, list2):
result[a] = b
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes two lists of equal length, and returns a dictionary mapping each element from the first list to the corresponding element in the second list. The function should also handle cases where the lists are not of equal length by returning an error message... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5395,
"level": 1,
"question": "Write a function in Python that takes two lists of equal length, and returns a dictionary mapping each element from the first list to the corresponding element in the second list. The function should also handle cases where the lists are not of equal l... |
def check_permutation(s, t):
if len(s) > len(t):
return False
if len(s) == 0:
return True
from collections import defaultdict
s_count = defaultdict(int)
for char in s:
s_count[char] += 1
t_count = defaultdict(int)
# Initialize the first window
for i in r... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a string contains a permutation of another string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5396,
"level": 1,
"question": "Write a function to check if a string contains a permutation of another string.",
"split": "train"
} |
def create_seaborn_visualizations():
import seaborn as sns
import matplotlib.pyplot as plt
# Load the datasets
penguins = sns.load_dataset("penguins")
dots = sns.load_dataset("dots")
# Set the theme for all plots
sns.set_theme(style="darkgrid", font_scale=1.25)
# Task 2: Create PairGr... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\nCreate a Python script that utilizes seaborn to perform the following tasks with the `penguins` dataset:\n\n1. **Load the Dataset**:\n Load the `penguins` dataset using seaborn's `load_dataset` function.\n\n2. **Data Visualization**:\n Create a `PairGrid` to visualiz... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5397,
"level": 1,
"question": "#### Objective\nCreate a Python script that utilizes seaborn to perform the following tasks with the `penguins` dataset:\n\n1. **Load the Dataset**:\n Load the `penguins` dataset using seaborn's `load_dataset` function.\n\n2. **Data Visualization**:\... |
def check_palindrome(s):
s = s.lower()
s = ''.join(c for c in s if c.isalnum())
return "Palindrome" if s == s[::-1] else "Not a Palindrome" | simplelr_Filter | [
{
"content": "Question:\nI have a task as follows:\n\nCreate a Python program that determines whether a given string is a palindrome or not. The program should ignore non-alphanumeric characters and should be case-insensitive. It should return \"Palindrome\" if the string is a palindrome, and \"Not a Palindrome... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5398,
"level": 1,
"question": "I have a task as follows:\n\nCreate a Python program that determines whether a given string is a palindrome or not. The program should ignore non-alphanumeric characters and should be case-insensitive. It should return \"Palindrome\" if the string is a... |
def min_operations_to_divisible(arr, k):
k = abs(k)
total = 0
for num in arr:
remainder = num % k
total += min(remainder, k - remainder)
return total | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `arr` and an integer `k`. In one operation, you can increase or decrease any element of `arr` by `1`. Return _the minimum number of operations required to make all elements of the array divisible by `k`_.\nAnswer:\nLet's think step by step.\n"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5399,
"level": 1,
"question": "You are given a **0-indexed** integer array `arr` and an integer `k`. In one operation, you can increase or decrease any element of `arr` by `1`. Return _the minimum number of operations required to make all elements of the array divisible by `k`_.",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.