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 f(n):
result = 1
for i in range(1, n + 1):
result *= i
return result | simplelr_Filter | [
{
"content": "Question:\nA.\n\n1. Write a function `f(n)` which takes a positive integer `n` as input and returns the product of all positive integers less than or equal to `n`.\r\n\r\n\r\n2. Implement your function in Python:\r\n\r\n\r\n\r\nB. What is the time complexity of your implemented function?\nAnswer:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4300,
"level": 1,
"question": "A.\n\n1. Write a function `f(n)` which takes a positive integer `n` as input and returns the product of all positive integers less than or equal to `n`.\r\n\r\n\r\n2. Implement your function in Python:\r\n\r\n\r\n\r\nB. What is the time complexity of y... |
def jaccard_similarity(str1: str, str2: str) -> float:
"""
Calculates the Jaccard similarity between two strings.
Parameters:
str1 (str): The first string.
str2 (str): The second string.
Returns:
float: Jaccard similarity score between the two strings.
"""
set1 = set(str1)
set2... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario:\nYou are responsible for implementing a string similarity measure based on the Jaccard index. This measure should be used to compare two strings and return a similarity score. The Jaccard index is defined as the size of the intersection divided by the size of the union of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4301,
"level": 1,
"question": "### Scenario:\nYou are responsible for implementing a string similarity measure based on the Jaccard index. This measure should be used to compare two strings and return a similarity score. The Jaccard index is defined as the size of the intersection d... |
def prioritize_projects(projects):
# Sort the projects by priority (ascending) and then by id (ascending)
sorted_projects = sorted(projects, key=lambda x: (x[1], x[0]))
# Extract the project identifiers from the sorted list
return [p[0] for p in sorted_projects] | simplelr_Leetcode | [
{
"content": "Question:\nA company needs to manage the team's project priorities. Given a list where each element represents a project with a unique positive integer identifier and priority levels from 1 (highest) to 5 (lowest), the task is to reorder the projects such that higher priority projects come before ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4302,
"level": 1,
"question": "A company needs to manage the team's project priorities. Given a list where each element represents a project with a unique positive integer identifier and priority levels from 1 (highest) to 5 (lowest), the task is to reorder the projects such that hi... |
def find_max(numbers):
if not numbers:
return None
return max(numbers) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that finds the maximum number in a list. If the list is empty, the function should return `None` instead of `-inf`. How can I do this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4303,
"level": 1,
"question": "Create a function that finds the maximum number in a list. If the list is empty, the function should return `None` instead of `-inf`. How can I do this?",
"split": "train"
} |
def validate_account_number(account_number: str, min_length: int, max_length: int) -> bool:
# Check if the account number contains only digits
if not account_number.isdigit():
return False
# Check if the length is within the specified range
length = len(account_number)
if not (min_length <= ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Function Implementation Question\n\n**Context**: \nYou are tasked with writing a new feature for a banking software that verifies account numbers. An account number must adhere to specific length constraints to ensure proper format and avoid errors during transactions.\n\n**Problem ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4304,
"level": 1,
"question": "### Function Implementation Question\n\n**Context**: \nYou are tasked with writing a new feature for a banking software that verifies account numbers. An account number must adhere to specific length constraints to ensure proper format and avoid errors... |
def find_longest_word(lst):
longest_length = 0
longest_word = ""
for word in lst:
current_length = len(word)
if current_length > longest_length:
longest_length = current_length
longest_word = word
return longest_word | simplelr_Filter | [
{
"content": "Question:\nYou've been tasked with writing a function `find_longest_word` that takes a list of strings as input and returns the longest word in the list. If there are multiple words with the same maximum length, the function should return the first word it encounters with that length.\nAnswer:\nLe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4305,
"level": 1,
"question": "You've been tasked with writing a function `find_longest_word` that takes a list of strings as input and returns the longest word in the list. If there are multiple words with the same maximum length, the function should return the first word it encoun... |
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
less = []
equal = []
greater = []
for x in arr:
if x < pivot:
less.append(x)
elif x == pivot:
equal.append(x)
else:
greater.append(x)
return quicksort(less) + e... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to sort an array of integers using the quicksort algorithm. What are the key steps involved in this sorting algorithm?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4306,
"level": 1,
"question": "Write a function to sort an array of integers using the quicksort algorithm. What are the key steps involved in this sorting algorithm?",
"split": "train"
} |
import math
from typing import List
def jump_search(arr: List[int], target: int) -> int:
if not arr:
return -1
n = len(arr)
step = int(math.sqrt(n))
current = 0
# Find the block where the target could be
while current < n and arr[current] < target:
current += step
... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario:\nYou are a software developer tasked with optimizing search operations on a large, sorted dataset. The dataset represents a list of product prices in ascending order. Given the requirement for frequent and fast searches, you decide to utilize the Jump Search algorithm for... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4307,
"level": 1,
"question": "#### Scenario:\nYou are a software developer tasked with optimizing search operations on a large, sorted dataset. The dataset represents a list of product prices in ascending order. Given the requirement for frequent and fast searches, you decide to ut... |
def evaluate_expression(s):
# Tokenize the string into numbers and operators
tokens = []
current_number = ''
for char in s:
if char in '+-*':
if current_number:
tokens.append(int(current_number))
current_number = ''
tokens.append(char)
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` representing a mathematical expression with only non-negative integers and the operators `'+'`, `'-'`, and `'*'`. Implement a function to evaluate the expression and return its result. The integer division should truncate toward zero. Note that the expressions... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4308,
"level": 1,
"question": "You are given a string `s` representing a mathematical expression with only non-negative integers and the operators `'+'`, `'-'`, and `'*'`. Implement a function to evaluate the expression and return its result. The integer division should truncate tow... |
def tree_print(tree):
for key in tree:
elements = [key] + tree[key]
line = ' -> '.join(map(str, elements))
print(line)
# Test your function with the sample dataset
tree = {
'a': ['Adam', 'Book', 4],
'b': ['Bill', 'Computer', 5, 'TV', 6, 'Jill', 'Sports', 1],
'c': ['Bill', 'Sport... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Tree-Based Data Structure Manipulation and Output Formatting\n\nSuppose you have hierarchical data represented as a nested dictionary, and you need to implement a function to print this data in a specified format. You are provided with a sample dataset and a partially impl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4309,
"level": 1,
"question": "### Question: Tree-Based Data Structure Manipulation and Output Formatting\n\nSuppose you have hierarchical data represented as a nested dictionary, and you need to implement a function to print this data in a specified format. You are provided with a ... |
def rotate(matrix):
# Transpose the matrix
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse()
return matrix
| simplelr_Taco | [
{
"content": "Question:\n## Rotate Matrix\n\nYou are given an `n x n` 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). \n\nYou should rotate the image in-place, which means you have to modify the input 2D matrix directly. Do not allocate another 2D matrix and do the rotation.\n\n### ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4310,
"level": 1,
"question": "## Rotate Matrix\n\nYou are given an `n x n` 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). \n\nYou should rotate the image in-place, which means you have to modify the input 2D matrix directly. Do not allocate another 2D ... |
from typing import List
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
# Sort intervals based on the start time
sorted_intervals = sorted(intervals, key=lambda x: x[0])
merged = []
for interval in sorted_intervals:
if not me... | simplelr_Apps | [
{
"content": "Question:\n**[Problem Statement]**\n\n# Merge Intervals\n\n## Task\nGiven a collection of intervals, merge all overlapping intervals.\n\n## Description\nYou are given an array of intervals, where each interval is represented as a list with its start and end times `[start, end]`. Your task is to wr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4311,
"level": 1,
"question": "**[Problem Statement]**\n\n# Merge Intervals\n\n## Task\nGiven a collection of intervals, merge all overlapping intervals.\n\n## Description\nYou are given an array of intervals, where each interval is represented as a list with its start and end times... |
import re
def validate_html_nesting(input_string: str) -> bool:
tags = re.findall(r'<([^>]+)>', input_string)
stack = []
for tag in tags:
if tag.startswith('/'):
if not stack:
return False
expected = tag[1:].lower()
top = stack.pop()
i... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nAs a software engineer, you are asked to write a function that can validate the structural integrity of HTML-like nested tags within a string. The goal is to ensure that each opening tag has a corresponding closing tag and that tags are properly nested.\n\n### Task\nImplem... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4312,
"level": 1,
"question": "### Scenario\nAs a software engineer, you are asked to write a function that can validate the structural integrity of HTML-like nested tags within a string. The goal is to ensure that each opening tag has a corresponding closing tag and that tags are p... |
import itertools
def unique_permutations(s):
perms = itertools.permutations(s)
unique_perms = {''.join(p) for p in perms}
return sorted(unique_perms)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a string as input and returns a list of all the unique permutations of the characters in the string. The function should sort the list of permutations lexicographically before returning it. The input string will only contain lowercase letters, and its length ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4313,
"level": 1,
"question": "Write a function that takes a string as input and returns a list of all the unique permutations of the characters in the string. The function should sort the list of permutations lexicographically before returning it. The input string will only contain... |
def is_square_free(num):
for i in range(2, int(num**0.5) + 1):
if num % (i * i) == 0:
return False
return True | simplelr_Apps | [
{
"content": "Question:\n# Square-free Numbers\n\nA number is square-free if it is not divisible by any perfect square greater than 1. Given an integer `num`, write a function `is_square_free` that returns `True` if `num` is square-free, and `False` otherwise.\n\n## Your task\n\nIn this Kata, you will be tasked... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4314,
"level": 1,
"question": "# Square-free Numbers\n\nA number is square-free if it is not divisible by any perfect square greater than 1. Given an integer `num`, write a function `is_square_free` that returns `True` if `num` is square-free, and `False` otherwise.\n\n## Your task\... |
def hello_world():
print("Hello, World!")
hello_world() | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that prints the classic \"Hello, World!\" message to the console?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4315,
"level": 1,
"question": "How can I create a Python function that prints the classic \"Hello, World!\" message to the console?",
"split": "train"
} |
from typing import List, Tuple
def total_sales(transactions: List[Tuple[str, float, int]]) -> float:
total = 0.0
for item, price, quantity in transactions:
total += price * quantity
return round(total, 2) | simplelr_Package | [
{
"content": "Question:\nYou are given a list of transactions, each represented as a tuple `(item, price, quantity)`. Your task is to implement a function `total_sales(transactions: List[Tuple[str, float, int]]) -> float` that performs the following operations:\n\n1. Calculate the total sales amount by multiply... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4316,
"level": 1,
"question": "You are given a list of transactions, each represented as a tuple `(item, price, quantity)`. Your task is to implement a function `total_sales(transactions: List[Tuple[str, float, int]]) -> float` that performs the following operations:\n\n1. Calculate... |
def to_uppercase(s):
return s.upper() | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to convert all the characters in a string to uppercase.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4317,
"level": 1,
"question": "Write a function to convert all the characters in a string to uppercase.",
"split": "train"
} |
def max_sum_subarray(arr, k):
if not arr or k == 0:
return 0
n = len(arr)
if k > n:
return 0
current_sum = sum(arr[:k])
max_sum = current_sum
for i in range(1, n - k + 1):
current_sum = current_sum - arr[i - 1] + arr[i + k - 1]
if current_sum > max_sum:
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum sum of any contiguous subarray of size `k` in a given list of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4318,
"level": 1,
"question": "Write a python function to find the maximum sum of any contiguous subarray of size `k` in a given list of integers.",
"split": "train"
} |
def modular_exponentiation(a, b, m):
if m == 1:
return 0
result = 1
a = a % m # Reduce 'a' modulo m to make it smaller
while b > 0:
if b % 2 == 1: # If 'b' is odd
result = (result * a) % m
a = (a * a) % m
b = b // 2
return result
# Example usage:
a = 3
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that calculates the value of the expression `a^b % m` using the concept of modular exponentiation, assuming 'a', 'b', and 'm' are positive integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4319,
"level": 1,
"question": "Write a Python program that calculates the value of the expression `a^b % m` using the concept of modular exponentiation, assuming 'a', 'b', and 'm' are positive integers.",
"split": "train"
} |
def find_min_in_rotated_sorted_array(nums: list[int]) -> int:
"""
Finds the minimum element in a rotated sorted array using binary search.
Args:
nums: A rotated sorted array of integers.
Returns:
The minimum element in the array.
"""
left = 0
right = len(nums) - 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context\nYou are working on a project involving efficient search algorithms in sorted integer arrays. One common task is to find the minimum element in a sorted and rotated array, which is a typical problem in understanding search techniques and al... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4320,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context\nYou are working on a project involving efficient search algorithms in sorted integer arrays. One common task is to find the minimum element in a sorted and rotated array, which is a typical problem in und... |
def edit_distance(word_a: str, word_b: str) -> int:
len_a = len(word_a)
len_b = len(word_b)
# Create a DP table of (len_a+1) x (len_b+1)
dp = [[0] * (len_b + 1) for _ in range(len_a + 1)]
# Initialize the first row and column
for i in range(len_a + 1):
dp[i][0] = i
for j in... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are working on a text-analysis tool that helps detect spelling errors and suggests corrections. One fundamental operation required is calculating the edit distance between two words, which will help you determine how similar two words are.\n\nYour task is to implement a function `ed... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4321,
"level": 1,
"question": "You are working on a text-analysis tool that helps detect spelling errors and suggests corrections. One fundamental operation required is calculating the edit distance between two words, which will help you determine how similar two words are.\n\nYour ... |
import heapq
def dijkstra(graph: dict[str, list[tuple[str, int]]], start: str) -> dict[str, float]:
# Initialize distances to infinity for all nodes
distances = {node: float('inf') for node in graph}
distances[start] = 0 # Distance to start is zero
# Priority queue to process nodes, initialized w... | simplelr_Algorithm | [
{
"content": "Question:\n### Dijkstra's Shortest Path Algorithm\n\n#### Problem Statement\nYou are given a directed graph represented as an adjacency list and a starting vertex. Your task is to implement Dijkstra's algorithm to find the shortest path from the starting vertex to all other vertices in the graph. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4322,
"level": 1,
"question": "### Dijkstra's Shortest Path Algorithm\n\n#### Problem Statement\nYou are given a directed graph represented as an adjacency list and a starting vertex. Your task is to implement Dijkstra's algorithm to find the shortest path from the starting vertex t... |
def search_matrix(matrix, target):
if not matrix or not matrix[0]:
return [-1, -1]
m = len(matrix)
n = len(matrix[0])
i, j = 0, n - 1
while i < m and j >= 0:
if matrix[i][j] == target:
return [i, j]
elif matrix[i][j] < target:
i += 1
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a `m x n` matrix where each element has a value of **0** or **1**. Each row and column of the matrix is sorted in non-decreasing order. Find the position of a given `target` value within the matrix. Return a list containing the row and column indices of the target if it ex... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4323,
"level": 1,
"question": "You are given a `m x n` matrix where each element has a value of **0** or **1**. Each row and column of the matrix is sorted in non-decreasing order. Find the position of a given `target` value within the matrix. Return a list containing the row and co... |
from collections import Counter
def are_permutations(str1: str, str2: str) -> bool:
"""
Checks if the two given strings are permutations of each other.
:param str1: First input string.
:param str2: Second input string.
:return: True if the strings are permutations of each other, False otherwise.
... | simplelr_Algorithm | [
{
"content": "Question:\n### Character Permutations Checker\n\nCreate a function that determines whether two given strings are permutations of each other. Two strings are considered permutations if you can rearrange one to get the other using exactly the same characters and frequency. This function will help en... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4324,
"level": 1,
"question": "### Character Permutations Checker\n\nCreate a function that determines whether two given strings are permutations of each other. Two strings are considered permutations if you can rearrange one to get the other using exactly the same characters and fr... |
import bisect
def isSubsequence(S, Q, Queries):
# Preprocess S to create a dictionary mapping each character to its indices
char_indices = {}
for idx, c in enumerate(S):
if c not in char_indices:
char_indices[c] = []
char_indices[c].append(idx)
answers = []
for P in... | simplelr_Taco | [
{
"content": "Question:\nYou are given a string S consisting of lowercase English letters. You need to answer Q queries, each query consists of a string P for which you need to find out whether P is a subsequence of S or not. A subsequence is a sequence that can be derived from another sequence by deleting some... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4325,
"level": 1,
"question": "You are given a string S consisting of lowercase English letters. You need to answer Q queries, each query consists of a string P for which you need to find out whether P is a subsequence of S or not. A subsequence is a sequence that can be derived fro... |
def reverse_array(original):
reversed_list = []
for i in range(len(original)-1, -1, -1):
reversed_list.append(original[i])
return reversed_list | simplelr_Filter | [
{
"content": "Question:\nCode an algorithm to reverse an array of positive integers and return a new array without modifying the original array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4326,
"level": 1,
"question": "Code an algorithm to reverse an array of positive integers and return a new array without modifying the original array.",
"split": "train"
} |
def min_add_to_make_balanced(s):
balance = 0
needed = 0
for c in s:
if c == '(':
balance += 1
else:
balance -= 1
if balance < 0:
needed += 1
balance = 0
return needed + balance | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that checks the balance of parentheses in a given string and returns the minimum number of parentheses that need to be added to make the string a balanced one. A string is considered balanced if every opening parenthesis `(` has a corresponding closing parenthes... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4327,
"level": 1,
"question": "Create a Python function that checks the balance of parentheses in a given string and returns the minimum number of parentheses that need to be added to make the string a balanced one. A string is considered balanced if every opening parenthesis `(` ha... |
def min_operations(S: str) -> int:
counts = [0] * 26
n = len(S)
for c in S:
counts[ord(c) - ord('a')] += 1
max_freq = max(counts)
return n - max_freq | simplelr_Code_Contests | [
{
"content": "Question:\nGiven a string S consisting of lowercase English letters, you need to determine the minimum number of operations required to make all the characters in the string the same. \n\nIn one operation, you can choose any character from the string and change it to any other character.\n\nWrite ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4328,
"level": 1,
"question": "Given a string S consisting of lowercase English letters, you need to determine the minimum number of operations required to make all the characters in the string the same. \n\nIn one operation, you can choose any character from the string and change i... |
def filter_duplicates(input_list):
seen = set()
result = []
for group in input_list:
group_tuple = tuple(group)
if group_tuple not in seen:
seen.add(group_tuple)
result.append(group)
return result | simplelr_Filter | [
{
"content": "Question:\nHere is a simple Python program to filter out the duplicate elements from a list. How would you rewrite the function `filter_duplicates` to handle a list of lists, where each inner list represents a group of elements that should be treated as a single unit?\nAnswer:\nLet's think step by... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4329,
"level": 1,
"question": "Here is a simple Python program to filter out the duplicate elements from a list. How would you rewrite the function `filter_duplicates` to handle a list of lists, where each inner list represents a group of elements that should be treated as a single ... |
def reverse_sentence(s):
words = s.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` representing a **sentence** where each word is separated by a single space, return the **reversed** sentence such that the words appear in reverse order but the words themselves are not reversed. For example, given `s` = \"hello world\", the output should be \"world h... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4330,
"level": 1,
"question": "Given a string `s` representing a **sentence** where each word is separated by a single space, return the **reversed** sentence such that the words appear in reverse order but the words themselves are not reversed. For example, given `s` = \"hello worl... |
import torch
def can_use_persistent_algorithm(input_tensor: torch.Tensor, gpu_type: str) -> bool:
return (torch.backends.cudnn.enabled and
input_tensor.is_cuda and
input_tensor.dtype == torch.float16 and
gpu_type == "V100")
| simplelr_Docs | [
{
"content": "Question:\n**Question:**\n\nYou are tasked with implementing a function in PyTorch to check if certain conditions are met to enable the persistent algorithm for performance improvement. \n\n**Function Signature:**\n```python\nimport torch\n\ndef can_use_persistent_algorithm(input_tensor: torch.Ten... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4331,
"level": 1,
"question": "**Question:**\n\nYou are tasked with implementing a function in PyTorch to check if certain conditions are met to enable the persistent algorithm for performance improvement. \n\n**Function Signature:**\n```python\nimport torch\n\ndef can_use_persisten... |
def is_anagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
for c in t:
count[ord(c) - ord('a')] -= 1
for v in count:
if v != 0:
return False
return True | simplelr_Apps | [
{
"content": "Question:\nGiven two strings s and t, write a function to determine if t is an anagram of s. \n\nExample 1:\nInput: s = \"anagram\", t = \"nagaram\"\nOutput: true\n\nExample 2:\nInput: s = \"rat\", t = \"car\"\nOutput: false\n\nExplanation:\nt is an anagram of s if it uses the same characters in t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4332,
"level": 1,
"question": "Given two strings s and t, write a function to determine if t is an anagram of s. \n\nExample 1:\nInput: s = \"anagram\", t = \"nagaram\"\nOutput: true\n\nExample 2:\nInput: s = \"rat\", t = \"car\"\nOutput: false\n\nExplanation:\nt is an anagram of s ... |
def processOperations(operations):
stack = []
for op in operations:
if op > 0:
stack.append(op)
elif op == 0:
if not stack:
return []
stack.append(stack[-1])
else:
k = -op
if k > len(stack):
retur... | simplelr_Taco | [
{
"content": "Question:\nYou are given an array of integers representing a sequence of operations of a stack machine. The machine supports the following operations:\n- A positive integer n pushes n onto the stack.\n- A negative integer n pops the top -n elements from the stack.\n- A zero (0) duplicates the top ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4333,
"level": 1,
"question": "You are given an array of integers representing a sequence of operations of a stack machine. The machine supports the following operations:\n- A positive integer n pushes n onto the stack.\n- A negative integer n pops the top -n elements from the stack... |
def second_last_element(arr):
if len(arr) < 2:
return -1
return arr[-2] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers and returns the second last (penultimate) element in the array. If the array has less than two elements, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4334,
"level": 1,
"question": "Create a function that takes an array of integers and returns the second last (penultimate) element in the array. If the array has less than two elements, return -1.",
"split": "train"
} |
def fizzbuzz():
for i in range(1, 101):
s = ""
if i % 3 == 0:
s += "Fizz"
if i % 5 == 0:
s += "Buzz"
print(s if s else i) | simplelr_Filter | [
{
"content": "Question:\nThis is a coding challenge.\n\n**Challenge:** Create a FizzBuzz function in Python.\n\n**Description:**\n\nThe FizzBuzz challenge is a classic programming problem. The goal is to write a function that prints the numbers from 1 to 100.\n\nHowever, for multiples of 3, print \"Fizz\" inste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4335,
"level": 1,
"question": "This is a coding challenge.\n\n**Challenge:** Create a FizzBuzz function in Python.\n\n**Description:**\n\nThe FizzBuzz challenge is a classic programming problem. The goal is to write a function that prints the numbers from 1 to 100.\n\nHowever, for m... |
def sum_numbers(n):
if n < 1:
return 0
return n * (n + 1) // 2 | simplelr_Filter | [
{
"content": "Question:\nYou've been asked to write a Python function that calculates the sum of all the integers from 1 up to a given number (inclusive). This function should take one argument, the upper limit of the range of numbers to be summed, and return the sum of all the integers from 1 up to this number... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4336,
"level": 1,
"question": "You've been asked to write a Python function that calculates the sum of all the integers from 1 up to a given number (inclusive). This function should take one argument, the upper limit of the range of numbers to be summed, and return the sum of all th... |
def authorized_employees(n, m, k, employees, elevators, target_floor):
# Find elevators that can reach the target floor (using 1-based index)
relevant_elevators = set()
for idx in range(m):
start, end = elevators[idx]
if start <= target_floor <= end:
relevant_elevators.add(idx + ... | simplelr_Taco | [
{
"content": "Question:\nElevator Access Control\n\nIn a modern building, the elevators are controlled by an algorithm which grants access to authorized personnel. Each elevator has a unique set of floors it can access, and each employee has a list of elevators they are authorized to use. The building's securit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4337,
"level": 1,
"question": "Elevator Access Control\n\nIn a modern building, the elevators are controlled by an algorithm which grants access to authorized personnel. Each elevator has a unique set of floors it can access, and each employee has a list of elevators they are author... |
from typing import List
def optimized_matrix_multiplication(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
if not A or not A[0]:
return []
m = len(A)
n = len(A[0])
p = len(B[0])
# Transpose matrix B for efficient column access
B_T = list(map(list, zip(*B)))
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question: Optimizing Matrix Multiplication\n\n#### Problem Statement\nYou are given two matrices `A` and `B` and your task is to implement an optimized matrix multiplication algorithm. Your solution should aim to handle large matrices efficiently.\n\n### Requiremen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4338,
"level": 1,
"question": "### Coding Assessment Question: Optimizing Matrix Multiplication\n\n#### Problem Statement\nYou are given two matrices `A` and `B` and your task is to implement an optimized matrix multiplication algorithm. Your solution should aim to handle large matr... |
def improve_skyline(heights):
if not heights:
return []
res = [heights[0]]
for h in heights[1:]:
res.append(min(h, res[-1]))
return res | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a list of integers representing the heights of buildings in a city skyline. The city council wants to improve the skyline's appearance by making sure no building is taller than the previous one when viewed from left to right. To achieve this, they have allowed you to reduc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4339,
"level": 1,
"question": "You are given a list of integers representing the heights of buildings in a city skyline. The city council wants to improve the skyline's appearance by making sure no building is taller than the previous one when viewed from left to right. To achieve t... |
from collections import Counter
def word_frequency(words):
counts = Counter(words)
tuples = list(counts.items())
sorted_tuples = sorted(tuples, key=lambda x: (-x[1], x[0]))
return sorted_tuples | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code that takes a list of strings as input and returns a list of tuples. Each tuple should contain the word and its frequency in the input list of strings. The order of the tuples in the output list should be sorted by the frequency in descending order. If two words have ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4340,
"level": 1,
"question": "Write a Python code that takes a list of strings as input and returns a list of tuples. Each tuple should contain the word and its frequency in the input list of strings. The order of the tuples in the output list should be sorted by the frequency in d... |
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[-1]
less = []
equal = []
greater = []
for elem in arr:
if elem < pivot:
less.append(elem)
elif elem == pivot:
equal.append(elem)
else:
greater.append(elem)
return ... | simplelr_Filter | [
{
"content": "Question:\nI have a list of integers and I want to sort it in Python using the quicksort algorithm. Can you provide a sample implementation?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4341,
"level": 1,
"question": "I have a list of integers and I want to sort it in Python using the quicksort algorithm. Can you provide a sample implementation?",
"split": "train"
} |
import heapq
def min_cost_path(cost):
if not cost or not cost[0]:
return 0
n = len(cost)
m = len(cost[0])
INF = float('inf')
dist = [[INF for _ in range(m)] for _ in range(n)]
dist[0][0] = cost[0][0]
heap = []
heapq.heappush(heap, (dist[0][0], 0, 0))
directions = [(-1, ... | simplelr_Code_Contests | [
{
"content": "Question:\nYou are given an endless 2D grid of rooms, each room has a different cost to enter, represented by a 2D array. You are initially positioned in the top-left room and you need to find a path to the bottom-right room that minimizes the sum of the costs of the rooms along the path. You can ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4342,
"level": 1,
"question": "You are given an endless 2D grid of rooms, each room has a different cost to enter, represented by a 2D array. You are initially positioned in the top-left room and you need to find a path to the bottom-right room that minimizes the sum of the costs of... |
def count_strings(string_list):
counts = {}
for s in string_list:
key = s.lower()
if key in counts:
counts[key] += 1
else:
counts[key] = 1
return counts | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes a list of strings as input and returns a dictionary where each unique string is a key and its value is the number of times it appears in the list. The function should ignore case sensitivity when counting occurrences. For example, if the input is `[... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4343,
"level": 1,
"question": "Write a function in Python that takes a list of strings as input and returns a dictionary where each unique string is a key and its value is the number of times it appears in the list. The function should ignore case sensitivity when counting occurrenc... |
def count_words(words):
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
return word_counts | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that receives a list of words as its parameter and returns a dictionary where the keys are the words from the list and the values are the counts of how many times each word appears in the list. You can assume that the input list will contain at least one word.\nAnswer:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4344,
"level": 1,
"question": "Create a function that receives a list of words as its parameter and returns a dictionary where the keys are the words from the list and the values are the counts of how many times each word appears in the list. You can assume that the input list will ... |
from typing import List
import traceback
import sys
def execute_and_trace(code_lines: List[str]) -> None:
namespace = {} # To hold variables across code lines
for line in code_lines:
try:
exec(line, namespace)
except BaseException as exc:
type_, value, tb = sys.exc_inf... | simplelr_Docs | [
{
"content": "Question:\n### Python Coding Assessment: Handling and Formatting Exceptions\n\n#### Objective\nWrite a Python program that can execute a sequence of code lines provided by the user, handle any exceptions that occur, and print a formatted stack trace and traceback information using the `traceback` ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4345,
"level": 1,
"question": "### Python Coding Assessment: Handling and Formatting Exceptions\n\n#### Objective\nWrite a Python program that can execute a sequence of code lines provided by the user, handle any exceptions that occur, and print a formatted stack trace and traceback... |
def romanToInt(s):
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
for i in range(len(s)):
current = roman_dict[s[i]]
if i < len(s) - 1:
next_val = roman_dict[s[i+1]]
if current < next_val:
total -= current
... | simplelr_Leetcode | [
{
"content": "Question:\nImplement a function `int romanToInt(string s)` that converts a Roman numeral to an integer. Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M. Each symbol has a corresponding integer value: \n\n- I : 1 \n- V : 5 \n- X : 10 \n- L : 50 \n- C : 100 \n- D :... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4346,
"level": 1,
"question": "Implement a function `int romanToInt(string s)` that converts a Roman numeral to an integer. Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M. Each symbol has a corresponding integer value: \n\n- I : 1 \n- V : 5 \n- X ... |
def longest_unique_substring(s):
last_occurrence = {}
max_len = 0
start = 0
for end in range(len(s)):
char = s[end]
if char in last_occurrence and last_occurrence[char] >= start:
start = last_occurrence[char] + 1
last_occurrence[char] = end
current_len = end -... | simplelr_Taco | [
{
"content": "Question:\nFind the length of the longest sequence of unique characters in a given string `s`.\n\nThe string will only contain alphabetic characters (both uppercase and lowercase) and its length will not exceed 10,000.\n\n## Examples\n```python\nlongest_unique_substring(\"abcabcbb\") == 3 # \"abc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4347,
"level": 1,
"question": "Find the length of the longest sequence of unique characters in a given string `s`.\n\nThe string will only contain alphabetic characters (both uppercase and lowercase) and its length will not exceed 10,000.\n\n## Examples\n```python\nlongest_unique_su... |
import re
def string_to_word_list(s):
return re.findall(r'[a-zA-Z]+|[^a-zA-Z\s]', s.strip())
# Example usage:
# string_to_tokens("Hello, world!")
# Output: ['Hello', ',', 'world', '!'] | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code snippet that converts a string to a list of words, considering punctuation as separate tokens and removing any leading or trailing whitespace?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4348,
"level": 1,
"question": "Can you provide a Python code snippet that converts a string to a list of words, considering punctuation as separate tokens and removing any leading or trailing whitespace?",
"split": "train"
} |
def calculate_median(values):
sorted_values = sorted(values)
n = len(sorted_values)
if n % 2 == 0:
mid1 = sorted_values[(n // 2) - 1]
mid2 = sorted_values[n // 2]
return (mid1 + mid2) / 2
else:
return sorted_values[n // 2] | simplelr_Filter | [
{
"content": "Question:\ndef calculate_median(values):\n \"\"\"Calculate the median from a list of values\"\"\"\n values = sorted(values)\n count = len(values)\n if count % 2 == 0:\n return (values[count // 2 - 1] + values[count // 2]) / 2.0\n else:\n return values[count // 2]\nAnsw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4349,
"level": 1,
"question": "def calculate_median(values):\n \"\"\"Calculate the median from a list of values\"\"\"\n values = sorted(values)\n count = len(values)\n if count % 2 == 0:\n return (values[count // 2 - 1] + values[count // 2]) / 2.0\n else:\n ... |
def rotate_matrix(matrix: list[list[int]]) -> None:
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]
# Reverse each row
for row in matrix:
row.reverse() | simplelr_Evol | [
{
"content": "Question:\nYou are given a matrix of integers and your task is to write a function that rotates the matrix by 90 degrees clockwise. \n\nFor example, given the following 3x3 matrix:\n\n```\n[\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\n```\n\nThe rotated matrix should be:\n\n```\n[\n [7, 4, 1],\n [8,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4350,
"level": 1,
"question": "You are given a matrix of integers and your task is to write a function that rotates the matrix by 90 degrees clockwise. \n\nFor example, given the following 3x3 matrix:\n\n```\n[\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\n```\n\nThe rotated matrix shou... |
import http.client
from urllib.parse import urlparse
def fetch_data(url, method):
# Parse the URL
parsed_url = urlparse(url)
# Extract host and path
host = parsed_url.netloc
path = parsed_url.path or "/"
# Create an HTTP connection
connection = http.client.HTTPConnection(host)
... | simplelr_Docs | [
{
"content": "Question:\n### HTTP Client Implementation using `http.client`\n\n#### Objective\n\nDemonstrate your ability to use the `http.client` module to interact with web resources programmatically by implementing a function that fetches data from a specified HTTP endpoint and processes different HTTP respo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4351,
"level": 1,
"question": "### HTTP Client Implementation using `http.client`\n\n#### Objective\n\nDemonstrate your ability to use the `http.client` module to interact with web resources programmatically by implementing a function that fetches data from a specified HTTP endpoint... |
def filter_by_threshold(lst, k):
return [x for x in lst if x >= k]
| simplelr_Taco | [
{
"content": "Question:\nWrite a program that takes a list of integers and an integer k, and returns a new list containing elements from the input list that are greater than or equal to k. \nThe output list should be in the same relative order as the input list.\n\nYour program should be efficient to handle lar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4352,
"level": 1,
"question": "Write a program that takes a list of integers and an integer k, and returns a new list containing elements from the input list that are greater than or equal to k. \nThe output list should be in the same relative order as the input list.\n\nYour progra... |
def custom_power(a: int, n: int, m: int) -> int:
if n == 0:
return 1 % m
result = 1
base = a % m
while n > 0:
if n % 2 == 1:
result = (result * base) % m
base = (base * base) % m
n = n // 2
return result | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with implementing a power function using binary exponentiation (iterative approach), which computes `a^n (mod m)` efficiently.\n\n**Function Signature:**\n```python\ndef custom_power(a: int, n: int, m: int) -> int:\n pass\n```\n\n### Input:\n* `a` (int): The base of th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4353,
"level": 1,
"question": "You are tasked with implementing a power function using binary exponentiation (iterative approach), which computes `a^n (mod m)` efficiently.\n\n**Function Signature:**\n```python\ndef custom_power(a: int, n: int, m: int) -> int:\n pass\n```\n\n### ... |
from typing import List, Tuple
def separate_even_odd(numbers: List[int]) -> Tuple[List[int], List[int]]:
evens = []
odds = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return (evens, odds) | simplelr_Code_Contests | [
{
"content": "Question:\nGiven a list of integers, write a function that separates the list into two new lists: one containing all the even numbers and the other containing all the odd numbers. The function should return a tuple containing both lists. The even and odd lists should maintain the original order of... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4354,
"level": 1,
"question": "Given a list of integers, write a function that separates the list into two new lists: one containing all the even numbers and the other containing all the odd numbers. The function should return a tuple containing both lists. The even and odd lists sh... |
def find_longest_palindrome(s: str) -> str:
max_len = 0
max_start = 0
max_end = 0
n = len(s)
for i in range(n):
# Check for odd length palindromes
left, right = i, i
while left >= 0 and right < n and s[left] == s[right]:
left -= 1
right += 1
cu... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `find_longest_palindrome(s: str) -> str` that takes a string `s` and returns the longest palindromic substring in `s`. If there are multiple palindromic substrings of the same maximum length, return the first one found. Assume the input string's length is at leas... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4355,
"level": 1,
"question": "Write a Python function `find_longest_palindrome(s: str) -> str` that takes a string `s` and returns the longest palindromic substring in `s`. If there are multiple palindromic substrings of the same maximum length, return the first one found. Assume t... |
def find_non_decreasing_sequences(arr):
n = len(arr)
if n == 0:
return []
result = []
start = 0
for i in range(n - 1):
if arr[i] > arr[i + 1]:
result.append([start, i])
start = i + 1
result.append([start, n - 1])
return result | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes in a list of integers `arr` and returns a list of lists (or 2D array) where each sublist contains the start and end indices of the consecutive elements in `arr` that form a non-decreasing sequence. If there are no such consecutive elements, return an empty li... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4356,
"level": 1,
"question": "Write a function that takes in a list of integers `arr` and returns a list of lists (or 2D array) where each sublist contains the start and end indices of the consecutive elements in `arr` that form a non-decreasing sequence. If there are no such conse... |
def find_duplicate(nums):
n = len(nums) - 1
expected = n * (n + 1) // 2
actual = sum(nums)
return actual - expected | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive, return the duplicate number.\n\nYou must solve the problem without modifying the array nums and uses only constant extra space.\n\nExample 1:\nInput: nums = [1,3,4,2,2]\nOutput... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4357,
"level": 1,
"question": "Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive, return the duplicate number.\n\nYou must solve the problem without modifying the array nums and uses only constant extra space.\n\nExample 1:... |
def sum_positive_numbers(numbers):
return sum(num for num in numbers if num > 0) | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns the sum of all the positive numbers in the list.\n\nExample:\n```python\ndef sum_positive_numbers(numbers):\n # Your code here\n\n# Test case\nnumbers = [-1, 2, 3, -4, 5]\nprint(sum_positive_numbers(numbers)) # Output should... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4358,
"level": 1,
"question": "Write a function that takes a list of integers and returns the sum of all the positive numbers in the list.\n\nExample:\n```python\ndef sum_positive_numbers(numbers):\n # Your code here\n\n# Test case\nnumbers = [-1, 2, 3, -4, 5]\nprint(sum_positive... |
def is_zig_zag_array(arr):
if len(arr) < 3:
return True
for i in range(1, len(arr) - 1):
current = arr[i]
prev = arr[i - 1]
next_val = arr[i + 1]
if not ((prev < current and current > next_val) or (prev > current and current < next_val)):
return False
retu... | simplelr_Apps | [
{
"content": "Question:\nA zig-zag array is an array that satisfies the following condition for all values of `i`:\n\nIf both `i > 0` and `i < array.length - 1`:\n\n* Either `array[i-1] < array[i] > array[i+1]`\n* Or `array[i-1] > array[i] < array[i+1]`\n\n### Examples:\n\n```\n[1, 3, 2, 4, 3] => true (as 1<... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4359,
"level": 1,
"question": "A zig-zag array is an array that satisfies the following condition for all values of `i`:\n\nIf both `i > 0` and `i < array.length - 1`:\n\n* Either `array[i-1] < array[i] > array[i+1]`\n* Or `array[i-1] > array[i] < array[i+1]`\n\n### Examples:\n\n```... |
from typing import List, Dict, Any
def filter_music_library(tracks: List[Dict[str, Any]], genre: str, max_duration: int) -> List[Dict[str, Any]]:
return [track for track in tracks if track['genre'] == genre and track['duration'] <= max_duration] | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Description\n\nYou are a developer working on a music streaming application. Your next task is to implement a feature that allows users to filter their music library based on specific criteria: genre and duration.\n\n### Task\n\nWrite a function `filter_music_library` which:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4360,
"level": 1,
"question": "### Problem Description\n\nYou are a developer working on a music streaming application. Your next task is to implement a feature that allows users to filter their music library based on specific criteria: genre and duration.\n\n### Task\n\nWrite a fun... |
from typing import List
def find_diagonal_order(mat: List[List[int]]) -> List[int]:
if not mat:
return []
rows = len(mat)
cols = len(mat[0])
max_s = (rows - 1) + (cols - 1)
result = []
for s in range(max_s + 1):
group = []
for i in range(s + 1):
j = s - ... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Description:\nYou are to implement a matrix diagonal traversal. In this problem, you'll write a function that returns an array containing the elements of a given matrix in diagonal order.\n\n### Function Signature:\n```python\ndef find_diagonal_order(mat: List[List[int]]) ->... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4361,
"level": 1,
"question": "### Problem Description:\nYou are to implement a matrix diagonal traversal. In this problem, you'll write a function that returns an array containing the elements of a given matrix in diagonal order.\n\n### Function Signature:\n```python\ndef find_diag... |
import heapq
def find_shortest_path(city_map, start, destination):
if start not in city_map or destination not in city_map:
return []
distances = {node: float('infinity') for node in city_map}
distances[start] = 0
previous = {node: None for node in city_map}
priority_queue = ... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question:\n\n#### Context\nYou are developing a navigation application that provides real-time route optimization for delivery drivers. Part of this task requires calculating the shortest path from one location to another within a city. The city is represented as a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4362,
"level": 1,
"question": "### Coding Assessment Question:\n\n#### Context\nYou are developing a navigation application that provides real-time route optimization for delivery drivers. Part of this task requires calculating the shortest path from one location to another within a... |
def max_difference(arr):
if len(arr) < 2:
return -1
min_so_far = arr[0]
max_diff = -1
for i in range(1, len(arr)):
current = arr[i]
if current > min_so_far:
diff = current - min_so_far
if diff > max_diff:
max_diff = diff
else:
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum difference between two elements in a given array, where the larger number appears after the smaller number. If no such difference exists, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4363,
"level": 1,
"question": "Write a python function to find the maximum difference between two elements in a given array, where the larger number appears after the smaller number. If no such difference exists, return -1.",
"split": "train"
} |
import heapq
def dijkstra(graph, start):
"""
Find the shortest path in a graph from a start node to all other nodes using Dijkstra's algorithm.
Args:
graph (dict): An adjacency list representing the graph. Each key is a node, and its value is a list of tuples (neighbor, weight).
start (nod... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the shortest path in a graph using Dijkstra's algorithm. The graph is represented as an adjacency list, where each key is a node and its value is a list of tuples representing the adjacent nodes and their corresponding edge weights.\nAnswer:\nLet's think ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4364,
"level": 1,
"question": "Write a python function to find the shortest path in a graph using Dijkstra's algorithm. The graph is represented as an adjacency list, where each key is a node and its value is a list of tuples representing the adjacent nodes and their corresponding e... |
def apply_rules(rules, initial_state, input_string):
current_state = initial_state
index = 0
n = len(input_string)
while index < n:
current_char = input_string[index]
found = False
for rule in rules:
if rule['state'] == current_state and rule['char'] == current_c... | simplelr_Filter | [
{
"content": "Question:\nI have a set of rules (which are actually deterministic finite automata) that I need to apply to a given input string. The rules are defined as follows:\n\n- Each rule is a set of four elements: `state`, `char`, `next_state`, `accept`. \n- `state` is the current state of the DFA.\n- `ch... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4365,
"level": 1,
"question": "I have a set of rules (which are actually deterministic finite automata) that I need to apply to a given input string. The rules are defined as follows:\n\n- Each rule is a set of four elements: `state`, `char`, `next_state`, `accept`. \n- `state` is t... |
def gcd(a, b):
a = abs(a)
b = abs(b)
if b == 0:
return a
else:
return gcd(b, a % b) | simplelr_Filter | [
{
"content": "Question:\nAs a skilled math whiz, I have decided to create my own math library. However, I am struggling to implement the implementation of a function to calculate the greatest common divisor (GCD) of two numbers using recursion. I have a basic understanding of recursion but I need more practice ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4366,
"level": 1,
"question": "As a skilled math whiz, I have decided to create my own math library. However, I am struggling to implement the implementation of a function to calculate the greatest common divisor (GCD) of two numbers using recursion. I have a basic understanding of ... |
def is_sorted(stack: list) -> bool:
for i in range(len(stack) - 1):
if stack[i] > stack[i + 1]:
return False
return True | simplelr_Data_Structure | [
{
"content": "Question:\nStack Sorted Checker\n\n#### Context\nYou are working as a software engineer at a logistics company. One of your tasks is to ensure that cargo containers are arranged in order of increasing weight from bottom to top in a stacking system. For simplicity, you are given a software represen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4367,
"level": 1,
"question": "Stack Sorted Checker\n\n#### Context\nYou are working as a software engineer at a logistics company. One of your tasks is to ensure that cargo containers are arranged in order of increasing weight from bottom to top in a stacking system. For simplicity... |
from typing import List
def k_rotation(arr: List[int], k: int) -> List[int]:
n = len(arr)
effective_k = k % n
return arr[-effective_k:] + arr[:-effective_k] | simplelr_Apps | [
{
"content": "Question:\nGiven an array of size n, we denote its k-rotation as the array formed by rotating the original array k positions to the right. For example, a 2-rotation of `[1, 2, 3, 4]` would be `[3, 4, 1, 2]`.\n\nWrite a function that takes an array of integers and an integer k as input and returns ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4368,
"level": 1,
"question": "Given an array of size n, we denote its k-rotation as the array formed by rotating the original array k positions to the right. For example, a 2-rotation of `[1, 2, 3, 4]` would be `[3, 4, 1, 2]`.\n\nWrite a function that takes an array of integers and... |
def floyd_warshall(matrix):
n = len(matrix)
# Create a copy of the adjacency matrix to store the shortest paths
dist = [row.copy() for row in matrix]
# Set the distance from each node to itself to zero
for i in range(n):
dist[i][i] = 0
# Floyd-Warshall algorithm to find shortest paths
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to implement the Floyd-Warshall algorithm, which finds the shortest paths between all pairs of vertices in a weighted graph. The function should take a 2D list representing the adjacency matrix of the graph, where the value at matrix[i][j] is the weight of the edge betw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4369,
"level": 1,
"question": "Write a function to implement the Floyd-Warshall algorithm, which finds the shortest paths between all pairs of vertices in a weighted graph. The function should take a 2D list representing the adjacency matrix of the graph, where the value at matrix[i... |
from typing import List
def findLongestArithmeticSubsequence(nums: List[int]) -> int:
n = len(nums)
if n == 0:
return 0
dp = [{} for _ in range(n)]
max_length = 1 # At least one element
for i in range(n):
for j in range(i):
d = nums[i] - nums[j]
current_leng... | simplelr_Evol | [
{
"content": "Question:\n<p>Given an array of integers, find the longest subsequence in the array where the difference between subsequent elements is a constant value. You need to return the length of this longest subsequence.</p>\n\n<p>Write a function <code>findLongestArithmeticSubsequence(nums)</code> that t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4370,
"level": 1,
"question": "<p>Given an array of integers, find the longest subsequence in the array where the difference between subsequent elements is a constant value. You need to return the length of this longest subsequence.</p>\n\n<p>Write a function <code>findLongestArithm... |
def count_unique_triplets(nums, target):
nums.sort()
count = 0
n = len(nums)
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
j = i + 1
k = n - 1
while j < k:
current_sum = nums[i] + nums[j] + nums[k]
if current_sum ... | simplelr_Filter | [
{
"content": "Question:\nI need to develop a Python function that can find the number of unique triplets in a list that sum up to a specific target value. The function should handle a list of integers and a target integer, returning the count of unique triplets whose sum is exactly the target value. How can I i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4371,
"level": 1,
"question": "I need to develop a Python function that can find the number of unique triplets in a list that sum up to a specific target value. The function should handle a list of integers and a target integer, returning the count of unique triplets whose sum is ex... |
def count_valid_binary_passwords(n):
if n == 0:
return 1
elif n == 1:
return 2
a, b = 1, 2 # f(0) and f(1)
for _ in range(2, n + 1):
c = a + b
a, b = b, c
return b | simplelr_Codeforces | [
{
"content": "Question:\nIn a distant galaxy, there exists a special lock mechanism which opens only when provided with a binary password of size n. However, there are certain constraints to form the binary password. Specifically, no two consecutive '1's are allowed in the password.\n\nGiven the size n, write a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4372,
"level": 1,
"question": "In a distant galaxy, there exists a special lock mechanism which opens only when provided with a binary password of size n. However, there are certain constraints to form the binary password. Specifically, no two consecutive '1's are allowed in the pas... |
def find_first_event(events, event_type):
for event in events:
event_part = event.split(' ', 1)
current_type = event_part[0]
if current_type == event_type:
return event_part[1]
return "NOT FOUND" | simplelr_Codeforces | [
{
"content": "Question:\nA company wants to monitor user activity on their website. Each activity is characterized by an event type and a timestamp. The website developers have created a list of events, where each event is represented as a string in the format \"event_type timestamp\". The events are sorted chr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4373,
"level": 1,
"question": "A company wants to monitor user activity on their website. Each activity is characterized by an event type and a timestamp. The website developers have created a list of events, where each event is represented as a string in the format \"event_type tim... |
def longest_repeating_char(s):
if not s:
return ('', 0)
current_char = s[0]
current_count = 1
max_char = current_char
max_count = 1
for char in s[1:]:
if char == current_char:
current_count += 1
else:
if current_count > max_count:
... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and outputs the longest consecutive repeating character in the string along with its count.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4374,
"level": 1,
"question": "Create a function that takes a string as input and outputs the longest consecutive repeating character in the string along with its count.",
"split": "train"
} |
def multiply_strings(num1, num2):
if num1 == "0" or num2 == "0":
return "0"
n = len(num1)
m = len(num2)
reversed_num1 = num1[::-1]
reversed_num2 = num2[::-1]
result = [0] * (n + m)
for i in range(m):
digit2 = int(reversed_num2[i])
for j in range(n):
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two non-negative integers `num1` and `num2` represented as strings. The strings contain digits only and have no leading zeros. Write a function to multiply the two numbers and return the product as a string. \n\n* For example, if `num1 = \"123\"` and `num2 = \"456\"`, th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4375,
"level": 1,
"question": "You are given two non-negative integers `num1` and `num2` represented as strings. The strings contain digits only and have no leading zeros. Write a function to multiply the two numbers and return the product as a string. \n\n* For example, if `num1 ... |
def find_first_occurrence(array, target):
for i in range(len(array)):
if array[i] == target:
return i
return -1 | simplelr_Filter | [
{
"content": "Question:\nI have an array of numbers and I need to find the index of the first occurrence of a specific number in the array. How do I do this in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4376,
"level": 1,
"question": "I have an array of numbers and I need to find the index of the first occurrence of a specific number in the array. How do I do this in Python?",
"split": "train"
} |
def maxApples(grid):
if not grid:
return 0
m = len(grid)
n = len(grid[0]) if m > 0 else 0
if m == 0 or n == 0:
return 0
# Initialize DP table
dp = [[0]*n for _ in range(m)]
# Base case: starting cell
dp[0][0] = 1 if grid[0][0] == 'A' else 0
# Fill the f... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an **m x n** 2D grid containing characters `grid`, where each character represents a piece of fruit. Every such character is either '`A`' (apple), '`B`' (banana), or '`O`' (orange). You need to collect fruits by going through the grid starting from the top-left corner to t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4377,
"level": 1,
"question": "You are given an **m x n** 2D grid containing characters `grid`, where each character represents a piece of fruit. Every such character is either '`A`' (apple), '`B`' (banana), or '`O`' (orange). You need to collect fruits by going through the grid sta... |
from collections import defaultdict
def firstUniqChar(s):
if not s:
return ' '
frequency = defaultdict(int)
for c in s:
frequency[c] += 1
for c in s:
if frequency[c] == 1:
return c
return ' ' | simplelr_Filter | [
{
"content": "Question:\nfrom collections import defaultdict\n\ndef firstUniqChar(s):\n frequency = defaultdict(int)\n for c in s:\n frequency[c] += 1\n for c in s:\n if frequency[c] == 1:\n return c\n return \" \"\n\ns = \"leetcode\"\nprint firstUniqChar(s)\n\n# What if the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4378,
"level": 1,
"question": "from collections import defaultdict\n\ndef firstUniqChar(s):\n frequency = defaultdict(int)\n for c in s:\n frequency[c] += 1\n for c in s:\n if frequency[c] == 1:\n return c\n return \" \"\n\ns = \"leetcode\"\nprin... |
def find_longest_consecutive_subsequence(nums: list[int]) -> int:
if not nums:
return 0
nums_set = set(nums)
max_length = 0
for num in nums_set:
if (num - 1) not in nums_set:
current_length = 1
current_num = num
while (current_num + 1) in nums_set:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Longest Consecutive Subsequence\n\nGiven an unsorted list of integers, you are tasked with finding the length of the longest consecutive subsequence (LCS). A subsequence is defined as a set of integers from the list such that if `x` is in the set, `x+1` is also in the set (and so on... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4379,
"level": 1,
"question": "### Longest Consecutive Subsequence\n\nGiven an unsorted list of integers, you are tasked with finding the length of the longest consecutive subsequence (LCS). A subsequence is defined as a set of integers from the list such that if `x` is in the set, ... |
import re
# Function to extract emails from a text file
def extract_emails(file_name):
try:
with open(file_name, 'r') as file:
text = file.read()
# Regular expression pattern for email addresses
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,6}\b'
... | simplelr_Filter | [
{
"content": "Question:\nCan you help me understand how to process a text file using Python to extract specific information, such as email addresses?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4380,
"level": 1,
"question": "Can you help me understand how to process a text file using Python to extract specific information, such as email addresses?",
"split": "train"
} |
def count_occurrences(arr, x):
if not arr:
return 0
# Find first occurrence
low, high = 0, len(arr) - 1
first_occ = -1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
first_occ = mid
high = mid - 1 # Look for earlier occurrence
e... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a sorted array `arr` of `n` integers and a target integer `x`, write a function that finds the number of occurrences of `x` in the array. If `x` is not present in the array, return `0`. Make sure that your solution runs in O(log n) time.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4381,
"level": 1,
"question": "Given a sorted array `arr` of `n` integers and a target integer `x`, write a function that finds the number of occurrences of `x` in the array. If `x` is not present in the array, return `0`. Make sure that your solution runs in O(log n) time.",
"spl... |
def second_largest_unique(arr):
seen = set()
first_max = second_max = -float('inf')
for num in arr:
if num not in seen:
seen.add(num)
if num > first_max:
second_max = first_max
first_max = num
elif num > second_max:
... | simplelr_Filter | [
{
"content": "Question:\nWrite a function which takes an array of integers and returns the second largest unique element in the array. If the array has less than 2 unique elements, the function should return None. The size of the input array can be up to 10^5, and each value in the array can range from -10^5 to... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4382,
"level": 1,
"question": "Write a function which takes an array of integers and returns the second largest unique element in the array. If the array has less than 2 unique elements, the function should return None. The size of the input array can be up to 10^5, and each value i... |
def enhanced_insertion_sort(arr: list) -> tuple:
"""
Sorts the list using the Insertion Sort algorithm and returns a tuple containing the
sorted list and the number of iterations.
:param arr: List of integers to sort
:return: A tuple - (sorted_list, iteration_count)
"""
iteration_count ... | simplelr_Data_Structure | [
{
"content": "Question:\nYou have been given the task of writing a sorting function using the Insertion Sort algorithm. This function will not only sort the given list but will also return the number of iterations required to completely sort the list. Additionally, the function should handle various edge cases ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4383,
"level": 1,
"question": "You have been given the task of writing a sorting function using the Insertion Sort algorithm. This function will not only sort the given list but will also return the number of iterations required to completely sort the list. Additionally, the functio... |
def longest_arithmetic_subarray(nums):
n = len(nums)
if n <= 1:
return n
max_length = 1
dp = [{} for _ in range(n)]
for i in range(1, n):
d = nums[i] - nums[i-1]
if d in dp[i-1]:
dp[i][d] = dp[i-1][d] + 1
else:
dp[i][d] = 2
if dp[i][d] ... | simplelr_Leetcode | [
{
"content": "Question:\nA sequence of integers is called an **Arithmetic Array** if the difference between consecutive elements is the same. Given an integer array `nums` of length `n`, return the length of the longest arithmetic subarray. An arithmetic subarray is a contiguous subarray of `nums` that forms an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4384,
"level": 1,
"question": "A sequence of integers is called an **Arithmetic Array** if the difference between consecutive elements is the same. Given an integer array `nums` of length `n`, return the length of the longest arithmetic subarray. An arithmetic subarray is a contiguo... |
def robot_origin(S):
x = 0
y = 0
for char in S:
if char == 'U':
y += 1
elif char == 'D':
y -= 1
elif char == 'L':
x -= 1
elif char == 'R':
x += 1
return "YES" if x == 0 and y == 0 else "NO"
| simplelr_Taco | [
{
"content": "Question:\nProblem\n\nYou are given a robot that starts at the origin point (0, 0) in a 2D grid. The robot can move in one of four directions: up, down, left, or right. It is given a set of instructions in the form of the string `S`, where each character in the string represents a movement directi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4385,
"level": 1,
"question": "Problem\n\nYou are given a robot that starts at the origin point (0, 0) in a 2D grid. The robot can move in one of four directions: up, down, left, or right. It is given a set of instructions in the form of the string `S`, where each character in the s... |
from typing import List
def dailyTemperatures(temperatures: List[int]) -> List[int]:
stack = []
result = [0] * len(temperatures)
for i in range(len(temperatures)):
while stack and temperatures[i] > temperatures[stack[-1]]:
idx = stack.pop()
result[idx] = i - idx
stac... | simplelr_Taco | [
{
"content": "Question:\nYou are given an array `temperatures` representing the average daily temperatures for a given period. You need to implement a function that will, for each day, find how many days you would have to wait until a warmer temperature. If there is no future day that is warmer, return 0 for th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4386,
"level": 1,
"question": "You are given an array `temperatures` representing the average daily temperatures for a given period. You need to implement a function that will, for each day, find how many days you would have to wait until a warmer temperature. If there is no future ... |
import json
def serialize_books_to_json(books, filename):
with open(filename, 'w') as f:
json.dump(books, f) | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that can serialize a list of dictionaries to a JSON file. Each dictionary in the list represents a book with keys like 'title', 'author', 'year', and 'isbn'. The function should take the list of dictionaries and a filename as arguments.\nAnswer:\nLet's think s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4387,
"level": 1,
"question": "Write a function in Python that can serialize a list of dictionaries to a JSON file. Each dictionary in the list represents a book with keys like 'title', 'author', 'year', and 'isbn'. The function should take the list of dictionaries and a filename as... |
def find_highest_value(lst):
if not lst:
return None
current_max = lst[0]
for num in lst[1:]:
if num > current_max:
current_max = num
return current_max | simplelr_Filter | [
{
"content": "Question:\nComplete the following snippet with proper code that will return the highest value in a given list. However, you are not allowed to use any built-in functions or methods that directly sort or find the maximum value in the list. You must implement your own logic to find the highest value... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4388,
"level": 1,
"question": "Complete the following snippet with proper code that will return the highest value in a given list. However, you are not allowed to use any built-in functions or methods that directly sort or find the maximum value in the list. You must implement your ... |
def max_profit_with_two_transactions(prices):
if len(prices) < 2:
return 0
buy1 = buy2 = -float('inf')
sell1 = sell2 = 0
for price in prices:
buy1 = max(buy1, -price)
sell1 = max(sell1, buy1 + price)
buy2 = max(buy2, sell1 - price)
sell2 = max(sell2, buy2 + price)... | simplelr_Evol | [
{
"content": "Question:\nDevelop a Python function that simulates a simplified stock trading system. The function should take an array of stock prices (representing the price of a single stock over consecutive days) and determine the maximum profit that could be achieved by making at most two transactions (a bu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4389,
"level": 1,
"question": "Develop a Python function that simulates a simplified stock trading system. The function should take an array of stock prices (representing the price of a single stock over consecutive days) and determine the maximum profit that could be achieved by ma... |
def word_exists(word, dictionary):
return word in dictionary | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to determine whether a specific word exists in the dictionary of words. If the word exists in the dictionary, return true. If not, return false.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4390,
"level": 1,
"question": "Write a python function to determine whether a specific word exists in the dictionary of words. If the word exists in the dictionary, return true. If not, return false.",
"split": "train"
} |
def next_bigger_number(num: int) -> int:
digits = list(map(int, str(num)))
n = len(digits)
i = n - 2 # Start from the second last digit
# Find the pivot
while i >= 0 and digits[i] >= digits[i + 1]:
i -= 1
if i == -1:
return -1 # No bigger permutation possible
# Find the ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Coding Task: Next Lexicographical Permutation\n\n---\n\n#### Problem Statement\nWrite a Python function `next_bigger_number(num: int) -> int` that takes a positive integer `num` and returns the next higher number formed with the same set of digits. If no bigger permutation is possib... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4391,
"level": 1,
"question": "### Coding Task: Next Lexicographical Permutation\n\n---\n\n#### Problem Statement\nWrite a Python function `next_bigger_number(num: int) -> int` that takes a positive integer `num` and returns the next higher number formed with the same set of digits.... |
def group_by_first_element(tuple_list):
result = {}
for tpl in tuple_list:
key = tpl[0]
value = tpl[1]
if key in result:
result[key].append(value)
else:
result[key] = [value]
return result | simplelr_Filter | [
{
"content": "Question:\nGiven a list of tuples, where each tuple contains two strings, implement a function `group_by_first_element` that groups the tuples by their first elements and returns a dictionary where the keys are the unique first elements from the tuples and the values are lists of the corresponding... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4392,
"level": 1,
"question": "Given a list of tuples, where each tuple contains two strings, implement a function `group_by_first_element` that groups the tuples by their first elements and returns a dictionary where the keys are the unique first elements from the tuples and the va... |
from typing import List, Tuple
def find_parents(device_id: str, relations: List[Tuple[str, str]]) -> List[str]:
parent_map = {}
for parent, child in relations:
parent_map[child] = parent
current = device_id
parents = []
while current in parent_map:
current_parent = parent_... | simplelr_Apps | [
{
"content": "Question:\n**Task:** Software Development\n\nIn a fictional universe, a company called \"MicroTech\" has developed a new type of network protocol for its devices. One of the core functionalities of this protocol is to maintain a hierarchical system of devices where each device has a unique identif... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4393,
"level": 1,
"question": "**Task:** Software Development\n\nIn a fictional universe, a company called \"MicroTech\" has developed a new type of network protocol for its devices. One of the core functionalities of this protocol is to maintain a hierarchical system of devices whe... |
import base64
def encode_base64(input_value):
if not isinstance(input_value, str):
raise ValueError("Input must be a string")
input_bytes = input_value.encode('utf-8')
b64_bytes = base64.b64encode(input_bytes)
return b64_bytes.decode('utf-8') | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string and encodes it using Base64. The function should return the encoded string. If the input is not a string, the function should raise a ValueError with the message \"Input must be a string\".\nAnswer:\nLet's think step by step.\n",
"role": "... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4394,
"level": 1,
"question": "Write a Python function that takes a string and encodes it using Base64. The function should return the encoded string. If the input is not a string, the function should raise a ValueError with the message \"Input must be a string\".",
"split": "trai... |
def count_ways(n: int) -> int:
if n == 0:
return 1
elif n == 1:
return 1
elif n == 2:
return 2
a, b, c = 1, 1, 2 # a = ways(0), b = ways(1), c = ways(2)
for _ in range(3, n + 1):
d = a + b + c
a, b, c = b, c, d
return c | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are assigned the task of counting the number of ways to climb a staircase of `n` steps, where you can climb either 1, 2, or 3 steps at a time.\n\nWrite a function `count_ways(n: int) -> int` that calculates and returns the total number of distinct ways to re... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4395,
"level": 1,
"question": "### Problem Statement\n\nYou are assigned the task of counting the number of ways to climb a staircase of `n` steps, where you can climb either 1, 2, or 3 steps at a time.\n\nWrite a function `count_ways(n: int) -> int` that calculates and returns the ... |
def reverse_and_remove_special_characters(s):
filtered = []
for char in s:
if char.isalnum():
filtered.append(char)
cleaned = ''.join(filtered)
return cleaned[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string input and returns the string in reverse order with all special characters removed.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4396,
"level": 1,
"question": "Create a function that takes a string input and returns the string in reverse order with all special characters removed.",
"split": "train"
} |
import math
def find_primes_up_to(n):
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0], sieve[1] = False, False
for p in range(2, int(math.sqrt(n)) + 1):
if sieve[p]:
for multiple in range(p * p, n + 1, p):
sieve[multiple] = False
primes = [i for i, ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find all the prime numbers up to a given number n. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4397,
"level": 1,
"question": "Write a python function to find all the prime numbers up to a given number n. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.",
"split": "train"
} |
def num_decodings(s):
if not s:
return 0
if not s.isdigit():
return 0
if s[0] == '0':
return 0
n = len(s)
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 case
if s[i-1] !... | simplelr_Evol | [
{
"content": "Question:\nYou are given a string that represents an encoded message. The encoding rule is peculiar: each letter from 'a' to 'z' is encoded to a number from '1' to '26' respectively. Given the encoded message, write a function to calculate the total number of ways to decode it. Consider the mappin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4398,
"level": 1,
"question": "You are given a string that represents an encoded message. The encoding rule is peculiar: each letter from 'a' to 'z' is encoded to a number from '1' to '26' respectively. Given the encoded message, write a function to calculate the total number of way... |
def total_trip_distance(cities, distances):
return sum(distances)
| simplelr_Taco | [
{
"content": "Question:\nAlex is planning to take a road trip and wants to determine the total distance he will travel. He has a list of cities he plans to visit in order, and the distances between consecutive cities. Alex knows the total distance between each pair of cities but needs a program to sum these dis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4399,
"level": 1,
"question": "Alex is planning to take a road trip and wants to determine the total distance he will travel. He has a list of cities he plans to visit in order, and the distances between consecutive cities. Alex knows the total distance between each pair of cities b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.