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 is_palindrome(word):
word_lower = word.lower()
return word_lower == word_lower[::-1] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that checks if a given word is a palindrome. A palindrome is a word that reads the same backward as forward. Your function should be case-insensitive, meaning \"Bob\" is considered a palindrome.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 400,
"level": 1,
"question": "Write a Python function that checks if a given word is a palindrome. A palindrome is a word that reads the same backward as forward. Your function should be case-insensitive, meaning \"Bob\" is considered a palindrome.",
"split": "train"
} |
def is_booking_compatible(existing_bookings: list, new_booking: tuple) -> bool:
"""
Checks if the new booking overlaps with any existing bookings.
:param existing_bookings: A list of tuples where each tuple contains two strings representing start and end times in the format 'HH:MM'.
:param new_book... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Booking System Overlapping Time Slots\n\nYou are developing a simple booking system for a meeting room. The system currently stores a list of existing bookings, each represented by a start and end time. Your task is to implement a function in Python that checks if a new bo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 401,
"level": 1,
"question": "### Question: Booking System Overlapping Time Slots\n\nYou are developing a simple booking system for a meeting room. The system currently stores a list of existing bookings, each represented by a start and end time. Your task is to implement a function... |
def merge(nums1: list[int], m: int, nums2: list[int], n: int) -> None:
i = m - 1
j = n - 1
k = m + n - 1
while i >= 0 and j >= 0:
if nums1[i] > nums2[j]:
nums1[k] = nums1[i]
i -= 1
else:
nums1[k] = nums2[j]
j -= 1
k -= 1
... | simplelr_Taco | [
{
"content": "Question:\nYou are given two integer arrays, nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. \n\nMerge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 402,
"level": 1,
"question": "You are given two integer arrays, nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. \n\nMerge nums1 and nums2 into a single array sorted in non-decreasing orde... |
def lis(lst):
if not lst:
return []
n = len(lst)
tails = []
indices = []
prev = [-1] * n
for i in range(n):
x = lst[i]
# Binary search to find the first index in tails >= x
low, high = 0, len(tails)
while low < high:
mid = (low + high) // 2
... | simplelr_Taco | [
{
"content": "Question:\n## Task\n\nWrite a function to find the longest increasing subsequence (LIS) in a given list of integers.\n\nInput range:\n\n```python\n500 tests\n1 <= len(lst) <= 10,000\n-100,000 <= lst[i] <= 100,000\n```\n\n___\n\n## Description\n\nAn increasing subsequence is a sequence derived from... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 403,
"level": 1,
"question": "## Task\n\nWrite a function to find the longest increasing subsequence (LIS) in a given list of integers.\n\nInput range:\n\n```python\n500 tests\n1 <= len(lst) <= 10,000\n-100,000 <= lst[i] <= 100,000\n```\n\n___\n\n## Description\n\nAn increasing subs... |
def product_of_all_except_self(nums):
n = len(nums)
if n == 0:
return []
prefix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]
suffix = [1] * n
for i in range(n-2, -1, -1):
suffix[i] = suffix[i+1] * nums[i+1]
return [prefix[i] * suf... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns a list of the same length where each element at index `i` is the product of all elements in the original list except the one at `i`.\n\nFor example:\n```python\nproduct_of_all_except_self([1, 2, 3, 4]) == [24, 12, 8, 6]\nprod... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 404,
"level": 1,
"question": "Write a function that takes a list of integers and returns a list of the same length where each element at index `i` is the product of all elements in the original list except the one at `i`.\n\nFor example:\n```python\nproduct_of_all_except_self([1, 2,... |
def rotate_matrix(matrix):
# Check if the matrix is non-empty and square
if not matrix:
raise ValueError("The input must be a non-empty square matrix.")
n = len(matrix)
for row in matrix:
if len(row) != n:
raise ValueError("The input must be a non-empty square matrix.")
... | simplelr_Algorithm | [
{
"content": "Question:\n### Matrix Rotation Operation\n\n#### Context:\nYou are tasked with performing matrix manipulations frequently in a graphics application. One common operation is rotating a matrix 90 degrees clockwise.\n\n#### Requirements:\n1. **Function to Rotate Matrix**: Implement a function `rotate... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 405,
"level": 1,
"question": "### Matrix Rotation Operation\n\n#### Context:\nYou are tasked with performing matrix manipulations frequently in a graphics application. One common operation is rotating a matrix 90 degrees clockwise.\n\n#### Requirements:\n1. **Function to Rotate Matr... |
def longest_distinct_substring(s):
char_index = {}
max_len = 0
start = 0
left = 0
for right in range(len(s)):
char = s[right]
if char in char_index and char_index[char] >= left:
left = char_index[char] + 1
char_index[char] = right
current_len = right - lef... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a string as input and returns the longest substring with all distinct characters. Implement an efficient solution, prioritizing time complexity, and ensure your approach can handle large strings within a reasonable time frame. Use appropriate data structures ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 406,
"level": 1,
"question": "Write a function that takes a string as input and returns the longest substring with all distinct characters. Implement an efficient solution, prioritizing time complexity, and ensure your approach can handle large strings within a reasonable time frame... |
from heapq import heappop, heappush
from collections import defaultdict
def shortest_path(n, edges, source):
# Build the adjacency list
adj = defaultdict(list)
for u, v, w in edges:
adj[u].append((v, w))
# Initialize distances with infinity, set source distance to 0
INF = float('inf')
... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\nYou need to implement a simplified version of the Dijkstra's algorithm to find the shortest path in a weighted graph with positive integer weights.\n\n### Problem Statement:\nImplement a method `shortest_path` that computes the shortest paths from a source vertex to all ot... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 407,
"level": 1,
"question": "### Question\nYou need to implement a simplified version of the Dijkstra's algorithm to find the shortest path in a weighted graph with positive integer weights.\n\n### Problem Statement:\nImplement a method `shortest_path` that computes the shortest pa... |
def min_coins(coins, amount):
if amount == 0:
return 0
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for coin in coins:
if coin <= i:
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1 | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the minimum number of coins required to form a given amount. You can use any combination of given coin denominations.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 408,
"level": 1,
"question": "Write a function to find the minimum number of coins required to form a given amount. You can use any combination of given coin denominations.",
"split": "train"
} |
import torch
def complex_tensor_operations():
# Step 1: Create complex tensor A
A = torch.randn(3, 3, dtype=torch.cfloat)
print("Original Tensor A:")
print(A)
# Step 2: Transform to real representation
A_real_rep = A.real
A_real_rep = (A_real_rep, A.imag) # Combined as a tuple similar... | simplelr_Docs | [
{
"content": "Question:\n### Complex Number Operations and Linear Algebra in PyTorch\n\n**Objective**:\nDemonstrate your understanding of complex numbers in PyTorch by creating, manipulating, and performing operations on complex tensors. Apply linear algebra operations and verify the results.\n\n**Instructions*... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 409,
"level": 1,
"question": "### Complex Number Operations and Linear Algebra in PyTorch\n\n**Objective**:\nDemonstrate your understanding of complex numbers in PyTorch by creating, manipulating, and performing operations on complex tensors. Apply linear algebra operations and veri... |
def shortest_path_weighted_matrix(matrix):
if not matrix or not matrix[0]:
return 0 # Though per problem statement, matrix is at least 1x1.
n = len(matrix)
m = len(matrix[0])
# Create a DP table with the same dimensions as the matrix.
dp = [[0 for _ in range(m)] for _ in range(n)]... | simplelr_Algorithm | [
{
"content": "Question:\n### Objective\nCreate an efficient program to determine the shortest path in a weighted matrix.\n\n### Question\nWrite a Python function `shortest_path_weighted_matrix` that finds the shortest path in a grid where each cell has a non-negative weight. The function should find the minimum... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 410,
"level": 1,
"question": "### Objective\nCreate an efficient program to determine the shortest path in a weighted matrix.\n\n### Question\nWrite a Python function `shortest_path_weighted_matrix` that finds the shortest path in a grid where each cell has a non-negative weight. Th... |
def rob(nums):
if not nums:
return 0
n = len(nums)
if n == 1:
return nums[0]
prev_prev = nums[0]
prev = max(nums[0], nums[1])
for i in range(2, n):
current = max(nums[i] + prev_prev, prev)
prev_prev, prev = prev, current
return prev | simplelr_Apps | [
{
"content": "Question:\nGiven an array of non-negative integers representing the amount of money of each house, you are a professional robber planning to rob houses along a street. Each house is either available to be robbed or not due to some constraints (e.g., some houses might have alarms installed). Determ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 411,
"level": 1,
"question": "Given an array of non-negative integers representing the amount of money of each house, you are a professional robber planning to rob houses along a street. Each house is either available to be robbed or not due to some constraints (e.g., some houses mi... |
def fibonacci(n):
if n <= 0:
return []
fib = []
if n >= 1:
fib.append(0)
if n >= 2:
fib.append(1)
for i in range(2, n):
next_term = fib[i-1] + fib[i-2]
fib.append(next_term)
return fib
| simplelr_Taco | [
{
"content": "Question:\nComplete the function that accepts an integer n and returns a list containing the first n terms of the Fibonacci sequence. The Fibonacci sequence is defined as a series of numbers where the next term is the sum of the previous two terms. The sequence starts with 0 and 1.\n\n\n## Example... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 412,
"level": 1,
"question": "Complete the function that accepts an integer n and returns a list containing the first n terms of the Fibonacci sequence. The Fibonacci sequence is defined as a series of numbers where the next term is the sum of the previous two terms. The sequence st... |
def clean_sentence(sentence: str) -> str:
return ' '.join(sentence.split()) | simplelr_Codeforces | [
{
"content": "Question:\nYou have been hired as a software developer at a small startup that processes text data. One of your tasks is to develop a system that removes redundant spaces from sentences. Your system should adhere to the following rules:\n\n1. Remove any spaces at the beginning and end of the sente... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 413,
"level": 1,
"question": "You have been hired as a software developer at a small startup that processes text data. One of your tasks is to develop a system that removes redundant spaces from sentences. Your system should adhere to the following rules:\n\n1. Remove any spaces at ... |
def levenshtein_distance(s, t):
if len(s) == 0:
return len(t)
if len(t) == 0:
return len(s)
# Create a matrix with (len(s)+1) rows and (len(t)+1) columns
matrix = [[0 for _ in range(len(t)+1)] for _ in range(len(s)+1)]
# Fill the first row and column
for i in range(len(... | simplelr_Filter | [
{
"content": "Question:\nI want to create a Python script that calculates the Levenshtein distance between two strings. The Levenshtein distance is a measure of the difference between two strings, defined as the minimum number of single-character edits (insertions, deletions, or substitutions) required to chang... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 414,
"level": 1,
"question": "I want to create a Python script that calculates the Levenshtein distance between two strings. The Levenshtein distance is a measure of the difference between two strings, defined as the minimum number of single-character edits (insertions, deletions, o... |
def are_permutations(s1, s2):
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if two strings are permutations of each other. Two strings are considered permutations if they contain the same characters in a different order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 415,
"level": 1,
"question": "Write a function to check if two strings are permutations of each other. Two strings are considered permutations if they contain the same characters in a different order.",
"split": "train"
} |
from collections import Counter
def isPossibleDivide(nums, k):
if not nums:
return True
n = len(nums)
if n % k != 0:
return False
if k == 0:
return False # Handle edge case where k is zero, though problem likely ensures k>0
nums.sort()
freq = Counter(nums)
for x in ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums`, you need to determine whether the array can be divided into consecutive subsequences of length `k`. A **consecutive subsequence** is a sequence of `k` numbers where the difference between any two consecutive numbers is `1`. If it is possible to divide the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 416,
"level": 1,
"question": "Given an integer array `nums`, you need to determine whether the array can be divided into consecutive subsequences of length `k`. A **consecutive subsequence** is a sequence of `k` numbers where the difference between any two consecutive numbers is `1`... |
def even_or_odd(num):
if num % 2 == 0:
return 'Even'
else:
return 'Odd' | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that will check if a number is even or odd and return a string indicating the result.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 417,
"level": 1,
"question": "Create a function that will check if a number is even or odd and return a string indicating the result.",
"split": "train"
} |
def count_lowercase_letters(s):
letter_counts = {}
for c in s:
if 'a' <= c <= 'z':
letter_counts[c] = letter_counts.get(c, 0) + 1
return letter_counts | simplelr_Filter | [
{
"content": "Question:\nCreate a dictionary for counting the occurrence of each lowercase letter in the given string. However, exclude any whitespace characters and punctuation marks from being counted. Additionally, the solution should have a time complexity of O(n) and a space complexity of O(1), where n is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 418,
"level": 1,
"question": "Create a dictionary for counting the occurrence of each lowercase letter in the given string. However, exclude any whitespace characters and punctuation marks from being counted. Additionally, the solution should have a time complexity of O(n) and a spa... |
def LargestPrime(N):
if N < 2:
return -1
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) if is_p... | simplelr_Taco | [
{
"content": "Question:\nGiven an integer N, find the largest prime number less than or equal to N. If no prime number is found less than or equal to N, return -1.\n\nExample 1:\nInput: N = 10\nOutput: 7\nExplanation: The prime numbers less than or equal to 10 are 2, 3, 5, and 7. The largest is 7.\n\nExample 2:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 419,
"level": 1,
"question": "Given an integer N, find the largest prime number less than or equal to N. If no prime number is found less than or equal to N, return -1.\n\nExample 1:\nInput: N = 10\nOutput: 7\nExplanation: The prime numbers less than or equal to 10 are 2, 3, 5, and ... |
import math
def is_prime(n):
# If n is less than 2, it's not a prime number
if n < 2:
return False
# 2 and 3 are prime numbers
if n == 2 or n == 3:
return True
# If n is even and greater than 2, it's not prime
if n % 2 == 0:
return False
# Calculate th... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes an integer n and returns True if n is a prime number, and False otherwise. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, 11, and 13 are prime numbers. The function shou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 420,
"level": 1,
"question": "Write a Python function that takes an integer n and returns True if n is a prime number, and False otherwise. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, 11, and 13 ar... |
def split_list_by_threshold(numbers, threshold):
less_or_equal = [num for num in numbers if num <= threshold]
greater = [num for num in numbers if num > threshold]
return (less_or_equal, greater) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that splits a list of numbers into two lists based on a threshold value. All numbers less than or equal to the threshold should be in the first list, and all numbers greater than the threshold should be in the second list. The function should take a list of numbe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 421,
"level": 1,
"question": "Write a Python function that splits a list of numbers into two lists based on a threshold value. All numbers less than or equal to the threshold should be in the first list, and all numbers greater than the threshold should be in the second list. The fu... |
def linear_search(lst, target):
for index, value in enumerate(lst):
if value == target:
return index
return -1
# Example usage:
numbers = [3, 5, 8, 2]
print(linear_search(numbers, 8)) # Output: 2
print(linear_search(numbers, 10)) # Output: -1 | simplelr_Filter | [
{
"content": "Question:\nCan you explain how to perform a linear search algorithm in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 422,
"level": 1,
"question": "Can you explain how to perform a linear search algorithm in Python?",
"split": "train"
} |
def max_subarray_sum(nums):
if not nums:
return 0 # Return 0 if the array is empty
max_current = max_global = nums[0]
for num in nums[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return ma... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum sum of a contiguous subarray of a given array. This problem is known as the \"Maximum Subarray Problem\". Use Kadane's Algorithm to solve this problem.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 423,
"level": 1,
"question": "Write a python function to find the maximum sum of a contiguous subarray of a given array. This problem is known as the \"Maximum Subarray Problem\". Use Kadane's Algorithm to solve this problem.",
"split": "train"
} |
def is_list_empty(lst):
return not lst | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if a given list is empty or not. The function should return True if the list is empty, and False otherwise.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 424,
"level": 1,
"question": "Create a function that checks if a given list is empty or not. The function should return True if the list is empty, and False otherwise.",
"split": "train"
} |
def longest_nonzero_subarray(arr):
max_length = 0
current_length = 0
for num in arr:
if num != 0:
current_length += 1
if current_length > max_length:
max_length = current_length
else:
current_length = 0
return max_length
# Test Cases... | simplelr_Evol | [
{
"content": "Question:\nGiven a list of integers, write a Python function to find the length of the longest contiguous subarray of non-zero integers. The function should take a list as an input and return the length of the longest contiguous subarray. Include test cases to validate your solution.\n\n```python\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 425,
"level": 1,
"question": "Given a list of integers, write a Python function to find the length of the longest contiguous subarray of non-zero integers. The function should take a list as an input and return the length of the longest contiguous subarray. Include test cases to val... |
from typing import List
def selection_sort_with_trace(arr: List[int]) -> List[int]:
n = len(arr)
print(f'iteration 0 : ', end='')
print(' '.join(map(str, arr)))
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j... | simplelr_Data_Structure | [
{
"content": "Question:\n### Selection Sort with Trace\n\n**Scenario**: \nYou're a software developer at a small startup. The team regularly needs to quickly sort small datasets and observe the sorting process for debugging and educational purposes. The current implementation of the selection sort algorithm wor... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 426,
"level": 1,
"question": "### Selection Sort with Trace\n\n**Scenario**: \nYou're a software developer at a small startup. The team regularly needs to quickly sort small datasets and observe the sorting process for debugging and educational purposes. The current implementation o... |
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to return the nth Fibonacci number using recursion. The nth Fibonacci number is defined as the sum of the two preceding ones, usually starting with 0 and 1. For example, the sequence starts like this: 0, 1, 1, 2, 3, 5, 8, 13, ...\nAnswer:\nLet's think step by ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 427,
"level": 1,
"question": "Write a python function to return the nth Fibonacci number using recursion. The nth Fibonacci number is defined as the sum of the two preceding ones, usually starting with 0 and 1. For example, the sequence starts like this: 0, 1, 1, 2, 3, 5, 8, 13, ...... |
def calculate_rectangle_properties(length, width):
"""
Calculate the area and perimeter of a rectangle.
Args:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Returns:
tuple: A tuple containing the area and perimeter of the rectang... | simplelr_Filter | [
{
"content": "Question:\n### Directions for Task 2\n\nThank you for your patience as we learn more about your thought process. In this task, we will apply the concepts we've discussed to a scenario. \n\nYour task is to analyze a given problem and write a code solution in Python. \n\nThe problem is as follows: \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 428,
"level": 1,
"question": "### Directions for Task 2\n\nThank you for your patience as we learn more about your thought process. In this task, we will apply the concepts we've discussed to a scenario. \n\nYour task is to analyze a given problem and write a code solution in Python... |
def reverse_words(sentence: str) -> str:
return ' '.join(sentence.split()[::-1]) | simplelr_Data_Structure | [
{
"content": "Question:\n### Reverse Words in a String\n#### Problem Statement\nYou are given a string representing a sentence (words separated by spaces). You need to reverse the order of the words while maintaining the order of the characters within individual words. For example:\n\nInput:\n```\n\"the sky is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 429,
"level": 1,
"question": "### Reverse Words in a String\n#### Problem Statement\nYou are given a string representing a sentence (words separated by spaces). You need to reverse the order of the words while maintaining the order of the characters within individual words. For exam... |
def max_in_list(numbers):
"""
Extracts the maximum integer from a list of integers.
Args:
numbers: A list or tuple containing integers.
Returns:
The maximum integer in the list, or None if the list is empty, contains non-integer elements, or is not a list/tuple.
"""
if not isin... | simplelr_Filter | [
{
"content": "Question:\nPlease write a code within a Python function that extracts the maximum number from a list of integers. How would you ensure the code is robust and maintainable?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 430,
"level": 1,
"question": "Please write a code within a Python function that extracts the maximum number from a list of integers. How would you ensure the code is robust and maintainable?",
"split": "train"
} |
def longestCommonPrefix(strs):
if not strs:
return ""
shortest = min(strs, key=lambda x: len(x))
for i, char in enumerate(shortest):
for s in strs:
if s[i] != char:
return shortest[:i]
return shortest | simplelr_Apps | [
{
"content": "Question:\nImplement a function `longestCommonPrefix` which accepts an array of strings and returns the longest common prefix string among them. If there is no common prefix, return an empty string `\"\"`.\n\n### Notes\n\n- All given inputs are in lowercase.\n- If the input array is empty, return ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 431,
"level": 1,
"question": "Implement a function `longestCommonPrefix` which accepts an array of strings and returns the longest common prefix string among them. If there is no common prefix, return an empty string `\"\"`.\n\n### Notes\n\n- All given inputs are in lowercase.\n- If... |
def decompress_string(s: str) -> str:
stack = []
current_str = ""
current_num = 0
for char in s:
if char.isdigit():
current_num = current_num * 10 + int(char)
elif char == '[':
stack.append((current_str, current_num))
current_str = ""
curre... | simplelr_Taco | [
{
"content": "Question:\nYou are asked to build a function that decompresses a string according to the following rules:\n\n1. The string will contain characters, digits, square brackets ('[' and ']') and nested brackets.\n2. The characters between the brackets need to be repeated as many times as the digits bef... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 432,
"level": 1,
"question": "You are asked to build a function that decompresses a string according to the following rules:\n\n1. The string will contain characters, digits, square brackets ('[' and ']') and nested brackets.\n2. The characters between the brackets need to be repeat... |
def search(nums, target):
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
if nums[low] <= nums[mid]:
# The left half is sorted
if nums[low] <= target <= nums[mid]:
high = mid - ... | simplelr_Leetcode | [
{
"content": "Question:\nA **sorted rotated array** is an array that is initially sorted in ascending order and is then rotated at some pivot point unknown to you beforehand. For example, the array `[0,1,2,4,5,6,7]` might be rotated to become `[4,5,6,7,0,1,2]`. Given a **sorted rotated array** `nums` of **uniqu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 433,
"level": 1,
"question": "A **sorted rotated array** is an array that is initially sorted in ascending order and is then rotated at some pivot point unknown to you beforehand. For example, the array `[0,1,2,4,5,6,7]` might be rotated to become `[4,5,6,7,0,1,2]`. Given a **sorted... |
def int_to_hex(n):
return format(n, 'x') | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to solve the following problem: Given an integer n, convert it to a hexadecimal number (base 16).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 434,
"level": 1,
"question": "Write a python function to solve the following problem: Given an integer n, convert it to a hexadecimal number (base 16).",
"split": "train"
} |
def consecutive_character_count(s: str) -> list:
if not s:
return []
result = []
current_char = s[0]
count = 1
for i in range(1, len(s)):
if s[i] == current_char:
count += 1
else:
result.append(count)
current_char = s[i]
count =... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are required to write a function that receives a string of lowercase alphabetic characters and returns a list where each element represents a count of its consecutive occurrences in the given string. This task tests your ability to handle string traversal an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 435,
"level": 1,
"question": "### Problem Statement\n\nYou are required to write a function that receives a string of lowercase alphabetic characters and returns a list where each element represents a count of its consecutive occurrences in the given string. This task tests your abi... |
from typing import List
def optimized_binary_search(array: List[int], value: int) -> int:
if not array:
return -1
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == value:
return mid
elif array[mid] > value:
... | simplelr_Data_Structure | [
{
"content": "Question:\nOptimized Binary Search Function\n\n#### Context\nYou are provided with a sorted array of integers. You need to implement a binary search algorithm to find the position of a given target value within the array. Your task is to write an efficient function that can handle both large datas... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 436,
"level": 1,
"question": "Optimized Binary Search Function\n\n#### Context\nYou are provided with a sorted array of integers. You need to implement a binary search algorithm to find the position of a given target value within the array. Your task is to write an efficient functio... |
def max_water_area(heights: list[int]) -> int:
max_area = 0
left = 0
right = len(heights) - 1
while left < right:
width = right - left
height = min(heights[left], heights[right])
current_area = width * height
if current_area > max_area:
max_area = current_area... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nGiven a list of integers representing the heights of a series of buildings, write a function to determine the maximum area of a rectangle formed by any two buildings and the water trapped between them. The heights of the buildings are given in a list, where the wi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 437,
"level": 1,
"question": "### Problem Statement\nGiven a list of integers representing the heights of a series of buildings, write a function to determine the maximum area of a rectangle formed by any two buildings and the water trapped between them. The heights of the buildings... |
def count_characters(s):
return len(s) | simplelr_Filter | [
{
"content": "Question:\nWrite a simple Python function that takes a string as input and returns the count of characters in the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 438,
"level": 1,
"question": "Write a simple Python function that takes a string as input and returns the count of characters in the string.",
"split": "train"
} |
def kilometers_to_miles(kilometers):
"""
Converts a distance in kilometers to miles.
Args:
kilometers (float): The distance in kilometers.
Returns:
float: The distance converted to miles.
"""
conversion_factor = 0.621371
return kilometers * conversion_factor
# Exam... | simplelr_Filter | [
{
"content": "Question:\nCould you code in python language a function transforming a distance in kilometers into mile units, thus converting the single provided value accordingly?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 439,
"level": 1,
"question": "Could you code in python language a function transforming a distance in kilometers into mile units, thus converting the single provided value accordingly?",
"split": "train"
} |
def running_sum(nums):
current_sum = 0
result = []
for num in nums:
current_sum += num
result.append(current_sum)
return result | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `nums`. A **running sum** of `nums` is an array `runningSum` where `runningSum[i]` is the sum of the elements from `nums[0]` to `nums[i]`. Implement a function that calculates the **running sum** of the array. Return _the **running sum** of th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 440,
"level": 1,
"question": "You are given a **0-indexed** integer array `nums`. A **running sum** of `nums` is an array `runningSum` where `runningSum[i]` is the sum of the elements from `nums[0]` to `nums[i]`. Implement a function that calculates the **running sum** of the array.... |
def find_max_value(numbers):
if not numbers:
return None
current_max = numbers[0]
for number in numbers[1:]:
if number > current_max:
current_max = number
return current_max | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes in a list of integers as input and returns the maximum value. Additionally, the function should be able to handle cases where the input list may contain negative numbers and decimal numbers. However, you are not allowed to use any built-in functions or... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 441,
"level": 1,
"question": "Write a Python function that takes in a list of integers as input and returns the maximum value. Additionally, the function should be able to handle cases where the input list may contain negative numbers and decimal numbers. However, you are not allowe... |
def can_become_goal(s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
if len(s) == 0:
return True
return goal in s + s | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings `s` and `goal`, both of which contain only lowercase English letters. Your task is to determine if you can obtain string `goal` by rotating the string `s` any number of times. Return `true` if you can obtain `goal` by rotating `s`, otherwise return `false`. Not... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 442,
"level": 1,
"question": "You are given two strings `s` and `goal`, both of which contain only lowercase English letters. Your task is to determine if you can obtain string `goal` by rotating the string `s` any number of times. Return `true` if you can obtain `goal` by rotating ... |
def min_subarray_len(arr, target):
min_len = float('inf')
current_sum = 0
left = 0
n = len(arr)
for right in range(n):
current_sum += arr[right]
while current_sum >= target and left <= right:
window_len = right - left + 1
if window_len < min_len:
... | simplelr_Apps | [
{
"content": "Question:\n# Task\nWrite a function that takes an array of integers and a target sum, and returns the smallest length of a contiguous subarray whose sum is greater than or equal to the target sum. If there isn't one, return 0 instead.\n\n# Example\n\nFor `arr = [2, 3, 1, 2, 4, 3]` and `target = 7`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 443,
"level": 1,
"question": "# Task\nWrite a function that takes an array of integers and a target sum, and returns the smallest length of a contiguous subarray whose sum is greater than or equal to the target sum. If there isn't one, return 0 instead.\n\n# Example\n\nFor `arr = [2... |
def sgd_classifier(train_file: str, test_file: str):
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import classification_report
from sklearn.impute import SimpleImputer
# Step 1: Data Preprocessing
# ... | simplelr_Docs | [
{
"content": "Question:\n### **Coding Assessment Question**\n\nYou are given a dataset `train.csv` which contains a large number of features and samples. Your task is to implement a classification model using the `SGDClassifier` from scikit-learn to predict whether a sample belongs to class 0 or class 1. The pe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 444,
"level": 1,
"question": "### **Coding Assessment Question**\n\nYou are given a dataset `train.csv` which contains a large number of features and samples. Your task is to implement a classification model using the `SGDClassifier` from scikit-learn to predict whether a sample bel... |
def reverse_string_count(s):
return (s[::-1], len(s)) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as an argument and returns the string reversed along with the character count of the reversed string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 445,
"level": 1,
"question": "Create a function that takes a string as an argument and returns the string reversed along with the character count of the reversed string.",
"split": "train"
} |
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that generates the nth Fibonacci number. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the first several numbers in the Fibonacci sequence are 0, 1, 1, 2, 3, 5, 8, 13... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 446,
"level": 1,
"question": "Create a function that generates the nth Fibonacci number. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the first several numbers in the Fibonacci se... |
def longest_unique_substr(s: str) -> int:
last_occurrence = {}
start = 0
max_length = 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... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\nYou are provided with a string manipulation problem that focuses on finding the longest substring without repeating characters. Your task is to design an efficient function to identify the longest such substring in a given input string.\n\n**Core Concepts**:\nA substring... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 447,
"level": 1,
"question": "### Question\n\nYou are provided with a string manipulation problem that focuses on finding the longest substring without repeating characters. Your task is to design an efficient function to identify the longest such substring in a given input string.\... |
def sum_of_digits(n):
sum_digits = 0
while n > 0:
sum_digits += n % 10
n = n // 10
return sum_digits
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `sum_of_digits` that takes a non-negative integer `n` and returns the sum of its digits. The function should work without converting the integer to a string or using any form of explicit casting between types.\n\n### Constraints\n\n- You should not use string conversion... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 448,
"level": 1,
"question": "Write a function `sum_of_digits` that takes a non-negative integer `n` and returns the sum of its digits. The function should work without converting the integer to a string or using any form of explicit casting between types.\n\n### Constraints\n\n- Yo... |
def is_match(s: str, p: str) -> bool:
n = len(s)
m = len(p)
dp = [[False] * (m + 1) for _ in range(n + 1)]
dp[0][0] = True
for i in range(n + 1):
for j in range(m + 1):
if i == 0 and j == 0:
continue # Already initialized
if j == 0:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Regular Expression Matching\n \nIn this problem, you need to implement a function that checks if an input string matches a given pattern using regular expressions with support for the special characters '.' and '*'. The function should return `True` if the entire string matches the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 449,
"level": 1,
"question": "### Regular Expression Matching\n \nIn this problem, you need to implement a function that checks if an input string matches a given pattern using regular expressions with support for the special characters '.' and '*'. The function should return `True... |
def product_of_array(arr):
if not arr:
return 1
product = 1
for num in arr:
product *= num
return product | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in an array and returns the product of all numbers in the array. If the array is empty, return 1 (since the product of no numbers should be considered as 1).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 450,
"level": 1,
"question": "Create a function that takes in an array and returns the product of all numbers in the array. If the array is empty, return 1 (since the product of no numbers should be considered as 1).",
"split": "train"
} |
def has_subarray_with_multiple_sum(arr, k):
n = len(arr)
if k == 0:
seen = set()
current_sum = 0
seen.add(current_sum)
for num in arr:
current_sum += num
if current_sum in seen:
return True
seen.add(current_sum)
return F... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find if there is a subarray with a sum that is a multiple of a given number k.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 451,
"level": 1,
"question": "Write a python function to find if there is a subarray with a sum that is a multiple of a given number k.",
"split": "train"
} |
from typing import List
from collections import Counter
def find_modes(arr: List[int]) -> List[int]:
"""
Given an array of integers, find and return all the mode(s)
in the array as a list. If there are multiple modes,
return them all in any order.
:param arr: List of integers
:return: List of ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are given a dataset of survey responses, and you need to identify the most frequently selected options to analyze the popular choices among the respondents. Your task is to implement a function that identifies the mode(s) of the given dataset.\n\n### Function Signature... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 452,
"level": 1,
"question": "### Scenario\nYou are given a dataset of survey responses, and you need to identify the most frequently selected options to analyze the popular choices among the respondents. Your task is to implement a function that identifies the mode(s) of the given ... |
def remove_duplicates(input_list):
seen = set()
result = []
for item in input_list:
if item not in seen:
seen.add(item)
result.append(item)
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to remove duplicates from a list in Python, but ensure that the order of elements is preserved. You should also handle cases where the input list is empty or contains only one element. How can this be efficiently implemented?\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 453,
"level": 1,
"question": "Write a function to remove duplicates from a list in Python, but ensure that the order of elements is preserved. You should also handle cases where the input list is empty or contains only one element. How can this be efficiently implemented?",
"split... |
from PIL import Image
def get_image_dimensions(image_path):
img = Image.open(image_path)
return img.size
# Example usage:
# image_path = "path_to_your_image.jpg"
# dimensions = get_image_dimensions(image_path)
# print(dimensions) # Outputs: (width, height) | simplelr_Filter | [
{
"content": "Question:\nHello Qwen, how can I generate a Python function that takes an image path as input and returns the dimensions (width, height) of the image?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 454,
"level": 1,
"question": "Hello Qwen, how can I generate a Python function that takes an image path as input and returns the dimensions (width, height) of the image?",
"split": "train"
} |
import re
def is_valid_email(email: str) -> bool:
"""
Validate if the given string is a valid email address.
Parameters:
email (str): A string representing an email address.
Returns:
bool: True if the email is valid according to the described rules, False otherwise.
Raises:
TypeE... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\nYou are required to implement a function that checks if a given string represents a valid email address based on the following criteria:\n - The email address must contain exactly one \"@\" symbol.\n - The local part, which precedes the \"@\", must be... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 455,
"level": 1,
"question": "### Coding Assessment Question\n\nYou are required to implement a function that checks if a given string represents a valid email address based on the following criteria:\n - The email address must contain exactly one \"@\" symbol.\n - The local part,... |
def partition_array(arr, k):
# Check if any element exceeds k
for num in arr:
if num > k:
return -1
# If all elements are <= k, return the array as a single subarray
return [arr] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to partition an array into sub-arrays such that the maximum element in each subarray is less than or equal to `k`. If return `-1` if it's not possible to partition the array in such a way.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 456,
"level": 1,
"question": "Write a python function to partition an array into sub-arrays such that the maximum element in each subarray is less than or equal to `k`. If return `-1` if it's not possible to partition the array in such a way.",
"split": "train"
} |
def validate_stack_sequences(push_arr, pop_arr):
stack = []
push_ptr = 0
pop_ptr = 0
n = len(push_arr)
m = len(pop_arr)
while push_ptr < n or pop_ptr < m:
if stack and stack[-1] == pop_arr[pop_ptr]:
stack.pop()
pop_ptr += 1
else:
if push_p... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two integer arrays `push_arr` and `pop_arr` with distinct values. `push_arr` represents the order in which integers are pushed onto a stack, and `pop_arr` represents the order in which the integers are popped from the stack. Return _true_ if `pop_arr` could represent a val... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 457,
"level": 1,
"question": "You are given two integer arrays `push_arr` and `pop_arr` with distinct values. `push_arr` represents the order in which integers are pushed onto a stack, and `pop_arr` represents the order in which the integers are popped from the stack. Return _true_ ... |
from collections import Counter
def can_form_symmetric_column(s: str) -> bool:
cnt = Counter(s)
odd_count = 0
for v in cnt.values():
if v % 2 != 0:
odd_count += 1
n = len(s)
if n % 2 == 0:
return odd_count == 0
else:
return odd_count == 1 | simplelr_Codeforces | [
{
"content": "Question:\nOlivia is an architect who likes building symmetrical structures. She has been given a special task to design a series of decorative columns made up of LEGO bricks. Each column is made by stacking LEGO bricks of various colors on top of each other. \n\nA column is considered symmetrical... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 458,
"level": 1,
"question": "Olivia is an architect who likes building symmetrical structures. She has been given a special task to design a series of decorative columns made up of LEGO bricks. Each column is made by stacking LEGO bricks of various colors on top of each other. \n\n... |
def merge_consecutive_duplicates(input_list):
if not input_list:
return []
result = [input_list[0]]
for element in input_list[1:]:
if element != result[-1]:
result.append(element)
return result | simplelr_Filter | [
{
"content": "Question:\nDevelop a function in Python to merge consecutive duplicates in a list into a single element and return a new list without those duplicates. However, the twist is to implement this function without using Python's in-built functions or libraries, to increase the complexity and understand... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 459,
"level": 1,
"question": "Develop a function in Python to merge consecutive duplicates in a list into a single element and return a new list without those duplicates. However, the twist is to implement this function without using Python's in-built functions or libraries, to incr... |
def even_count_even_numbers(lst):
return sum(1 for num in lst if num % 2 == 0) % 2 == 0 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list of integers and returns True if the list contains an even number of even numbers, otherwise False.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 460,
"level": 1,
"question": "Create a function that takes in a list of integers and returns True if the list contains an even number of even numbers, otherwise False.",
"split": "train"
} |
def transform_and_filter_vectors(vectors):
return [
[(x + 1, y * 2) for x, y in group if (x + 1) <= 10]
for group in vectors
] | simplelr_Filter | [
{
"content": "Question:\nHere is a set of vectors represented as a list of ordered pairs of real numbers: `[[(1, 1), (2, 2), (3, 3)], [(4, 4), (5, 5), (6, 6)]]`. Write a Python code snippet that takes such a list of vector sets as input, adds 1 to the first element of each vector and multiplies the second eleme... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 461,
"level": 1,
"question": "Here is a set of vectors represented as a list of ordered pairs of real numbers: `[[(1, 1), (2, 2), (3, 3)], [(4, 4), (5, 5), (6, 6)]]`. Write a Python code snippet that takes such a list of vector sets as input, adds 1 to the first element of each vect... |
def min_subarray_sum(nums, target):
min_length = float('inf')
result = []
for i in range(len(nums)):
current_sum = 0
for j in range(i, len(nums)):
current_sum += nums[j]
if current_sum >= target:
length = j - i + 1
if length < min_lengt... | simplelr_Evol | [
{
"content": "Question:\nDevelop a Python function that takes a list of integers and returns the shortest contiguous subarray whose sum is greater than or equal to a specified target value. If no such subarray exists, return an empty list. \n\nFor example:\n```python\ndef min_subarray_sum(nums, target):\n # ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 462,
"level": 1,
"question": "Develop a Python function that takes a list of integers and returns the shortest contiguous subarray whose sum is greater than or equal to a specified target value. If no such subarray exists, return an empty list. \n\nFor example:\n```python\ndef min_s... |
from typing import List
def max_subarray(array: List[int]) -> int:
if not array:
return 0 # According to problem statement, this case won't occur as len(array) >=1
current_max = array[0]
max_so_far = array[0]
for num in array[1:]:
current_max = max(num, current_max + num)... | simplelr_Data_Structure | [
{
"content": "Question:\n**Scenario**:\nYou are working on a financial analysis tool. One feature of this tool is to analyze the historical profit and loss data to find the period with the maximum gain. You need to implement a function that identifies this period using the given profit and loss records.\n\n**Pr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 463,
"level": 1,
"question": "**Scenario**:\nYou are working on a financial analysis tool. One feature of this tool is to analyze the historical profit and loss data to find the period with the maximum gain. You need to implement a function that identifies this period using the give... |
def is_valid_24_hour_time(time):
if len(time) != 5:
return "NO"
if time[2] != ':':
return "NO"
hh, mm = time.split(':')
if len(hh) != 2 or len(mm) != 2:
return "NO"
if not hh.isdigit() or not mm.isdigit():
return "NO"
hour = int(hh)
minute = int(mm)
if 0 <... | simplelr_Codeforces | [
{
"content": "Question:\nWrite a function that determines whether a given string is a valid 24-hour clock time. A valid time should be formatted as \"HH:MM\" where \"HH\" represents the hour (00-23) and \"MM\" represents the minute (00-59). Both the hour and minute must always be two digits.\n\nThe input is a s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 464,
"level": 1,
"question": "Write a function that determines whether a given string is a valid 24-hour clock time. A valid time should be formatted as \"HH:MM\" where \"HH\" represents the hour (00-23) and \"MM\" represents the minute (00-59). Both the hour and minute must always ... |
def find_subarray_with_target_sum(nums, target):
prefix_sums = {0: -1}
current_sum = 0
for j in range(len(nums)):
current_sum += nums[j]
if (current_sum - target) in prefix_sums:
return [prefix_sums[current_sum - target] + 1, j]
if current_sum not in prefix_sums:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers `nums` and an integer `target`. Your task is to find a continuous subarray within `nums` whose sum equals to `target`. If such a subarray exists, return the starting and ending indices of the subarray (0-indexed). If no such subarray exists, return `[-1,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 465,
"level": 1,
"question": "You are given a list of integers `nums` and an integer `target`. Your task is to find a continuous subarray within `nums` whose sum equals to `target`. If such a subarray exists, return the starting and ending indices of the subarray (0-indexed). If no ... |
def single_number(nums):
res = 0
for num in nums:
res ^= num
return res | simplelr_Leetcode | [
{
"content": "Question:\nWrite a function that takes a non-empty array of integers where each integer appears twice except for one that appears only once. Your task is to find and return the integer that appears only once. The algorithm should have a linear runtime complexity and use only constant extra space.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 466,
"level": 1,
"question": "Write a function that takes a non-empty array of integers where each integer appears twice except for one that appears only once. Your task is to find and return the integer that appears only once. The algorithm should have a linear runtime complexity a... |
def max_profit(prices):
profit = 0
for i in range(len(prices) - 1):
if prices[i+1] > prices[i]:
profit += prices[i+1] - prices[i]
return profit | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function that simulates a simplified stock trading strategy and determines the maximum possible profit. You are given a list of stock prices where the i-th element is the price of the stock on the i-th day. You can make as many transactions as you want, but you must sell a stock... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 467,
"level": 1,
"question": "Write a function that simulates a simplified stock trading strategy and determines the maximum possible profit. You are given a list of stock prices where the i-th element is the price of the stock on the i-th day. You can make as many transactions as y... |
from typing import List
def improved_insertion_sort(arr: List[int]) -> List[int]:
n = len(arr)
for i in range(1, n):
current = arr[i]
j = i - 1
swapped = False
# Insert current into the sorted part
while j >= 0 and arr[j] > current:
arr[j + 1] = arr[j]
... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are required to write a function called `improved_insertion_sort` that sorts a list of integers using the insertion sort algorithm. The algorithm provided should be optimized to detect whether the list becomes sorted during the sorting process and terminate early if no swaps are mad... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 468,
"level": 1,
"question": "You are required to write a function called `improved_insertion_sort` that sorts a list of integers using the insertion sort algorithm. The algorithm provided should be optimized to detect whether the list becomes sorted during the sorting process and t... |
def subarray_sum(nums, target):
prefix_map = {0: -1} # Map to store prefix sum and its earliest index
current_sum = 0
for i in range(len(nums)):
current_sum += nums[i]
if (current_sum - target) in prefix_map:
start = prefix_map[current_sum - target] + 1
end = i
... | simplelr_Leetcode | [
{
"content": "Question:\nYou have an array of integers `nums` and an integer `target`. Your task is to find out if there exists a contiguous subarray within `nums` whose sum is exactly `target`. If such a subarray exists, return _the starting and ending indices of one such subarray_. If there are multiple such ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 469,
"level": 1,
"question": "You have an array of integers `nums` and an integer `target`. Your task is to find out if there exists a contiguous subarray within `nums` whose sum is exactly `target`. If such a subarray exists, return _the starting and ending indices of one such suba... |
def max_abs_diff(nums):
return max(nums) - min(nums) | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums`, you need to find two distinct indices `i` and `j` in the array such that the absolute difference between `nums[i]` and `nums[j]` is maximized. Return the maximum absolute difference. You can assume that the array contains at least two elements and that... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 470,
"level": 1,
"question": "Given an array of integers `nums`, you need to find two distinct indices `i` and `j` in the array such that the absolute difference between `nums[i]` and `nums[j]` is maximized. Return the maximum absolute difference. You can assume that the array conta... |
def merge_and_sort_lists(list1, list2):
merged = list1 + list2
unique = set(merged)
unique_list = list(unique)
sorted_list = sorted(unique_list)
return sorted_list | simplelr_Package | [
{
"content": "Question:\nYou need to create a function named `merge_and_sort_lists` that merges two lists of integers and returns a single sorted list without duplicates. The function should ensure that duplicate elements present in the input lists appear only once in the resulting list. Implement the function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 471,
"level": 1,
"question": "You need to create a function named `merge_and_sort_lists` that merges two lists of integers and returns a single sorted list without duplicates. The function should ensure that duplicate elements present in the input lists appear only once in the resul... |
from typing import List, Callable
def transform_array(arr: List[int], func: Callable[[int], int]) -> List[int]:
return [func(x) for x in arr] | simplelr_Algorithm | [
{
"content": "Question:\n### Array Transformation with Function Application\n\n#### Background\nYou are given an array of integers. Your task is to apply a given mathematical function to each element of the array and return the transformed array.\n\n#### Task\nWrite a function `transform_array(arr: List[int], f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 472,
"level": 1,
"question": "### Array Transformation with Function Application\n\n#### Background\nYou are given an array of integers. Your task is to apply a given mathematical function to each element of the array and return the transformed array.\n\n#### Task\nWrite a function ... |
def isValid(s: str) -> bool:
stack = []
for char in s:
if char == '(':
stack.append(char)
else:
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a string containing only parentheses `(` and `)` and determines if the string is a valid parentheses sequence. A valid parentheses sequence is one where every opening parenthesis has a corresponding closing parenthesis and they are properly nested.\n\n```\nis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 473,
"level": 1,
"question": "Write a function that takes a string containing only parentheses `(` and `)` and determines if the string is a valid parentheses sequence. A valid parentheses sequence is one where every opening parenthesis has a corresponding closing parenthesis and th... |
def reorder_string(s: str) -> str:
digits = []
letters = []
specials = []
for c in s:
if c.isdigit():
digits.append(c)
elif c.isalpha():
letters.append(c)
else:
specials.append(c)
return ''.join(digits + letters + specials) | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario:\nYou are given a string containing a mix of alphabetic characters, digits, and special characters. Your task is to implement a function that returns a new string in which all the digits are moved to the front, followed by the alphabetic characters, and finally the special ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 474,
"level": 1,
"question": "### Scenario:\nYou are given a string containing a mix of alphabetic characters, digits, and special characters. Your task is to implement a function that returns a new string in which all the digits are moved to the front, followed by the alphabetic ch... |
def format_duration(seconds):
if seconds <= 0:
return "00:00:00"
h = seconds // 3600
remainder = seconds % 3600
m = remainder // 60
s = remainder % 60
return f"{h:02d}:{m:02d}:{s:02d}" | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes an integer representing a duration in seconds and returns the format as `hh:mm:ss` (a string). Ensure that the output follows these rules:\n\n1. If the duration is less than or equal to zero, return `\"00:00:00\"`.\n2. Always use two digits for hours, minutes... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 475,
"level": 1,
"question": "Write a function that takes an integer representing a duration in seconds and returns the format as `hh:mm:ss` (a string). Ensure that the output follows these rules:\n\n1. If the duration is less than or equal to zero, return `\"00:00:00\"`.\n2. Always... |
import re
def is_palindrome(word):
cleaned = re.sub(r'[^a-z0-9]', '', word.lower())
return cleaned == cleaned[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given word is a palindrome. A palindrome is a word that reads the same backward as forward, e.g., \"madam\" or \"racecar\". The function should return `true` if the word is a palindrome, and `false` otherwise. The function should ignore spaces, punctuation... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 476,
"level": 1,
"question": "Write a function to check if a given word is a palindrome. A palindrome is a word that reads the same backward as forward, e.g., \"madam\" or \"racecar\". The function should return `true` if the word is a palindrome, and `false` otherwise. The function... |
def pascal_triangle(n):
triangle = [[] for _ in range(n)]
for i in range(n):
for j in range(i + 1):
if j == 0 or j == i:
triangle[i].append(1)
else:
triangle[i].append(triangle[i-1][j-1] + triangle[i-1][j])
return triangle | simplelr_Filter | [
{
"content": "Question:\nTry to write some code which is the Pascal's Triangle. pascal_triangle(n) takes an integer n as input and returns a list of lists where each inner list is a row in the triangle.\n\nHere is my attempt to test your code. \n\npascal_triangle(5)\npascal_triangle(2)\npascal_triangle(1)\n\nTh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 477,
"level": 1,
"question": "Try to write some code which is the Pascal's Triangle. pascal_triangle(n) takes an integer n as input and returns a list of lists where each inner list is a row in the triangle.\n\nHere is my attempt to test your code. \n\npascal_triangle(5)\npascal_tri... |
from typing import List
def find_missing_number(nums: List[int]) -> int:
m = len(nums)
expected_sum = m * (m + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are a software engineer tasked with ensuring the integrity of a digital system that assigns unique IDs to user accounts. You need to implement a function to identify any missing user ID in a sequence or determine the next available ID if none are missing.\n\n### Task\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 478,
"level": 1,
"question": "### Scenario\nYou are a software engineer tasked with ensuring the integrity of a digital system that assigns unique IDs to user accounts. You need to implement a function to identify any missing user ID in a sequence or determine the next available ID ... |
def combination_dp(n: int, r: int) -> int:
if r < 0 or r > n:
return 0
if r == 0 or r == n:
return 1
# Initialize DP table
dp = [[0] * (r + 1) for _ in range(n + 1)]
for i in range(n + 1):
max_j = min(i, r)
for j in range(max_j + 1):
if j == 0 or... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Calculate Combination (nCr) using Dynamic Programming\n\n**Context**:\nSuppose you are working on a combinatorial mathematics software that requires numerous calculations of combinations or \"n choose r\" operations. Your current recursive approach is too slow for large in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 479,
"level": 1,
"question": "### Question: Calculate Combination (nCr) using Dynamic Programming\n\n**Context**:\nSuppose you are working on a combinatorial mathematics software that requires numerous calculations of combinations or \"n choose r\" operations. Your current recursive... |
def remove_letters(s):
return ''.join([char for char in s if char.isdigit()]) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove all the letters in a string and only keep the digits.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 480,
"level": 1,
"question": "Write a python function to remove all the letters in a string and only keep the digits.",
"split": "train"
} |
def simplify_text(s):
result = []
started = False
last_space = False
for char in s:
if char == ' ':
if not started:
continue
else:
if not last_space:
result.append(' ')
last_space = True
... | simplelr_Taco | [
{
"content": "Question:\nYou're working on a string manipulation library and need to implement a function to simplify text by removing all instances of multiple consecutive spaces. Your task is to write a function that takes a string as an input and returns a new string with all sequences of multiple spaces rep... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 481,
"level": 1,
"question": "You're working on a string manipulation library and need to implement a function to simplify text by removing all instances of multiple consecutive spaces. Your task is to write a function that takes a string as an input and returns a new string with al... |
def unique_elements(arr):
seen = {}
result = []
for num in arr:
if num not in seen:
seen[num] = True
result.append(num)
return result | simplelr_Evol | [
{
"content": "Question:\nImplement a function that accepts an array of integers and returns a new array containing only the unique elements from the original array, in the order they first appeared. Do not use any additional libraries or built-in functions to remove duplicates.\n\nExample:\nInput: [4, 5, 4, 6, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 482,
"level": 1,
"question": "Implement a function that accepts an array of integers and returns a new array containing only the unique elements from the original array, in the order they first appeared. Do not use any additional libraries or built-in functions to remove duplicates.... |
def convert_to_dict(people):
age_dict = {}
for person in people:
name, age = person
age_dict[name] = age
return age_dict
# Example usage:
people = [('John', 25), ('Anna', 30)]
print(convert_to_dict(people)) # Output: {'John': 25, 'Anna': 30} | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python function that takes a list of tuples, where each tuple represents a person with their name and age, and returns a dictionary with the names as keys and ages as values? For example, given the list `[('John', 25), ('Anna', 30)]`, the function should return `{... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 483,
"level": 1,
"question": "Can you help me with a Python function that takes a list of tuples, where each tuple represents a person with their name and age, and returns a dictionary with the names as keys and ages as values? For example, given the list `[('John', 25), ('Anna', 30... |
def evaluate_polynomial(coefficients, x):
result = 0.0
for i, coefficient in enumerate(coefficients):
result += coefficient * (x ** i)
return result | simplelr_Package | [
{
"content": "Question:\nYour task is to write a function named `evaluate_polynomial` that evaluates a given polynomial at a specific value of x. The polynomial will be represented as a list of coefficients, where the i-th element of the list is the coefficient for the x^i term. The function should perform the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 484,
"level": 1,
"question": "Your task is to write a function named `evaluate_polynomial` that evaluates a given polynomial at a specific value of x. The polynomial will be represented as a list of coefficients, where the i-th element of the list is the coefficient for the x^i term... |
def remove_duplicates(lst): return list(dict.fromkeys(lst)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove duplicates from a list. One line solution.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 485,
"level": 1,
"question": "Write a python function to remove duplicates from a list. One line solution.",
"split": "train"
} |
def is_accepted_by_dfa(transitions, start_state, accept_states, input_string):
# Collect all symbols in the DFA's input alphabet
input_alphabet = {symbol for (state, symbol) in transitions.keys()}
# Check each symbol in the input string
for symbol in input_string:
if symbol not in input_alp... | simplelr_Algorithm | [
{
"content": "Question:\n### Background\nA finite state machine (FSM) is a computational model used to design both computer programs and sequential logic circuits. It is composed of a finite number of states, transitions between those states, and actions. One common type of FSM is the deterministic finite autom... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 486,
"level": 1,
"question": "### Background\nA finite state machine (FSM) is a computational model used to design both computer programs and sequential logic circuits. It is composed of a finite number of states, transitions between those states, and actions. One common type of FSM... |
def minItems(prices, target):
prices_sorted = sorted(prices, reverse=True)
total = 0
count = 0
for price in prices_sorted:
total += price
count += 1
if total >= target:
return count
return -1
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of positive integers representing the prices of different items in a store, and a target amount of money you have. The task is to complete the function minItems() which determines the minimum number of items you need to buy to reach or exceed the target amount of money. I... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 487,
"level": 1,
"question": "Given an array of positive integers representing the prices of different items in a store, and a target amount of money you have. The task is to complete the function minItems() which determines the minimum number of items you need to buy to reach or ex... |
def two_sum(nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return [] | simplelr_Filter | [
{
"content": "Question:\nYou are given an integer array 'nums' and an integer 'target'. You need to find the indices of two numbers in the array that add up to the target.\n\nExample:\n\n Input: nums = [2, 7, 11, 15], target = 9\n Output: [0, 1]\n Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 488,
"level": 1,
"question": "You are given an integer array 'nums' and an integer 'target'. You need to find the indices of two numbers in the array that add up to the target.\n\nExample:\n\n Input: nums = [2, 7, 11, 15], target = 9\n Output: [0, 1]\n Explanation: Because nums[0] +... |
def polygon_area(points):
n = len(points)
if n < 3:
return 0.0
sum1 = 0.0
sum2 = 0.0
for i in range(n):
x_i, y_i = points[i]
x_next, y_next = points[(i + 1) % n]
sum1 += x_i * y_next
sum2 += y_i * x_next
area = 0.5 * abs(sum1 - sum2)
return area | simplelr_Filter | [
{
"content": "Question:\nI am working on a project where I need to calculate the area of a polygon defined by a set of points in a 2D plane. The points are given in order, and I need to write a Python function to do this. Can you guide me on how to approach this problem?\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 489,
"level": 1,
"question": "I am working on a project where I need to calculate the area of a polygon defined by a set of points in a 2D plane. The points are given in order, and I need to write a Python function to do this. Can you guide me on how to approach this problem?",
"s... |
import re
def extract_legal_sentences(text, legal_keywords):
# Split text into sentences using regex to match sentence boundaries
sentences = re.split(r'(?<=[.!?]) +', text)
# Compile the regex pattern for all keywords once
pattern = re.compile(r'\b(' + '|'.join(re.escape(kw) for kw in legal_keywo... | simplelr_Filter | [
{
"content": "Question:\nI've been trying to write a program that can identify and extract \"legal\" sentences from a given text, but it's been a tricky task. I'm hoping you can help me out.\n\nThe text is a mix of sentences that contain specific keywords related to laws and regulations, as well as some irrelev... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 490,
"level": 1,
"question": "I've been trying to write a program that can identify and extract \"legal\" sentences from a given text, but it's been a tricky task. I'm hoping you can help me out.\n\nThe text is a mix of sentences that contain specific keywords related to laws and re... |
def min_operations(s1: str, s2: str) -> int:
m = len(s1)
n = len(s2)
# Create a DP table of (m+1) x (n+1) initialized to 0
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Initialize the first row and column
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nWrite a function that calculates the minimum number of operations required to convert a given string `s1` into another string `s2` using the following operations:\n1. Insert a character\n2. Delete a character\n3. Replace a character\n\nThe function should return... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 491,
"level": 1,
"question": "### Problem Statement\n\nWrite a function that calculates the minimum number of operations required to convert a given string `s1` into another string `s2` using the following operations:\n1. Insert a character\n2. Delete a character\n3. Replace a chara... |
def max_profit(prices):
if not prices or len(prices) < 2:
return 0
min_price = float('inf')
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
else:
profit = price - min_price
if profit > max_profit:
max... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum profit that can be made by trading a stock within a given time period, where only one transaction is permitted. You should return the maximum profit. If no profit can be made, return 0.\nAnswer:\nLet's think step by step.\n",
"role": "user... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 492,
"level": 1,
"question": "Write a python function to find the maximum profit that can be made by trading a stock within a given time period, where only one transaction is permitted. You should return the maximum profit. If no profit can be made, return 0.",
"split": "train"
} |
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
def visualize_seaborn_palettes():
# Categorical Data: Scatterplot with Qualitative Palette
categories = ['A', 'B', 'C', 'D']
num_points = 100
scatter_x = np.random.rand(num_points)
scatter_y = np.random.rand(num_points)
sc... | simplelr_Docs | [
{
"content": "Question:\n### Question:\n\nYou have been given a dataset of randomly generated numeric data, as well as some categorical data. Your task is to write a function in Python that will utilize Seaborn to create and display three distinct types of visualizations using different types of color palettes ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 493,
"level": 1,
"question": "### Question:\n\nYou have been given a dataset of randomly generated numeric data, as well as some categorical data. Your task is to write a function in Python that will utilize Seaborn to create and display three distinct types of visualizations using ... |
def has_subarray_with_sum(nums, target):
prefix_sums = {0}
current_sum = 0
for num in nums:
current_sum += num
if (current_sum - target) in prefix_sums:
return True
prefix_sums.add(current_sum)
return False | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of non-negative integers `nums` and an integer `target`. Find if there exists a subarray (contiguous elements) in `nums` whose sum equals `target`. Return `true` if such a subarray exists, and `false` otherwise.\nAnswer:\nLet's think step by step.\n",
"role": "u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 494,
"level": 1,
"question": "You are given a list of non-negative integers `nums` and an integer `target`. Find if there exists a subarray (contiguous elements) in `nums` whose sum equals `target`. Return `true` if such a subarray exists, and `false` otherwise.",
"split": "train"... |
import psutil
import time
def monitor_memory():
mem_usage = []
for _ in range(10):
mem_percent = psutil.virtual_memory().percent
mem_usage.append(mem_percent)
time.sleep(1)
print(mem_usage)
with open("memory_usage.txt", "w") as f:
for percent in mem_usage:
f.... | simplelr_Package | [
{
"content": "Question:\nWrite a function that monitors the memory usage of the system for 10 seconds, storing the memory percentage used at each second. After 10 seconds, print the list of memory usage percentages and write these values into a text file named \"memory_usage.txt\". Use the psutil library to get... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 495,
"level": 1,
"question": "Write a function that monitors the memory usage of the system for 10 seconds, storing the memory percentage used at each second. After 10 seconds, print the list of memory usage percentages and write these values into a text file named \"memory_usage.tx... |
def total_price(items, item_type):
total = 0
for item in items:
if item['type'] == item_type:
total += item['price']
return total
| simplelr_Taco | [
{
"content": "Question:\nYou are given a list of dictionaries, where each dictionary represents an item in a store with information about its name, type, and price. Your task is to calculate the total price of all items of a specific type. The function should take two parameters: the list of items and the type ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 496,
"level": 1,
"question": "You are given a list of dictionaries, where each dictionary represents an item in a store with information about its name, type, and price. Your task is to calculate the total price of all items of a specific type. The function should take two parameter... |
def rotate_left(lst, n):
if not lst:
return []
k = n % len(lst)
if k == 0:
return lst.copy()
return lst[k:] + lst[:k]
| simplelr_Taco | [
{
"content": "Question:\nImplement a function that takes a list of integers and an integer `n`. The function should return a new list containing the original integers in the list but rotated left `n` times. \n\nFor example, given ```lst = [1, 2, 3, 4, 5]``` and ```n = 2```, the function should return ```[3, 4, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 497,
"level": 1,
"question": "Implement a function that takes a list of integers and an integer `n`. The function should return a new list containing the original integers in the list but rotated left `n` times. \n\nFor example, given ```lst = [1, 2, 3, 4, 5]``` and ```n = 2```, the... |
def matrix_multiply(matrix1: list[list[int]], matrix2: list[list[int]]) -> list[list[int]]:
# Get the dimensions of the matrices
m = len(matrix1)
n = len(matrix1[0])
p = len(matrix2[0])
# Create the result matrix filled with zeros
result = [[0 for _ in range(p)] for _ in range(m)]
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nImplement a function named `matrix_multiply` that takes two matrices represented as two-dimensional lists and returns their product.\n\n### Function Signature\n```python\ndef matrix_multiply(matrix1: list[list[int]], matrix2: list[list[int]]) -> list[list[int]]:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 498,
"level": 1,
"question": "### Problem Statement\nImplement a function named `matrix_multiply` that takes two matrices represented as two-dimensional lists and returns their product.\n\n### Function Signature\n```python\ndef matrix_multiply(matrix1: list[list[int]], matrix2: list... |
def count_unique_substrings(s):
substrings = set()
n = len(s)
for start in range(n):
for end in range(start + 1, n + 1):
substrings.add(s[start:end])
return len(substrings)
# Example usage:
print(count_unique_substrings("abcabc")) # Output: 15 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to count the number of unique substrings of a given string. To illustrate your function, you should count unique substrings for a sample string, such as \"abcabc\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 499,
"level": 1,
"question": "Write a python function to count the number of unique substrings of a given string. To illustrate your function, you should count unique substrings for a sample string, such as \"abcabc\".",
"split": "train"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.