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 hasTwoSum(arr, target):
seen = set()
for num in arr:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers arr and an integer target. Determine whether there exist two distinct indices such that the sum of the elements at those indices is equal to target.\nExample 1:\nInput:\narr = [2, 7, 11, 15]\ntarget = 9\nOutput: True\nExplanation: The elements at indices 0 and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5900,
"level": 1,
"question": "Given an array of integers arr and an integer target. Determine whether there exist two distinct indices such that the sum of the elements at those indices is equal to target.\nExample 1:\nInput:\narr = [2, 7, 11, 15]\ntarget = 9\nOutput: True\nExplana... |
def has_repeating_characters(s):
seen = set()
for char in s:
if char in seen:
return True
seen.add(char)
return False | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given string has repeating characters or not. You should consider both ASCII characters and special characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5901,
"level": 1,
"question": "Write a function to check if a given string has repeating characters or not. You should consider both ASCII characters and special characters.",
"split": "train"
} |
def count_elements(my_list):
"""Return the number of elements in the list."""
return len(my_list) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to count the number of elements in a list and return the count.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5902,
"level": 1,
"question": "Write a function to count the number of elements in a list and return the count.",
"split": "train"
} |
def move_value_to_end(nums, val):
write_pointer = 0
for i in range(len(nums)):
if nums[i] != val:
nums[write_pointer] = nums[i]
write_pointer += 1
for i in range(write_pointer, len(nums)):
nums[i] = val
return nums | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums`, move all instances of a specific value `val` to the end of the array while maintaining the relative order of the other elements. You must do this in-place and in O(n) time complexity.\n\nReturn the modified array after moving the elements.\nAnswer:\nLet's ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5903,
"level": 1,
"question": "Given an integer array `nums`, move all instances of a specific value `val` to the end of the array while maintaining the relative order of the other elements. You must do this in-place and in O(n) time complexity.\n\nReturn the modified array after mo... |
def minimum_total(triangle):
if not triangle:
return 0
# Start with the first row
prev_row = [triangle[0][0]]
for i in range(1, len(triangle)):
current_row = []
for j in range(len(triangle[i])):
if j == 0:
val = prev_row[0] + triangle[i][j]
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **triangular array** of integers `triangle`. Your task is to find the **minimum path sum** from the top to the bottom. Each step you may move to an adjacent number on the row below. More formally, if you are on the \\( i \\)-th row and \\( j \\)-th column, you may move t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5904,
"level": 1,
"question": "You are given a **triangular array** of integers `triangle`. Your task is to find the **minimum path sum** from the top to the bottom. Each step you may move to an adjacent number on the row below. More formally, if you are on the \\( i \\)-th row and ... |
def is_valid_parentheses(s):
stack = []
bracket_map = {')': '(', '}': '{', ']': '['}
for char in s:
if char in bracket_map.values():
stack.append(char)
elif char in bracket_map:
if not stack:
return False
top = stack.pop()
if to... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to check if the parentheses in the given string match in number and they follow the correct order. For example, the string '({[()()]})' should return True, while the string ')(' should return False.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5905,
"level": 1,
"question": "Write a python function to check if the parentheses in the given string match in number and they follow the correct order. For example, the string '({[()()]})' should return True, while the string ')(' should return False.",
"split": "train"
} |
import heapq
from typing import List
def min_merge_cost(populations: List[int]) -> int:
heapq.heapify(populations)
total_cost = 0
while len(populations) > 1:
a = heapq.heappop(populations)
b = heapq.heappop(populations)
merged = a + b
total_cost += merged
heapq.... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are given a list of integers representing the population count of different regions in a country. Your task is to merge these populations into a single region, following these rules:\n1. In each step, you can merge two regions into one. The cost of merging two... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5906,
"level": 1,
"question": "### Problem Statement\nYou are given a list of integers representing the population count of different regions in a country. Your task is to merge these populations into a single region, following these rules:\n1. In each step, you can merge two region... |
import bisect
def total_friend_connections(popularity, k):
popularity.sort()
count = 0
n = len(popularity)
for i in range(n):
target = popularity[i] + k
# Use bisect_right to find the insertion point starting from i+1
j = bisect.bisect_right(popularity, target, i + 1, n) - 1
... | simplelr_Leetcode | [
{
"content": "Question:\nIn a social network, people are represented by a 0-indexed integer array `popularity` where `popularity[i]` represents the popularity score of the i-th person. The social network allows friend connections to be formed between two people if and only if the absolute difference between the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5907,
"level": 1,
"question": "In a social network, people are represented by a 0-indexed integer array `popularity` where `popularity[i]` represents the popularity score of the i-th person. The social network allows friend connections to be formed between two people if and only if ... |
def find_minimum(lst):
if not lst:
return None # or raise ValueError("List is empty")
return min(lst) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the minimum element in a given list of integers. How can I do this using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5908,
"level": 1,
"question": "Write a function to find the minimum element in a given list of integers. How can I do this using Python?",
"split": "train"
} |
def num_decodings(s: str) -> int:
n = len(s)
if n == 0:
return 0
dp = [0] * (n + 1)
dp[0] = 1 # Base case: empty string has one way to be decoded
for i in range(1, n + 1):
# Check if current single digit can be decoded
if s[i-1] != '0':
dp[i] += dp[i-1]
... | simplelr_Evol | [
{
"content": "Question:\nImplement a function that takes a string containing digits and returns the number of possible ways to decode it, based on the mapping 'A' -> 1, 'B' -> 2, ..., 'Z' -> 26. For example, the string \"12\" can be decoded as \"AB\" (1 2) or \"L\" (12). Write a Python function that takes such ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5909,
"level": 1,
"question": "Implement a function that takes a string containing digits and returns the number of possible ways to decode it, based on the mapping 'A' -> 1, 'B' -> 2, ..., 'Z' -> 26. For example, the string \"12\" can be decoded as \"AB\" (1 2) or \"L\" (12). Write... |
from collections import Counter
def majority_element(nums):
count = Counter(nums)
n = len(nums)
for key, value in count.items():
if value > n // 2:
return key
return None | simplelr_Apps | [
{
"content": "Question:\nWrite a function that receives a list of integers and returns the majority element. The majority element is the element that appears more than half of the size of the list. You can assume that the list always contains a majority element. If there is no majority element, the function sho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5910,
"level": 1,
"question": "Write a function that receives a list of integers and returns the majority element. The majority element is the element that appears more than half of the size of the list. You can assume that the list always contains a majority element. If there is no... |
def is_divisible_by_all(x, nums):
if not nums:
return True
if any(num == 0 for num in nums):
return False
return all(x % num == 0 for num in nums) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to check if a given integer x is divisible by all numbers in a given list 'nums'.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5911,
"level": 1,
"question": "Write a python function to check if a given integer x is divisible by all numbers in a given list 'nums'.",
"split": "train"
} |
import heapq
from typing import List
def k_largest_elements(arr: List[int], k: int) -> List[int]:
if k == 0 or len(arr) == 0:
return []
heap = []
for num in arr:
if len(heap) < k:
heapq.heappush(heap, num)
else:
if num > heap[0]:
heapq.he... | simplelr_Package | [
{
"content": "Question:\nYou need to implement a Python function, `k_largest_elements(arr: List[int], k: int) -> List[int]`, that returns the k largest elements from the given list of integers in descending order. You are required to achieve this by utilizing a min-heap data structure to efficiently track the k... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5912,
"level": 1,
"question": "You need to implement a Python function, `k_largest_elements(arr: List[int], k: int) -> List[int]`, that returns the k largest elements from the given list of integers in descending order. You are required to achieve this by utilizing a min-heap data s... |
def min_max_values(numbers):
if not numbers:
return (None, None)
min_val = max_val = numbers[0]
for num in numbers[1:]:
if num < min_val:
min_val = num
elif num > max_val:
max_val = num
return (min_val, max_val) | simplelr_Filter | [
{
"content": "Question:\nHere's a programming exercise:\n\nWrite a program that will take a list of numbers and determine the minimum and maximum values in the list.\n\n**Testing the Program**\n\nTo test the program, use the provided unit tests.\n\n```python\nimport unittest\n\nclass TestMinimumMaximumValues(un... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5913,
"level": 1,
"question": "Here's a programming exercise:\n\nWrite a program that will take a list of numbers and determine the minimum and maximum values in the list.\n\n**Testing the Program**\n\nTo test the program, use the provided unit tests.\n\n```python\nimport unittest\n... |
def is_possible(n: int) -> bool:
if n == 1:
return True
while n % 2 == 0:
n = n // 2
while n % 3 == 0:
n = n // 3
return n == 1 | simplelr_Code_Contests | [
{
"content": "Question:\nSamantha is teaching her younger brother how to use a particular kind of calculator that can only perform multiplication and division. However, her brother can only enter two types of numbers: 2 and 3. Samantha wants to help her brother get a specific number, but she needs to determine ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5914,
"level": 1,
"question": "Samantha is teaching her younger brother how to use a particular kind of calculator that can only perform multiplication and division. However, her brother can only enter two types of numbers: 2 and 3. Samantha wants to help her brother get a specific ... |
def max_distance(matrix):
max_val = -float('inf')
min_val = float('inf')
for row in matrix:
for num in row:
if num > max_val:
max_val = num
if num < min_val:
min_val = num
return max_val - min_val | simplelr_Leetcode | [
{
"content": "Question:\nGiven an `m x n` integer matrix, define the distance between two cells `(i1, j1)` and `(i2, j2)` as the absolute difference in their values. Find the maximum distance you can achieve between any two distinct cells in the matrix such that the value in the first cell is greater than the v... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5915,
"level": 1,
"question": "Given an `m x n` integer matrix, define the distance between two cells `(i1, j1)` and `(i2, j2)` as the absolute difference in their values. Find the maximum distance you can achieve between any two distinct cells in the matrix such that the value in t... |
import math
def maxPossibleGCD(nums):
current_gcd = nums[0]
for num in nums[1:]:
current_gcd = math.gcd(current_gcd, num)
if current_gcd == 1:
break
return current_gcd
| simplelr_Taco | [
{
"content": "Question:\nYou are given an array of positive integers nums. You can perform the following operation on the array any number of times:\n\n- Choose any two elements nums[i] and nums[j] such that nums[i] >= nums[j].\n- Replace nums[i] with nums[i] - nums[j].\n\nYour goal is to maximize the greatest ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5916,
"level": 1,
"question": "You are given an array of positive integers nums. You can perform the following operation on the array any number of times:\n\n- Choose any two elements nums[i] and nums[j] such that nums[i] >= nums[j].\n- Replace nums[i] with nums[i] - nums[j].\n\nYou... |
from typing import List
from collections import deque
def is_path_exists(grid: List[List[int]]) -> bool:
rows = len(grid)
if rows == 0:
return False
cols = len(grid[0])
if cols == 0:
return False
start = (0, 0)
end = (rows - 1, cols - 1)
if grid[start[0]][start[1]]... | simplelr_Taco | [
{
"content": "Question:\nIn a game, you control a character that moves through a 2D grid. The grid is represented as an `MxN` matrix where each cell can either be `0` (empty) or `1` (obstacle). Your character can move up, down, left, or right, but cannot move into a cell with an obstacle. Your task is to determ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5917,
"level": 1,
"question": "In a game, you control a character that moves through a 2D grid. The grid is represented as an `MxN` matrix where each cell can either be `0` (empty) or `1` (obstacle). Your character can move up, down, left, or right, but cannot move into a cell with ... |
def find_odd_pair(nums):
"""
Find the first pair of adjacent elements in a list that sum to an odd number.
Args:
nums (list): A list of integers.
Returns:
tuple: The first pair (a, b) where a and b are adjacent and a + b is odd.
Returns None if no such pair exists.
"... | simplelr_Filter | [
{
"content": "Question:\nGiven a list of integers, write a function to find the first pair of adjacent elements that sum to an odd number.\n\nExample:\nInput: [2, 3, 4, 5, 6]\nOutput: (2, 3)\n\nIf no such pair exists, return None.\n\nHere is my code:\n\n```python\ndef find_odd_pair(nums):\n for i in range(le... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5918,
"level": 1,
"question": "Given a list of integers, write a function to find the first pair of adjacent elements that sum to an odd number.\n\nExample:\nInput: [2, 3, 4, 5, 6]\nOutput: (2, 3)\n\nIf no such pair exists, return None.\n\nHere is my code:\n\n```python\ndef find_odd... |
def euler_totient(n):
if n == 1:
return 1
factors = set()
temp = n
i = 2
while i * i <= temp:
if temp % i == 0:
factors.add(i)
while temp % i == 0:
temp //= i
i += 1
if temp > 1:
factors.add(temp)
result = n
for p in... | simplelr_Data_Structure | [
{
"content": "Question:\n**Euler's Totient Function Calculation**\n\nYour task is to implement the function `euler_totient(n)` that computes Euler's totient function for a given integer `n`, using the algorithm structure detailed above. The totient function, denoted ϕ(n), counts the integers from 1 to n that ar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5919,
"level": 1,
"question": "**Euler's Totient Function Calculation**\n\nYour task is to implement the function `euler_totient(n)` that computes Euler's totient function for a given integer `n`, using the algorithm structure detailed above. The totient function, denoted ϕ(n), coun... |
def next_permutation(num: int) -> int:
digits = list(map(int, str(num)))
n = len(digits)
pivot = -1
# Step 1: Find the pivot
for i in range(n-2, -1, -1):
if digits[i] < digits[i+1]:
pivot = i
break
if pivot == -1:
return -1
# Step 2: Find the smalles... | simplelr_Data_Structure | [
{
"content": "Question:\n### Coding Challenge: Next Permutation Algorithm\n\n#### Objective:\nWrite a function that finds the next higher permutation of a given number using the same set of digits. If no such permutation exists, return -1.\n\n#### Function Signature:\n```python\ndef next_permutation(num: int) -... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5920,
"level": 1,
"question": "### Coding Challenge: Next Permutation Algorithm\n\n#### Objective:\nWrite a function that finds the next higher permutation of a given number using the same set of digits. If no such permutation exists, return -1.\n\n#### Function Signature:\n```pytho... |
import heapq
def min_elevation_path(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
max_elevation = [[float('inf')] * n for _ in range(m)]
max_elevation[0][0] = grid[0][0]
heap = []
heapq.heappush(heap, (grid[0][0], 0, 0))
directions = [(-1, 0), (1, 0... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a 2D grid of integers `grid` of size `m x n`. You are currently located at the top-left corner of the grid (i.e., `grid[0][0]`) and want to reach the bottom-right corner (i.e., `grid[m-1][n-1]`). The grid represents the elevation levels. Your aim is to minimize the maximum... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5921,
"level": 1,
"question": "You are given a 2D grid of integers `grid` of size `m x n`. You are currently located at the top-left corner of the grid (i.e., `grid[0][0]`) and want to reach the bottom-right corner (i.e., `grid[m-1][n-1]`). The grid represents the elevation levels. ... |
from typing import List
def spell_checker(known_words: List[str], document_words: List[str]) -> List[str]:
known_set = set(known_words)
misspelled = []
for word in document_words:
if word not in known_set:
misspelled.append(word)
return misspelled | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are tasked with implementing a spell checker. Given a list of known words and a list of words from a document, create a function that identifies which words in the document are misspelled based on the known words list. The function should return a list of miss... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5922,
"level": 1,
"question": "### Problem Statement\nYou are tasked with implementing a spell checker. Given a list of known words and a list of words from a document, create a function that identifies which words in the document are misspelled based on the known words list. The fu... |
def min_cut_palindrome_partition(s):
n = len(s)
if n == 0:
return 0
# Precompute the palindrome table
is_palindrome = [[False] * n for _ in range(n)]
for i in range(n):
is_palindrome[i][i] = True
for i in range(n - 1):
if s[i] == s[i + 1]:
is_palindrome[i... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the minimum number of cuts required to partition a given string into palindromic substrings.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5923,
"level": 1,
"question": "Write a python function to find the minimum number of cuts required to partition a given string into palindromic substrings.",
"split": "train"
} |
def merge_sorted_lists(list1, list2):
result = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
result.append(list1[i])
i += 1
else:
result.append(list2[j])
j += 1
result.extend(list1[i:])
result.extend(lis... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to merge two sorted lists into one sorted list. The function should return the merged list without using any additional space (except for a small amount of space for function variables).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5924,
"level": 1,
"question": "Write a python function to merge two sorted lists into one sorted list. The function should return the merged list without using any additional space (except for a small amount of space for function variables).",
"split": "train"
} |
def count_unique_substrings(s: str) -> int:
# Build the suffix automaton
sa = []
sa.append({'len': 0, 'link': -1, 'next': dict()}) # initial state
last = 0
size = 1
for c in s:
# Create new state
curr = size
sa.append({
'len': sa[last]['len'] + 1,
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are required to implement a function that counts the number of unique substrings within a given string.\n\nYour task is to write a function `count_unique_substrings(s: str) -> int` that takes in a string `s` and returns the count of all possible unique subst... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5925,
"level": 1,
"question": "### Problem Statement\n\nYou are required to implement a function that counts the number of unique substrings within a given string.\n\nYour task is to write a function `count_unique_substrings(s: str) -> int` that takes in a string `s` and returns the... |
def spending_analysis(transactions):
if not transactions:
return (0, 0, 0)
total = sum(transactions)
count = len(transactions)
average = total / count
avg_rounded = round(average)
max_amount = max(transactions)
return (avg_rounded, max_amount, total) | simplelr_Code_Contests | [
{
"content": "Question:\nA bank needs to develop a new feature that helps its customers manage their finances better. To do this, they need to calculate the total spending behavior of customers based on their bank statements. Each bank statement consists of several transactions, each represented by the amount s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5926,
"level": 1,
"question": "A bank needs to develop a new feature that helps its customers manage their finances better. To do this, they need to calculate the total spending behavior of customers based on their bank statements. Each bank statement consists of several transaction... |
import math
def is_prime(number):
if number < 2:
return False
if number == 2:
return True
if number % 2 == 0:
return False
max_divisor = math.isqrt(number) + 1
for i in range(3, max_divisor, 2):
if number % i == 0:
return False
return True | simplelr_Filter | [
{
"content": "Question:\nCreate a function named \"is_prime\" that takes one parameter, \"number\", and returns True if the number is prime, and False otherwise. A prime number is defined as a number greater than 1 that has no positive divisors other than 1 and itself.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5927,
"level": 1,
"question": "Create a function named \"is_prime\" that takes one parameter, \"number\", and returns True if the number is prime, and False otherwise. A prime number is defined as a number greater than 1 that has no positive divisors other than 1 and itself.",
"sp... |
def calculate_manhattan_distance(x1, y1, x2, y2):
for param in [x1, y1, x2, y2]:
if type(param) is not int:
raise ValueError("All coordinates must be integers.")
distance = abs(x2 - x1) + abs(y2 - y1)
return distance | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\n\nYou are a software engineer at a logistics company, and your current task is to develop a function that calculates the shortest route between two delivery points using the Manhattan Distance. The Manhattan Distance, sometimes called the \"Taxicab Distance,\" is the sum o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5928,
"level": 1,
"question": "### Scenario\n\nYou are a software engineer at a logistics company, and your current task is to develop a function that calculates the shortest route between two delivery points using the Manhattan Distance. The Manhattan Distance, sometimes called the... |
def reformat_license_key(s: str, k: int) -> str:
processed = s.replace('-', '').upper()
if not processed:
return ""
length = len(processed)
remainder = length % k
if remainder == 0:
first_length = k
else:
first_length = remainder
groups = []
if first_length > 0 an... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` that represents a license key which is a sequence of alphanumeric characters grouped by dashes. The string is reformatted to be divided into groups of size `k` (where `k` is a positive integer) separated by dashes. The first group may be shorter than `k` but s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5929,
"level": 1,
"question": "You are given a string `s` that represents a license key which is a sequence of alphanumeric characters grouped by dashes. The string is reformatted to be divided into groups of size `k` (where `k` is a positive integer) separated by dashes. The first ... |
def longest_consecutive(nums):
num_set = set(nums)
max_length = 0
for num in nums:
if (num - 1) not in num_set:
current_length = 1
next_num = num + 1
while next_num in num_set:
current_length += 1
next_num += 1
max_lengt... | simplelr_Apps | [
{
"content": "Question:\nGiven an array of unsorted integers, you need to find the length of the longest sequence of consecutive elements. The sequence should not necessarily be sorted. \n\nNote:\nYour algorithm's time complexity should be O(n).\n\nExample 1:\n\nInput:\nnums = [100, 4, 200, 1, 3, 2]\n\nOutput:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5930,
"level": 1,
"question": "Given an array of unsorted integers, you need to find the length of the longest sequence of consecutive elements. The sequence should not necessarily be sorted. \n\nNote:\nYour algorithm's time complexity should be O(n).\n\nExample 1:\n\nInput:\nnums =... |
from typing import List
def maxSumSubarray(arr: List[int], k: int) -> int:
n = len(arr)
if k < 1 or n < k:
return -1
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_su... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `arr` of length `n` and an integer `k`. You need to return the maximum sum of a subarray of length `k`. A subarray is a contiguous non-empty sequence of elements within an array. If the length of the array is less than `k`, return `-1`.\n\nThe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5931,
"level": 1,
"question": "You are given a **0-indexed** integer array `arr` of length `n` and an integer `k`. You need to return the maximum sum of a subarray of length `k`. A subarray is a contiguous non-empty sequence of elements within an array. If the length of the array is... |
from typing import List
def knapsack(max_weight: int, weights: List[int], values: List[int]) -> int:
n = len(weights)
# Create a 2D DP table with (n+1) rows and (max_weight+1) columns
dp = [[0] * (max_weight + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
weight = weights[i - 1]
... | simplelr_Algorithm | [
{
"content": "Question:\n### Knapsack Problem using Dynamic Programming\n\nAlice is a logistician responsible for optimizing the load of a spacecraft. She needs to determine the maximum value that can be carried in the spacecraft given a weight limit and an array of items, each with a specific weight and value.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5932,
"level": 1,
"question": "### Knapsack Problem using Dynamic Programming\n\nAlice is a logistician responsible for optimizing the load of a spacecraft. She needs to determine the maximum value that can be carried in the spacecraft given a weight limit and an array of items, eac... |
def filter_top_students(records, passing_score):
# Filter the students who have scores equal to or higher than the passing score
filtered = [record for record in records if record[1] >= passing_score]
# Sort the filtered list by descending score, then by ascending name
sorted_students = sorted(filt... | simplelr_Package | [
{
"content": "Question:\nYou are required to develop a function `filter_top_students(records, passing_score)` that filters out the top students from a list of student records based on a given minimum passing score. Each student record comprises a student's name and their score in a subject.\n\nThe function shou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5933,
"level": 1,
"question": "You are required to develop a function `filter_top_students(records, passing_score)` that filters out the top students from a list of student records based on a given minimum passing score. Each student record comprises a student's name and their score... |
from collections import Counter
def can_make_equal(arr, k):
n = len(arr)
if k >= n:
return True
count = Counter(arr)
required = n - k
for v in count.values():
if v >= required:
return True
return False | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` and an integer `k`. You can make at most `k` operations on the array, where in each operation, you can either:\n1. Remove a single element from the array.\n2. Increment a single element of the array by 1.\n\nYour goal is to make all elements in t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5934,
"level": 1,
"question": "You are given an array of integers `arr` and an integer `k`. You can make at most `k` operations on the array, where in each operation, you can either:\n1. Remove a single element from the array.\n2. Increment a single element of the array by 1.\n\nYou... |
from typing import Union, List
def prime_factors_or_prime_check(n: int) -> Union[bool, List[int]]:
if n < 2:
return False
original_n = n
factors = []
i = 2
while i * i <= n:
while n % i == 0:
factors.append(i)
n = n // i
i += 1
if n > 1:
f... | simplelr_Data_Structure | [
{
"content": "Question:\n### Primality Checker Enhancement\n\nYou are asked to enhance the existing prime-check algorithm by implementing an additional function that not only checks for primality but also returns a list of prime factors for non-prime numbers. Your task is to write a Python function called `prim... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5935,
"level": 1,
"question": "### Primality Checker Enhancement\n\nYou are asked to enhance the existing prime-check algorithm by implementing an additional function that not only checks for primality but also returns a list of prime factors for non-prime numbers. Your task is to w... |
def calculate_total_compensation(tuples_list):
total_comp = {}
for emp_id, _, comp in tuples_list:
total_comp[emp_id] = total_comp.get(emp_id, 0) + comp
return total_comp | simplelr_Leetcode | [
{
"content": "Question:\nA company wishes to track the compensation given to its employees on a bi-weekly basis. The company issues a report that consists of a list of tuples, where each tuple represents the compensation details for an employee in a given week. Each tuple consists of three values: `(employee_id... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5936,
"level": 1,
"question": "A company wishes to track the compensation given to its employees on a bi-weekly basis. The company issues a report that consists of a list of tuples, where each tuple represents the compensation details for an employee in a given week. Each tuple cons... |
import random
import string
def generate_password(length):
"""Generate a random password of a given length with at least one lowercase, uppercase, digit, and punctuation."""
if length < 8:
print("Password length should be at least 8 characters.")
return None
# Define the character sets
... | simplelr_Filter | [
{
"content": "Question:\ndef generate_password(length):\n \"\"\"Generate a random password of a given length.\"\"\"\n import random\n import string\n\n if length < 8:\n print(\"Password length should be at least 8 characters.\")\n return None\n\n all_characters = string.ascii_letter... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5937,
"level": 1,
"question": "def generate_password(length):\n \"\"\"Generate a random password of a given length.\"\"\"\n import random\n import string\n\n if length < 8:\n print(\"Password length should be at least 8 characters.\")\n return None\n\n a... |
import itertools
def subsets_sorted(lst):
sorted_lst = sorted(lst)
subsets = []
for k in range(len(sorted_lst) + 1):
subsets.extend(itertools.combinations(sorted_lst, k))
return [list(subset) for subset in subsets] | simplelr_Apps | [
{
"content": "Question:\nGiven a list of integers, you are required to generate all possible subsets of the list and then return the subsets sorted by their lengths, and for subsets with the same length, you should order them lexicographically based on their string representation. \n\nExample Input\n-----------... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5938,
"level": 1,
"question": "Given a list of integers, you are required to generate all possible subsets of the list and then return the subsets sorted by their lengths, and for subsets with the same length, you should order them lexicographically based on their string representat... |
def string_length_parity(s):
return "Even" if len(s) % 2 == 0 else "Odd" | simplelr_Filter | [
{
"content": "Question:\nI have a string in Python, and I need to determine if its length is even or odd. Can you help me write a function to accomplish this? It should return \"Even\" if the length of the string is even, and \"Odd\" if the length is odd.\nAnswer:\nLet's think step by step.\n",
"role": "use... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5939,
"level": 1,
"question": "I have a string in Python, and I need to determine if its length is even or odd. Can you help me write a function to accomplish this? It should return \"Even\" if the length of the string is even, and \"Odd\" if the length is odd.",
"split": "train"
... |
from typing import List
def interpolation_search(array: List[int], search_key: int) -> int:
"""
:param array: The array to be searched.
:param search_key: The key to be searched in the array.
:returns: Index of search_key in array if found, else -1.
"""
low = 0
high = len(array) - 1
w... | simplelr_Data_Structure | [
{
"content": "Question:\nGiven a sorted list of integers in increasing order, an algorithm 'Interpolation Search' is to be implemented to find the position of a given target value within the list efficiently. The function should be designed to optimize the search process, especially for uniformly distributed ar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5940,
"level": 1,
"question": "Given a sorted list of integers in increasing order, an algorithm 'Interpolation Search' is to be implemented to find the position of a given target value within the list efficiently. The function should be designed to optimize the search process, espe... |
def run_length_encoding(s):
if not s:
return []
result = []
prev_char = s[0]
count = 1
for char in s[1:]:
if char == prev_char:
count += 1
else:
result.append((prev_char, count))
prev_char = char
count = 1
result.append((pre... | simplelr_Taco | [
{
"content": "Question:\nA **run-length encoding (RLE)** is a simple form of data compression in which consecutive occurrences of the same data value are replaced by a single data value and a count. For example, the string `\"aaabbbbcc\"` would be represented as `[('a', 3), ('b', 4), ('c', 2)]`.\n\nGiven a stri... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5941,
"level": 1,
"question": "A **run-length encoding (RLE)** is a simple form of data compression in which consecutive occurrences of the same data value are replaced by a single data value and a count. For example, the string `\"aaabbbbcc\"` would be represented as `[('a', 3), ('... |
def find_largest(arr):
if not arr:
return None
max_element = arr[0]
for element in arr:
if element > max_element:
max_element = element
return max_element | simplelr_Filter | [
{
"content": "Question:\ndef find_largest(arr):\n if not arr:\n return None\n max_element = arr[0]\n for element in arr:\n if element > max_element:\n max_element = element\n return max_element\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5942,
"level": 1,
"question": "def find_largest(arr):\n if not arr:\n return None\n max_element = arr[0]\n for element in arr:\n if element > max_element:\n max_element = element\n return max_element",
"split": "train"
} |
from email.message import EmailMessage
def create_multipart_email(headers: dict, parts: list, set_unixfrom: bool = False) -> str:
main_msg = EmailMessage()
for key, value in headers.items():
main_msg[key] = value
main_msg.make_mixed()
for part in parts:
part_msg = EmailMessage()
... | simplelr_Docs | [
{
"content": "Question:\nYou are required to create a function that constructs a multipart email message with specific headers and payloads, and then serializes it into a string. Your function should demonstrate the ability to handle headers, manage payloads in a multipart message, and ensure proper serializati... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5943,
"level": 1,
"question": "You are required to create a function that constructs a multipart email message with specific headers and payloads, and then serializes it into a string. Your function should demonstrate the ability to handle headers, manage payloads in a multipart mes... |
def evaluate_expression(s):
if not s:
return 0
result = int(s[0])
for i in range(1, len(s), 2):
op = s[i]
num = int(s[i + 1])
if op == '+':
result += num
elif op == '-':
result -= num
return result | simplelr_Filter | [
{
"content": "Question:\nI want you to construct a rudimentary parser in Python that's designed to read and process simple mathematical expressions. The expressions will never have spaces and will contain the operators \"+\", \"-\" for addition and subtraction respectively. A single digit (0-9) will always foll... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5944,
"level": 1,
"question": "I want you to construct a rudimentary parser in Python that's designed to read and process simple mathematical expressions. The expressions will never have spaces and will contain the operators \"+\", \"-\" for addition and subtraction respectively. A ... |
def length_of_longest_substring(s):
char_map = {}
max_length = 0
left = 0
for right in range(len(s)):
char = s[right]
if char in char_map and char_map[char] >= left:
left = char_map[char] + 1
char_map[char] = right
current_length = right - left + 1
if ... | simplelr_Filter | [
{
"content": "Question:\nGenerate a function that finds the length of the longest substring without repeating characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5945,
"level": 1,
"question": "Generate a function that finds the length of the longest substring without repeating characters.",
"split": "train"
} |
def get_even_number_list(input_list, number_list):
"""
Appends even numbers from the input_list to the number_list.
If the number list already contains a number it doesn't add it.
Parameters:
input_list (list): List of integers
number_list (list): List of integers
Returns:
numb... | simplelr_Filter | [
{
"content": "Question:\nIn this problem, I append a list of numbers with even numbers from the given list. If the list already contains a number, I don't add it. \n\nFor example, if my number list is empty and the input list is [1,2,3,4] then the output will be [2,4]. \n\nIf the input list is [2,4,6,8] and my ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5946,
"level": 1,
"question": "In this problem, I append a list of numbers with even numbers from the given list. If the list already contains a number, I don't add it. \n\nFor example, if my number list is empty and the input list is [1,2,3,4] then the output will be [2,4]. \n\nIf ... |
from typing import List
def search_in_dataset(data: List[int], queries: List[int]) -> List[int]:
"""
This function searches for each query in the dataset and returns the first occurrence index.
It uses a dictionary to cache results for efficient lookups, especially for repeated queries.
Args:
data... | simplelr_Data_Structure | [
{
"content": "Question:\n### Linear Search Optimization Challenge\n\n#### Scenario\nImagine you are tasked with searching for specific elements in a large dataset repeatedly. You recognize that a linear search is less efficient with increased data size, prompting the need to search for a more optimal approach.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5947,
"level": 1,
"question": "### Linear Search Optimization Challenge\n\n#### Scenario\nImagine you are tasked with searching for specific elements in a large dataset repeatedly. You recognize that a linear search is less efficient with increased data size, prompting the need to s... |
def countOccurrences(s, c):
return s.count(c)
| simplelr_Taco | [
{
"content": "Question:\nGiven a string `s` and a character `c`, your task is to find the number of occurrences of the character `c` in the string `s`.\n\nExample 1:\nInput:\ns = \"hello\"\nc = 'l'\nOutput:\n2\nExplanation:\nThe character 'l' appears 2 times in the string \"hello\".\n\nExample 2:\nInput:\ns = \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5948,
"level": 1,
"question": "Given a string `s` and a character `c`, your task is to find the number of occurrences of the character `c` in the string `s`.\n\nExample 1:\nInput:\ns = \"hello\"\nc = 'l'\nOutput:\n2\nExplanation:\nThe character 'l' appears 2 times in the string \"he... |
from collections import defaultdict
def longest_substring_with_k_distinct(s: str, k: int) -> str:
left = 0
counts = defaultdict(int)
max_length = 0
start = 0
for right in range(len(s)):
char = s[right]
counts[char] += 1
# Shrink the window until we have at most k di... | simplelr_Filter | [
{
"content": "Question:\nThis is a problem I am trying to solve:\n\nYou are given a string `s` containing lowercase English letters. You need to find the longest substring of `s` which contains at most `k` distinct characters.\n\n**Example:**\n\n```\nInput: s = \"eceba\", k = 2\nOutput: \"ece\"\n```\n\n**Here's... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5949,
"level": 1,
"question": "This is a problem I am trying to solve:\n\nYou are given a string `s` containing lowercase English letters. You need to find the longest substring of `s` which contains at most `k` distinct characters.\n\n**Example:**\n\n```\nInput: s = \"eceba\", k = ... |
def sum_of_unique_subsequences(arr: list) -> int:
unique_elements = set(arr)
return sum(unique_elements) | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of All Unique Subsequences\n\n#### Context\nIn many programming problems, you need to work with subsequences of arrays. A subsequence is derived from an array by deleting some or no elements without changing the order of the remaining elements. This problem will test your abilit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5950,
"level": 1,
"question": "### Sum of All Unique Subsequences\n\n#### Context\nIn many programming problems, you need to work with subsequences of arrays. A subsequence is derived from an array by deleting some or no elements without changing the order of the remaining elements.... |
import math
def evaluate_postfix(expression: list[str]) -> int:
stack = []
for token in expression:
if token in '+-*/':
b = stack.pop()
a = stack.pop()
if token == '+':
res = a + b
elif token == '-':
res = a - b
... | simplelr_Algorithm | [
{
"content": "Question:\nYou are required to write a function that evaluates the postfix (Reverse Polish Notation) expression and returns the result. The function should support the four basic arithmetic operators ('+', '-', '*', '/').\n\n### Function Signature\n```python\ndef evaluate_postfix(expression: List[... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5951,
"level": 1,
"question": "You are required to write a function that evaluates the postfix (Reverse Polish Notation) expression and returns the result. The function should support the four basic arithmetic operators ('+', '-', '*', '/').\n\n### Function Signature\n```python\ndef... |
def unbounded_knapsack(W: int, val: list[int], wt: list[int]) -> int:
n = len(val)
dp = [0] * (W + 1)
for i in range(1, W + 1):
max_val = 0
for j in range(n):
if wt[j] <= i:
current = dp[i - wt[j]] + val[j]
if current > max_val:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are given an unbounded knapsack with an infinite supply of items, each with a specific weight and value. Your task is to implement a function `unbounded_knapsack` to determine the maximum value that can be achieved with a given capacity of the knapsack.\n\n###... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5952,
"level": 1,
"question": "### Problem Statement\nYou are given an unbounded knapsack with an infinite supply of items, each with a specific weight and value. Your task is to implement a function `unbounded_knapsack` to determine the maximum value that can be achieved with a giv... |
def longest_even_subsequence_length(a):
count = 0
for num in a:
if num % 2 == 0:
count += 1
return count | simplelr_Apps | [
{
"content": "Question:\n# Task\nGiven an array of integers, determine the length of the longest subsequence such that every element in the subsequence is an even number. The elements of the subsequence do not need to be contiguous but should preserve the original order of appearance in the array.\n\n# Example\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5953,
"level": 1,
"question": "# Task\nGiven an array of integers, determine the length of the longest subsequence such that every element in the subsequence is an even number. The elements of the subsequence do not need to be contiguous but should preserve the original order of app... |
def factorial(n):
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
elif n <= 1:
return 1
else:
return n * factorial(n - 1) | simplelr_Filter | [
{
"content": "Question:\nDesign an algorithm to calculate the factorial of a number using recursion in Python. Ensure to include a base case to handle the termination of the recursion.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5954,
"level": 1,
"question": "Design an algorithm to calculate the factorial of a number using recursion in Python. Ensure to include a base case to handle the termination of the recursion.",
"split": "train"
} |
import json
def json_to_ascii(json_input):
"""
This function takes a JSON string, decodes it into a Python object,
and then encodes it back into an ASCII string.
Args:
json_input (str): The input JSON string.
Returns:
str: The ASCII-encoded JSON string.
"""
# Deco... | simplelr_Filter | [
{
"content": "Question:\nCreate a script that takes a JSON array as input, decodes it into a Python object, then encodes it again as an ASCII string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5955,
"level": 1,
"question": "Create a script that takes a JSON array as input, decodes it into a Python object, then encodes it again as an ASCII string.",
"split": "train"
} |
def calculate_gcd(a, b):
a = abs(a)
b = abs(b)
while b:
a, b = b, a % b
return a
# Example usage:
print(calculate_gcd(48, 18)) # Output: 6
print(calculate_gcd(-48, 18)) # Output: 6
print(calculate_gcd(0, 5)) # Output: 5
print(calculate_gcd(0, 0)) # Output: 0 | simplelr_Filter | [
{
"content": "Question:\n### Function to Calculate GCD of Two Numbers\n#### Using Euclidean Algorithm\n```python\ndef calculate_gcd(a, b):\n \"\"\"\n Calculate the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.\n\n Args:\n a (int): The first number.\n b (int):... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5956,
"level": 1,
"question": "### Function to Calculate GCD of Two Numbers\n#### Using Euclidean Algorithm\n```python\ndef calculate_gcd(a, b):\n \"\"\"\n Calculate the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.\n\n Args:\n a (int): ... |
def coin_change(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 ... | simplelr_Apps | [
{
"content": "Question:\nYou are given a list of positive integers representing the number of coins of each denomination in a vending machine. The vending machine accepts an integer amount of money and will return the minimum number of coins needed to match that amount. If it is not possible to match the amount... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5957,
"level": 1,
"question": "You are given a list of positive integers representing the number of coins of each denomination in a vending machine. The vending machine accepts an integer amount of money and will return the minimum number of coins needed to match that amount. If it ... |
from itertools import permutations
from typing import List
def find_anagrams(s: str) -> List[str]:
all_perms = permutations(s)
unique_perms = set()
for p in all_perms:
unique_perms.add(''.join(p))
return sorted(unique_perms) | simplelr_Apps | [
{
"content": "Question:\nCreate a function `find_anagrams` to help Chef find all unique anagrams of a given string. An anagram is a rearrangement of the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once. Chef wants the anagrams to be sorted in lexicographic... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5958,
"level": 1,
"question": "Create a function `find_anagrams` to help Chef find all unique anagrams of a given string. An anagram is a rearrangement of the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once. Chef wants the ana... |
def min_moves_to_balance(s: str) -> int:
x = s.count('x')
y = s.count('y')
return abs(x - y)
| simplelr_Taco | [
{
"content": "Question:\nGiven a string `s` consisting of characters 'x' and 'y' only, your task is to make the string balanced. A string is considered balanced if the number of 'x' characters is equal to the number of 'y' characters. In one move, you can remove any one character from the string.\n\nWrite a fun... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5959,
"level": 1,
"question": "Given a string `s` consisting of characters 'x' and 'y' only, your task is to make the string balanced. A string is considered balanced if the number of 'x' characters is equal to the number of 'y' characters. In one move, you can remove any one charac... |
def has_adjacent_pair_sum_zero(numbers):
if len(numbers) < 2:
return False
for i in range(len(numbers) - 1):
if numbers[i] + numbers[i + 1] == 0:
return True
return False | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that will take in a list of integers, and return True if there is at least one pair of adjacent integers that sum up to 0. For example, the function should return True for the input of `[1, -1, 3, 4]` because the pair `1` and `-1` sum up to `0`.\nAnswer:\nLet's think s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5960,
"level": 1,
"question": "Create a function that will take in a list of integers, and return True if there is at least one pair of adjacent integers that sum up to 0. For example, the function should return True for the input of `[1, -1, 3, 4]` because the pair `1` and `-1` sum... |
def simplify_path(path: str) -> str:
stack = []
tokens = path.split('/')
for token in tokens:
if token == '' or token == '.':
continue
elif token == '..':
if stack:
stack.pop()
else:
stack.append(token)
return '/' + '/'.join(sta... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are asked to simplify Unix-style file paths. Your task is to implement a function `def simplify_path(path: str) -> str` that simplifies a given absolute path for a file (Unix-style).\n\n#### Input\n- `path`: a string representing an absolute Unix-style path (from `/` to `/home//foo/... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5961,
"level": 1,
"question": "You are asked to simplify Unix-style file paths. Your task is to implement a function `def simplify_path(path: str) -> str` that simplifies a given absolute path for a file (Unix-style).\n\n#### Input\n- `path`: a string representing an absolute Unix-s... |
from typing import List
def rotate_list(nums: List[int], k: int) -> List[int]:
if not nums:
return []
n = len(nums)
k %= n
return nums[-k:] + nums[:-k] | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n**Context**: In the context of data manipulation and list processing, one often has to reorganize or transform lists to meet certain criteria. One common operation is rotating lists or arrays by a given number of positions.\n\n**Question**:\n\nImplement... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5962,
"level": 1,
"question": "### Coding Assessment Question\n\n**Context**: In the context of data manipulation and list processing, one often has to reorganize or transform lists to meet certain criteria. One common operation is rotating lists or arrays by a given number of posit... |
def compress_string(s: str) -> str:
if not s:
return ""
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
if count > 1:
result.append(current_char + str(count))
else:
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a string consisting of lowercase alphabets. You need to compress the string using the following algorithm:\n\n- For each consecutive group of the same character, replace it with the character followed by the frequency of that character group.\n- If the frequency of any gro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5963,
"level": 1,
"question": "You are given a string consisting of lowercase alphabets. You need to compress the string using the following algorithm:\n\n- For each consecutive group of the same character, replace it with the character followed by the frequency of that character gr... |
def median(numbers):
sorted_numbers = sorted(numbers)
n = len(sorted_numbers)
if n % 2 == 1:
return sorted_numbers[n // 2]
else:
return (sorted_numbers[(n // 2) - 1] + sorted_numbers[n // 2]) / 2 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the median of a list of numbers. The median is the middle value in a sorted list of numbers. If the list has an even number of elements, the median is the average of the two middle numbers. For example, the median of [3, 1, 2, 4, 5] is 3, and for [3, 1,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5964,
"level": 1,
"question": "Create a function that calculates the median of a list of numbers. The median is the middle value in a sorted list of numbers. If the list has an even number of elements, the median is the average of the two middle numbers. For example, the median of [... |
def find_the_longest_substring(s):
vowels = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}
seen = {0: -1} # Initialize with state 0 at index -1
mask = 0
max_len = 0
for index, char in enumerate(s):
if char in vowels:
mask ^= (1 << vowels[char]) # Toggle the bit for the current vowel... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters. Your task is to determine the length of the longest substring of `s` where each vowel ('a', 'e', 'i', 'o', 'u') appears an even number of times. Return _an integer representing the length of the longest such substring._... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5965,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters. Your task is to determine the length of the longest substring of `s` where each vowel ('a', 'e', 'i', 'o', 'u') appears an even number of times. Return _an integer representing the len... |
def dijkstra(num_nodes: int, edges: list[tuple[int, int, int]], start_node: int) -> list[int]:
"""Returns the list of shortest distances from the start_node to each node."""
import heapq
# Build adjacency list
adj = [[] for _ in range(num_nodes + 1)]
for u, v, weight in edges:
adj[u].append... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nDevelop a function to calculate the shortest path in a directional weighted graph using Dijkstra's algorithm. Given a graph represented as an adjacency list and a starting node, your function should return the shortest distances from the starting node to all other... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5966,
"level": 1,
"question": "### Problem Statement\nDevelop a function to calculate the shortest path in a directional weighted graph using Dijkstra's algorithm. Given a graph represented as an adjacency list and a starting node, your function should return the shortest distances ... |
def max_sequence(arr):
if not arr:
return 0
current_max = 0
max_so_far = 0
for num in arr:
current_max = max(current_max + num, 0)
max_so_far = max(max_so_far, current_max)
return max_so_far
| simplelr_Taco | [
{
"content": "Question:\nWrite a function called `max_sequence` that takes a list of integers `arr` as input and returns the sum of the maximum sum subarray. A subarray is a contiguous portion of the array. If the array is empty, the function should return 0.\n\nFor example:\n\n- `max_sequence([−2,1,−3,4,−1,2,1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5967,
"level": 1,
"question": "Write a function called `max_sequence` that takes a list of integers `arr` as input and returns the sum of the maximum sum subarray. A subarray is a contiguous portion of the array. If the array is empty, the function should return 0.\n\nFor example:\n... |
import seaborn.objects as so
import matplotlib.pyplot as plt
def plot_temps(data):
days = data['days']
temps = data['temperatures']
p = so.Plot(x=days, y=temps).add(so.Line(marker="o"))
p = p.theme({"axes.xmargin": 0.1, "axes.ymargin": 0.1})
p = p.limit(x=(0, 8), y=(-5, 40))
p = p.limit(y=... | simplelr_Docs | [
{
"content": "Question:\nYou are provided with a dataset of temperatures recorded over a week. Your task is to use seaborn to create a line plot of these temperatures, with specific customizations using the seaborn objects (`so.Plot`) module.\n\n#### Task:\n\n1. **Plot the data**: Create a line plot of temperat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5968,
"level": 1,
"question": "You are provided with a dataset of temperatures recorded over a week. Your task is to use seaborn to create a line plot of these temperatures, with specific customizations using the seaborn objects (`so.Plot`) module.\n\n#### Task:\n\n1. **Plot the dat... |
def remove_duplicates(s: str) -> str:
seen = set()
result = []
for char in s:
if char not in seen:
seen.add(char)
result.append(char)
return ''.join(result) | simplelr_Codeforces | [
{
"content": "Question:\nMaria is organizing a string collection. She discovered that some strings in her collection contain repeating characters, and she wants to remove the duplicates in such a way that only the first occurrence of each character is retained, preserving the original order of characters.\n\nWr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5969,
"level": 1,
"question": "Maria is organizing a string collection. She discovered that some strings in her collection contain repeating characters, and she wants to remove the duplicates in such a way that only the first occurrence of each character is retained, preserving the ... |
def binary_search(array, target):
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == target:
return mid
elif array[mid] > target:
high = mid - 1
else:
low = mid + 1
return -1 | simplelr_Data_Structure | [
{
"content": "Question:\n**Context**: You have been hired to work on a search engine where efficient lookups in large datasets are crucial. One component of the search engine is a sorted list of keywords, and you need to implement a feature to quickly determine the position of a given keyword in this list.\n\n*... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5970,
"level": 1,
"question": "**Context**: You have been hired to work on a search engine where efficient lookups in large datasets are crucial. One component of the search engine is a sorted list of keywords, and you need to implement a feature to quickly determine the position of... |
import pandas as pd
import numpy as np
def task_func(json_file_path):
# Read the JSON file into a DataFrame
df = pd.read_json(json_file_path)
# Initialize the summary dictionary
summary = {}
for column in df.columns:
# Count the number of missing values in the current column
... | simplelr_Package | [
{
"content": "Question:\nWrite a function that reads a JSON file into a pandas DataFrame and fills any missing or NaN values in non-numeric columns with the string 'missing'. Additionally, for numeric columns, replace the missing values with the median of their respective columns. Return the processed DataFrame... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5971,
"level": 1,
"question": "Write a function that reads a JSON file into a pandas DataFrame and fills any missing or NaN values in non-numeric columns with the string 'missing'. Additionally, for numeric columns, replace the missing values with the median of their respective colu... |
from typing import List
def sort_colors(nums: List[int]) -> None:
low = 0
high = len(nums) - 1
mid = 0
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are given an array containing arbitrary order of colors represented by integers: red (0), white (1), and blue (2). You need to sort the array such that all instances of the same color are adjacent and the colors are in the order red, white and blue. Use an in-place sor... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5972,
"level": 1,
"question": "### Scenario\nYou are given an array containing arbitrary order of colors represented by integers: red (0), white (1), and blue (2). You need to sort the array such that all instances of the same color are adjacent and the colors are in the order red, ... |
def delete_reoccurring_characters(s: str) -> str:
seen = set()
result = []
for char in s:
if char not in seen:
result.append(char)
seen.add(char)
return ''.join(result) | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase alphabets. Your task is to write a function `delete_reoccurring_characters` that removes any recurring character (subsequent occurrences of characters already seen) from the string and returns the resultant string with the first occurre... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5973,
"level": 1,
"question": "You are given a string `s` consisting of lowercase alphabets. Your task is to write a function `delete_reoccurring_characters` that removes any recurring character (subsequent occurrences of characters already seen) from the string and returns the resu... |
def get_value(dictionary, key):
return dictionary.get(key) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a dictionary and a key as arguments, and returns the value associated with the key if the key exists in the dictionary. If the key does not exist, the function should return `None`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5974,
"level": 1,
"question": "Create a Python function that takes a dictionary and a key as arguments, and returns the value associated with the key if the key exists in the dictionary. If the key does not exist, the function should return `None`.",
"split": "train"
} |
def increment_index(dict_list, key, value):
for index, dictionary in enumerate(dict_list):
if dictionary.get(key) == value:
return index + 1
return -1 | simplelr_Filter | [
{
"content": "Question:\nYou have been tasked with writing a function `increment_index` that increments the index of a given key in a list of dictionaries. The function takes in a list of dictionaries, a key, and a value to search for in the list of dictionaries. It returns the incremented index of the key if t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5975,
"level": 1,
"question": "You have been tasked with writing a function `increment_index` that increments the index of a given key in a list of dictionaries. The function takes in a list of dictionaries, a key, and a value to search for in the list of dictionaries. It returns th... |
def is_valid_password(password):
if len(password) < 8:
return False
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
return has_upper and has_lower and has_digit | simplelr_Package | [
{
"content": "Question:\nYou need to write a Python function that identifies whether a string is a valid password. A valid password must satisfy the following conditions:\n\n1. It must be at least 8 characters long.\n2. It must contain at least one uppercase letter.\n3. It must contain at least one lowercase le... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5976,
"level": 1,
"question": "You need to write a Python function that identifies whether a string is a valid password. A valid password must satisfy the following conditions:\n\n1. It must be at least 8 characters long.\n2. It must contain at least one uppercase letter.\n3. It mus... |
def bubble_sort(arr):
n = len(arr)
swap = True
# Continue making passes until no swaps are needed
while swap:
swap = False # Reset swap flag for this pass
# Iterate through each element up to the second last
for i in range(n - 1):
if arr[i] > arr[i + 1]:
... | simplelr_Filter | [
{
"content": "Question:\n### Programming Foundation: Basic Algorithm\n\n# Question 1: Bubble Sort\nConsider a simple bubble sort algorithm for an array of integers. The algorithm compares each pair of adjacent integers in the array and swaps them if they are in the wrong order. This process is repeated until no... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5977,
"level": 1,
"question": "### Programming Foundation: Basic Algorithm\n\n# Question 1: Bubble Sort\nConsider a simple bubble sort algorithm for an array of integers. The algorithm compares each pair of adjacent integers in the array and swaps them if they are in the wrong order... |
def modular_exponentiation(base, exponent, modulus):
if modulus == 1:
return 0
result = 1
base = base % modulus
while exponent > 0:
if exponent % 2 == 1:
result = (result * base) % modulus
exponent = exponent >> 1 # Equivalent to dividing exponent by 2
base =... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the modular exponentiation of a number in a given modulo.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5978,
"level": 1,
"question": "Write a python function to calculate the modular exponentiation of a number in a given modulo.",
"split": "train"
} |
def max_subarray(arr):
if not arr:
return 0
max_current = max_global = arr[0]
for num in arr[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global | simplelr_Filter | [
{
"content": "Question:\nHello Qwen, I have a Python test in my next class and I need help with a specific problem. The problem is about finding the maximum sum of a contiguous subarray within a one-dimensional array of numbers. This is known as the maximum subarray problem. Can you explain how to solve this pr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5979,
"level": 1,
"question": "Hello Qwen, I have a Python test in my next class and I need help with a specific problem. The problem is about finding the maximum sum of a contiguous subarray within a one-dimensional array of numbers. This is known as the maximum subarray problem. C... |
from collections import deque
def find_path(maze):
m = len(maze)
if m == 0:
return -1
n = len(maze[0])
# Handle 1x1 case
if m == 1 and n == 1:
return 0 if maze[0][0] == 1 else -1
# Check if start or end is non-passable
if maze[0][0] != 1 or maze[m-1][n-1] != 1:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Shortest Path in Binary Maze\n\nGiven a binary maze represented as a 2D list, write a function `find_path` that finds the shortest path length from the top-left corner to the bottom-right corner. You can only move to adjacent cells (up, down, left, right) if they contain the value 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5980,
"level": 1,
"question": "### Shortest Path in Binary Maze\n\nGiven a binary maze represented as a 2D list, write a function `find_path` that finds the shortest path length from the top-left corner to the bottom-right corner. You can only move to adjacent cells (up, down, left,... |
def sum_of_primes(n):
if n <= 2:
return 0
sieve = [True] * n
sieve[0] = sieve[1] = False
for current in range(2, int(n ** 0.5) + 1):
if sieve[current]:
for multiple in range(current * current, n, current):
sieve[multiple] = False
total = 0
for num in r... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a number as an input and returns the sum of all prime numbers less than that number. I need a solution in Python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5981,
"level": 1,
"question": "Create a function that takes a number as an input and returns the sum of all prime numbers less than that number. I need a solution in Python.",
"split": "train"
} |
import math
def is_prime(n):
if type(n) is bool or not isinstance(n, int) or n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = math.sqrt(n)
for i in range(3, int(sqrt_n) + 1, 2):
if n % i == 0:
return False
return True | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to check if a given number is a prime number or not. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5982,
"level": 1,
"question": "Write a python function to check if a given number is a prime number or not. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.",
"split": "train"
} |
def triangle_type(a, b, c):
if a == b == c:
return "Equilateral"
elif a == b or b == c or a == c:
return "Isosceles"
else:
return "Scalene" | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that identifies the type of a triangle based on its side lengths and returns the type as a string. The function should accept three integers as arguments, each representing the length of a side of the triangle. The types of triangles are: Equilateral (all sides are equ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5983,
"level": 1,
"question": "Create a function that identifies the type of a triangle based on its side lengths and returns the type as a string. The function should accept three integers as arguments, each representing the length of a side of the triangle. The types of triangles ... |
def swap_numbers(a, b):
return b, a | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to swap the values of two integers without using temporary variables or arithmetic operations.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5984,
"level": 1,
"question": "Write a function to swap the values of two integers without using temporary variables or arithmetic operations.",
"split": "train"
} |
def duplicate_counter(lst):
counts = {}
for element in lst:
counts[element] = counts.get(element, 0) + 1
return counts | simplelr_Apps | [
{
"content": "Question:\nImplement a function `duplicate_counter(lst)` that takes a list `lst` as its input and returns a dictionary with each element in the list as the key and the number of times that element appears in the list as the value.\n\nExample:\n```\nFor lst = [a, b, b, c, a, c, c, a], the function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5985,
"level": 1,
"question": "Implement a function `duplicate_counter(lst)` that takes a list `lst` as its input and returns a dictionary with each element in the list as the key and the number of times that element appears in the list as the value.\n\nExample:\n```\nFor lst = [a, ... |
def trailing_zeros(n):
count = 0
i = 5
while n // i >= 1:
count += n // i
i *= 5
return count
| simplelr_Taco | [
{
"content": "Question:\nImplement a function that receives an integer n (1 <= n <= 5000) and returns the number of trailing zeros in the factorial of n.\n\nTrailing zeros are created by pairs of factors 2 and 5 in prime factors of the number, and because in factorials there are always more factors of 2 than fa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5986,
"level": 1,
"question": "Implement a function that receives an integer n (1 <= n <= 5000) and returns the number of trailing zeros in the factorial of n.\n\nTrailing zeros are created by pairs of factors 2 and 5 in prime factors of the number, and because in factorials there a... |
import string
def is_pangram(sentence):
"""
Checks if a sentence is a pangram.
Args:
sentence: The sentence to check.
Returns:
True if the sentence is a pangram, False otherwise.
"""
sentence = sentence.lower()
letters = set()
for char in sentence:
if char.isal... | simplelr_Filter | [
{
"content": "Question:\nThis is a sentence:\n\nThe quick brown fox jumps over the lazy dog.\n\nThis sentence is a pangram because it uses every letter of the alphabet at least once.\n\nCorrect. 👍\n\n\nHere are some other pangrams:\n\n* Pack my box with five dozen liquor jugs.\n* The five boxing wizards jump q... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5987,
"level": 1,
"question": "This is a sentence:\n\nThe quick brown fox jumps over the lazy dog.\n\nThis sentence is a pangram because it uses every letter of the alphabet at least once.\n\nCorrect. 👍\n\n\nHere are some other pangrams:\n\n* Pack my box with five dozen liquor jugs... |
def decode_ways(s: str) -> int:
n = len(s)
if n == 0:
return 0
dp = [0] * (n + 1)
dp[0] = 1 # Base case: empty string has one way to decode
for i in range(1, n + 1):
# Check single digit
if s[i-1] != '0':
dp[i] += dp[i-1]
# Check two digits
i... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are tasked with finding all the possible ways to decode a given string representing encoded alphabetical letters, where 'A' to 'Z' are represented by '1' to '26' respectively. Each digit or two-digit combination in the string can map to a letter.\n\nImplemen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5988,
"level": 1,
"question": "### Problem Statement\n\nYou are tasked with finding all the possible ways to decode a given string representing encoded alphabetical letters, where 'A' to 'Z' are represented by '1' to '26' respectively. Each digit or two-digit combination in the stri... |
def get_prime_factors(n):
factors = []
divisor = 2
while divisor < n:
if n % divisor == 0:
factors.append(divisor)
n = n // divisor
else:
divisor += 1
if n > 1:
factors.append(n)
return factors | simplelr_Filter | [
{
"content": "Question:\nI am trying to create a function that will return all prime factors of a given number. I want to create it using a simple loop, without using any built-in functions for getting prime factors. \n\nHere's my attempt:\n\n```python\ndef get_prime_factors(n):\n factors = []\n divisor =... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5989,
"level": 1,
"question": "I am trying to create a function that will return all prime factors of a given number. I want to create it using a simple loop, without using any built-in functions for getting prime factors. \n\nHere's my attempt:\n\n```python\ndef get_prime_factors(n... |
def increment_by_index(arr):
return [val + idx for idx, val in enumerate(arr)] | simplelr_Apps | [
{
"content": "Question:\nCreate a function that takes an integer array and returns a new array with each element incremented by the value of its index. \n\nThe input array will contain at least one element and all elements will be non-negative integers.\n\nFor an input array: [2, 4, 6, 8] \nthe function should ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5990,
"level": 1,
"question": "Create a function that takes an integer array and returns a new array with each element incremented by the value of its index. \n\nThe input array will contain at least one element and all elements will be non-negative integers.\n\nFor an input array: ... |
import re
def is_valid_email(email):
email_regex = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
return bool(re.fullmatch(email_regex, email.strip()))
# Example usage:
# print(is_valid_email("test@example.com")) # Returns: True
# print(is_valid_email("invalid-email")) # Returns: False | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code snippet that checks if a string is a valid email address?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5991,
"level": 1,
"question": "Can you provide a Python code snippet that checks if a string is a valid email address?",
"split": "train"
} |
from typing import List
def longest_unique_subsequence(arr: List[int]) -> int:
if not arr:
return 0
last_seen = {}
max_length = 0
start = 0
for end in range(len(arr)):
current = arr[end]
if current in last_seen and last_seen[current] >= start:
start = l... | simplelr_Algorithm | [
{
"content": "Question:\n### Task\n\nWrite a function that determines the length of the longest contiguous subsequence of unique integers in an unsorted array. The subsequence must be contiguous in the array but the elements themselves must all be distinct.\n\n### Input and Output\n\n* **Function Signature**:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5992,
"level": 1,
"question": "### Task\n\nWrite a function that determines the length of the longest contiguous subsequence of unique integers in an unsorted array. The subsequence must be contiguous in the array but the elements themselves must all be distinct.\n\n### Input and Ou... |
def reverse_string(input_str: str) -> str:
"""
Returns the input string reversed.
Args:
input_str (str): The string to be reversed.
Returns:
str: The reversed string.
"""
return input_str[::-1] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code snippet to create a function that takes a string as input and returns the string reversed. For example, if the input is \"hello\", the output should be \"olleh\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5993,
"level": 1,
"question": "Write a Python code snippet to create a function that takes a string as input and returns the string reversed. For example, if the input is \"hello\", the output should be \"olleh\".",
"split": "train"
} |
def reverse_string(s):
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse a string. The function should be able to handle both strings with spaces and special characters. For example, if the input string is \"hello world!\", the output should be \"!dlrow olleh\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5994,
"level": 1,
"question": "Write a python function to reverse a string. The function should be able to handle both strings with spaces and special characters. For example, if the input string is \"hello world!\", the output should be \"!dlrow olleh\".",
"split": "train"
} |
import numpy as np
def max_profit(filename='stockPrices.npz'):
# Read the data from the specified file
data = np.load(filename)
prices = data['prices']
# Check if the prices array is valid (not necessary as per the problem's assumption)
if len(prices) < 2:
return 0
max_profit_... | simplelr_Package | [
{
"content": "Question:\nYou are given a set of data representing the stock prices of various companies over a period of time. Your task is to write a function to determine the maximum profit that could have been made by buying and then later selling the stock on a single day. Assume you can hold only one share... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5995,
"level": 1,
"question": "You are given a set of data representing the stock prices of various companies over a period of time. Your task is to write a function to determine the maximum profit that could have been made by buying and then later selling the stock on a single day.... |
def binary_search(sorted_list, target):
left = 0
right = len(sorted_list) - 1
while left <= right:
mid = (left + right) // 2
if sorted_list[mid] == target:
return mid
elif sorted_list[mid] < target:
left = mid + 1
else:
right = mid - 1
... | simplelr_Filter | [
{
"content": "Question:\nGenerate a code snippet in Python to implement a simple binary search on a sorted list of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5996,
"level": 1,
"question": "Generate a code snippet in Python to implement a simple binary search on a sorted list of integers.",
"split": "train"
} |
def find_maximum(numbers):
if not numbers:
return None
max_value = numbers[0]
for number in numbers[1:]:
if number > max_value:
max_value = number
return max_value | simplelr_Filter | [
{
"content": "Question:\nI want to create a function in Python that takes a list of numbers and returns the maximum value. But I want to implement it without using the built-in `max()` function. How can I do that?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5997,
"level": 1,
"question": "I want to create a function in Python that takes a list of numbers and returns the maximum value. But I want to implement it without using the built-in `max()` function. How can I do that?",
"split": "train"
} |
def fibonacci_sequence(n):
if n <= 0:
return []
fib_sequence = []
if n >= 1:
fib_sequence.append(0)
if n >= 2:
fib_sequence.append(1)
for i in range(2, n):
next_term = fib_sequence[i-1] + fib_sequence[i-2]
fib_sequence.append(next_term)
return fib_sequence | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the Fibonacci sequence up to a given number of terms, n. The function should return the Fibonacci sequence as a list, where the first two numbers are always 0 and 1, respectively.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5998,
"level": 1,
"question": "Write a python function to calculate the Fibonacci sequence up to a given number of terms, n. The function should return the Fibonacci sequence as a list, where the first two numbers are always 0 and 1, respectively.",
"split": "train"
} |
def count_digits(n: int) -> int:
if n == 0:
return 1
n = abs(n)
count = 0
while n > 0:
n = n // 10
count += 1
return count | simplelr_Data_Structure | [
{
"content": "Question:\nCounting the Number of Digits\n\n#### Context:\nYou are working on a project that requires frequent validation of input numbers based on the number of digits they have. A function is required to determine the number of digits in any integer. This will be a utility function that can then... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5999,
"level": 1,
"question": "Counting the Number of Digits\n\n#### Context:\nYou are working on a project that requires frequent validation of input numbers based on the number of digits they have. A function is required to determine the number of digits in any integer. This will ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.