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 rotate_matrix_90_clockwise(matrix: list[list[int]]) -> None:
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse() | simplelr_Algorithm | [
{
"content": "Question:\n### Matrix Rotation\n\n#### Objective\nYour task is to implement a function that rotates an NxN matrix by 90 degrees clockwise. The function should perform the rotation in place, modifying the input matrix directly without using additional matrices.\n\n#### Input\nThe function will take... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 100,
"level": 1,
"question": "### Matrix Rotation\n\n#### Objective\nYour task is to implement a function that rotates an NxN matrix by 90 degrees clockwise. The function should perform the rotation in place, modifying the input matrix directly without using additional matrices.\n\n... |
def list_to_dict(lst):
return {item: len(item) for item in lst}
# Example usage
fruit_list = ["apple", "banana", "cherry"]
result = list_to_dict(fruit_list)
print(result) # Output: {'apple': 5, 'banana': 6, 'cherry': 6} | simplelr_Filter | [
{
"content": "Question:\nWrite a program in Python that converts a list of strings into a dictionary, where each string in the list is a key, and the value is the length of that string. For example, the list `[\"apple\", \"banana\", \"cherry\"]` should be converted to `{\"apple\": 5, \"banana\": 6, \"cherry\": ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 101,
"level": 1,
"question": "Write a program in Python that converts a list of strings into a dictionary, where each string in the list is a key, and the value is the length of that string. For example, the list `[\"apple\", \"banana\", \"cherry\"]` should be converted to `{\"apple... |
def strings_to_length_dict(string_list):
# First pass: Check each string for numbers
for s in string_list:
if s and any(c.isdigit() for c in s):
raise ValueError("Numbers are not allowed in the strings")
# Second pass: Create the dictionary
return {s: 0 if not s else len(s) for ... | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function that takes a list of strings as input and returns a dictionary where each string in the list is a key, and the corresponding value is the length of the string. However, if a string contains numbers, the function should raise a `ValueError` indicating that number... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 102,
"level": 1,
"question": "Design a Python function that takes a list of strings as input and returns a dictionary where each string in the list is a key, and the corresponding value is the length of the string. However, if a string contains numbers, the function should raise a `... |
def sparseMatrixMultiply(A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
# Preprocess matrix B to store non-zero elements for each row
len_B_rows = len(B)
if len_B_rows == 0:
return []
cols_B = len(B[0])
B_rows = [[] for _ in range... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given two sparse matrices A and B. Write a function `sparseMatrixMultiply(A, B)` that multiplies these two matrices, assuming that the column number of A is equal to the row number of B. The function should return the resultant matrix C.\n\n### Input\n- `A`: A list of lists wher... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 103,
"level": 1,
"question": "You are given two sparse matrices A and B. Write a function `sparseMatrixMultiply(A, B)` that multiplies these two matrices, assuming that the column number of A is equal to the row number of B. The function should return the resultant matrix C.\n\n### ... |
def product_except_self(nums):
n = len(nums)
if n == 0:
return []
left_products = [1] * n
for i in range(1, n):
left_products[i] = left_products[i-1] * nums[i-1]
right_products = [1] * n
for i in range(n-2, -1, -1):
right_products[i] = right_products[i+1] * nums... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes an integer array as input and returns the product of all the elements in the array except the element at the current index, without using division.\n\nSAMPLE INPUT\n[1, 2, 3, 4]\n\nSAMPLE OUTPUT\n[24, 12, 8, 6]\n\nExplanation\n\nFor the input array [1, 2, 3, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 104,
"level": 1,
"question": "Write a function that takes an integer array as input and returns the product of all the elements in the array except the element at the current index, without using division.\n\nSAMPLE INPUT\n[1, 2, 3, 4]\n\nSAMPLE OUTPUT\n[24, 12, 8, 6]\n\nExplanation... |
def extract_names(personal_data, min_age, city):
result = []
for person in personal_data:
if person[1] > min_age and person[2] == city:
result.append(person[0])
return result | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function to extract specific names from a list of tuples containing personal data. The function should return a list of names where the age is greater than a given threshold and the city is a specific name. The tuple structure is as follows: `(name, age, city)`.\nAnswer:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 105,
"level": 1,
"question": "Design a Python function to extract specific names from a list of tuples containing personal data. The function should return a list of names where the age is greater than a given threshold and the city is a specific name. The tuple structure is as foll... |
def reverse_string(s):
"""Reverses the input string, handling Unicode characters and line breaks properly."""
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse a string in Python. The function should take a single string as input and return the reversed string. Additionally, ensure that your function handles Unicode characters and line breaks properly.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 106,
"level": 1,
"question": "Write a function to reverse a string in Python. The function should take a single string as input and return the reversed string. Additionally, ensure that your function handles Unicode characters and line breaks properly.",
"split": "train"
} |
def bubble_sort(lst):
lst = lst[:]
n = len(lst)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
swapped = True
if not swapped:
break
return lst | simplelr_Filter | [
{
"content": "Question:\nCreate a function in Python that takes an unsorted list of integers and sorts it using the bubble sort technique.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 107,
"level": 1,
"question": "Create a function in Python that takes an unsorted list of integers and sorts it using the bubble sort technique.",
"split": "train"
} |
def longest_contiguous_subarray(numbers):
if not numbers:
return (0, None)
max_length = 1
max_value = numbers[0]
current_length = 1
current_value = numbers[0]
for num in numbers[1:]:
if num == current_value:
current_length += 1
else:
if c... | simplelr_Evol | [
{
"content": "Question:\nGiven a list of integers, write a function that returns the length of the longest contiguous subarray where all elements have the same value. The function should also return the value of the elements in this subarray. Consider the output to be a tuple where the first element is the leng... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 108,
"level": 1,
"question": "Given a list of integers, write a function that returns the length of the longest contiguous subarray where all elements have the same value. The function should also return the value of the elements in this subarray. Consider the output to be a tuple w... |
from collections import deque
def wordLadderLength(beginWord, endWord, wordList):
word_set = set(wordList)
if beginWord == endWord:
return 1
if endWord not in word_set:
return 0
queue = deque()
queue.append((beginWord, 1))
visited = set()
visited.add(beginWord)
... | simplelr_Taco | [
{
"content": "Question:\nImplement a function `wordLadderLength(beginWord, endWord, wordList)` that takes in three parameters: a `beginWord` representing the starting word, an `endWord` representing the ending word, and a `wordList` containing a list of available words. Your task is to determine the length of t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 109,
"level": 1,
"question": "Implement a function `wordLadderLength(beginWord, endWord, wordList)` that takes in three parameters: a `beginWord` representing the starting word, an `endWord` representing the ending word, and a `wordList` containing a list of available words. Your ta... |
def process_input(lst):
result = []
for x in lst:
if -50 <= x <= -1:
result.append(100 - x)
elif x == 0:
result.append("ZERO")
elif 1 <= x <= 50:
result.append(x * 2)
else:
result.append(x)
return result | simplelr_Code_Contests | [
{
"content": "Question:\nCreate a function `process_input` that takes a list of integers as input and processes each integer according to specific rules. \n\nFor each integer `x`:\n1. If `x` is between -50 and -1, inclusive, subtract the integer from 100.\n2. If `x` is 0, replace it with the string \"ZERO\".\n3... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 110,
"level": 1,
"question": "Create a function `process_input` that takes a list of integers as input and processes each integer according to specific rules. \n\nFor each integer `x`:\n1. If `x` is between -50 and -1, inclusive, subtract the integer from 100.\n2. If `x` is 0, repla... |
from typing import List
def pigeonhole_sort(arr: List[int]) -> List[int]:
if not arr:
return []
max_value = 100 # Since life expectancies are in [1, 100]
pigeonhole = [0] * (max_value + 1) # Indexes 0 to 100
# Count the frequency of each number
for num in arr:
pigeonhole[num... | simplelr_Data_Structure | [
{
"content": "Question:\n### Sorting Life Expectancy Data\n\nIn a scientific study, you are given a dataset containing the life expectancies of various species of animals. You are required to sort this list to analyze patterns related to lifespan. Given the constraints of the study, you know that the life expec... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 111,
"level": 1,
"question": "### Sorting Life Expectancy Data\n\nIn a scientific study, you are given a dataset containing the life expectancies of various species of animals. You are required to sort this list to analyze patterns related to lifespan. Given the constraints of the s... |
import os
def manipulate_env(action, key, value=None):
if action in ["add", "modify"]:
os.environ[key] = value
elif action == "delete":
if key in os.environ:
del os.environ[key]
elif action == "get":
return os.environ.get(key, None)
return None
| simplelr_Docs | [
{
"content": "Question:\n### Environment Variable Manipulation Challenge\n\n#### Problem Statement:\n\nYou are required to write a Python function that manipulates environment variables. The function should support adding, modifying, and deleting environment variables. Specifically, you need to implement a func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 112,
"level": 1,
"question": "### Environment Variable Manipulation Challenge\n\n#### Problem Statement:\n\nYou are required to write a Python function that manipulates environment variables. The function should support adding, modifying, and deleting environment variables. Specific... |
def left_rotate_array(arr: list, k: int) -> list:
n = len(arr)
if n == 0:
return []
k_eff = k % n
if k_eff == 0:
return list(arr)
return arr[k_eff:] + arr[:k_eff] | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are asked to create a function that performs a left rotation on an array. This is a common algorithmic task used to test proficiency in array manipulation and understanding of algorithmic time complexities.\n\n### Array Left Rotation\n\n### Objective:\nImpleme... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 113,
"level": 1,
"question": "### Problem Statement\nYou are asked to create a function that performs a left rotation on an array. This is a common algorithmic task used to test proficiency in array manipulation and understanding of algorithmic time complexities.\n\n### Array Left R... |
from collections import deque
def find_minimum_window_sum(arr: list[int], target: int) -> int:
n = len(arr)
# Compute the prefix sum array
prefix_sum = [0] * (n + 1)
for i in range(n):
prefix_sum[i+1] = prefix_sum[i] + arr[i]
min_length = float('inf')
dq = deque()
for j in... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\nGiven an array of integers, implement a function `find_minimum_window_sum(arr: List[int], target: int) -> int` to find the length of the smallest contiguous subarray whose sum is greater than or equal to the given target value. If there is no such subar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 114,
"level": 1,
"question": "### Coding Assessment Question\n\nGiven an array of integers, implement a function `find_minimum_window_sum(arr: List[int], target: int) -> int` to find the length of the smallest contiguous subarray whose sum is greater than or equal to the given targe... |
import tokenize
import token
import ast
from io import BytesIO
def transform_integers_to_hex(file_path: str) -> str:
with open(file_path, 'r', encoding='utf-8') as f:
source_code = f.read()
tokens = list(tokenize.tokenize(BytesIO(source_code.encode('utf-8')).readline))
processed_tokens = []
... | simplelr_Docs | [
{
"content": "Question:\n### Python Coding Assessment\n\n#### Objective:\nDemonstrate your understanding of the `tokenize` module by writing a script that transforms all integer literals in a Python source file into hexadecimal format.\n\n#### Problem Statement:\n\nWrite a function `transform_integers_to_hex(fi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 115,
"level": 1,
"question": "### Python Coding Assessment\n\n#### Objective:\nDemonstrate your understanding of the `tokenize` module by writing a script that transforms all integer literals in a Python source file into hexadecimal format.\n\n#### Problem Statement:\n\nWrite a func... |
import heapq
def shortest_path(graph, start):
# Initialize distances to infinity for all nodes except the start node
distances = {node: float('infinity') for node in graph}
distances[start] = 0
# Priority queue: (distance, node)
heap = []
heapq.heappush(heap, (0, start))
while hea... | simplelr_Package | [
{
"content": "Question:\nIn this exercise, you will implement a function to calculate the shortest path in a weighted graph using Dijkstra's algorithm. This task will help you understand graph traversal techniques and how to efficiently determine the shortest distances between nodes in a graph.\n\nYou are requi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 116,
"level": 1,
"question": "In this exercise, you will implement a function to calculate the shortest path in a weighted graph using Dijkstra's algorithm. This task will help you understand graph traversal techniques and how to efficiently determine the shortest distances between ... |
def get_kth_smallest(N, arr, k):
sorted_arr = sorted(arr)
return sorted_arr[k-1]
| simplelr_Taco | [
{
"content": "Question:\nGiven an integer array `arr` of length `N` and an integer `k`, write a function that returns the k-th smallest element in the array after sorting it in ascending order.\n\nConstraints:\n\n- 1 ≤ N ≤ 10^5\n- 1 ≤ arr[i] ≤ 10^9\n- 1 ≤ k ≤ N\n\nYour function should be efficient to handle the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 117,
"level": 1,
"question": "Given an integer array `arr` of length `N` and an integer `k`, write a function that returns the k-th smallest element in the array after sorting it in ascending order.\n\nConstraints:\n\n- 1 ≤ N ≤ 10^5\n- 1 ≤ arr[i] ≤ 10^9\n- 1 ≤ k ≤ N\n\nYour function... |
def isSorted(arr):
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, determine whether the list is sorted in non-decreasing order.\n\nExample 1:\nInput: arr = [1, 2, 2, 3, 4, 5]\nOutput: True\nExplanation: The list is sorted in non-decreasing order.\n\nExample 2:\nInput: arr = [5, 4, 3, 2, 1]\nOutput: False\nExplanation: The lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 118,
"level": 1,
"question": "Given a list of integers, determine whether the list is sorted in non-decreasing order.\n\nExample 1:\nInput: arr = [1, 2, 2, 3, 4, 5]\nOutput: True\nExplanation: The list is sorted in non-decreasing order.\n\nExample 2:\nInput: arr = [5, 4, 3, 2, 1]\nO... |
from collections import defaultdict
def groupBy(l, key):
ans = defaultdict(list)
for elem in l:
ans[key(elem)].append(elem)
return dict(ans) | simplelr_Filter | [
{
"content": "Question:\nI've been trying to implement a groupBy operation in Python. I have the following code:\n\n```python\ndef groupBy(l, key):\n ans = {}\n for elem in l:\n if key(elem) in ans:\n ans[key(elem)].append(elem)\n else:\n ans[key(elem)] = [elem]\n re... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 119,
"level": 1,
"question": "I've been trying to implement a groupBy operation in Python. I have the following code:\n\n```python\ndef groupBy(l, key):\n ans = {}\n for elem in l:\n if key(elem) in ans:\n ans[key(elem)].append(elem)\n else:\n ... |
def length_of_longest_substring(word):
if not word:
return 0
char_map = {}
left = 0
max_len = 0
for right in range(len(word)):
char = word[right]
# If the character is already in the map and within the current window, update left
if char in char_map and char_map[char]... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `word`. You need to find the longest substring of `word` such that all characters in the substring are unique. Return the length of this longest substring. In the case where `word` is empty, return `0`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 120,
"level": 1,
"question": "You are given a string `word`. You need to find the longest substring of `word` such that all characters in the substring are unique. Return the length of this longest substring. In the case where `word` is empty, return `0`.",
"split": "train"
} |
def find_words_from_scramble(s, d):
# Preprocess the dictionary d into a structure mapping length to sorted characters to words
preprocessed = {}
for word in d:
word_len = len(word)
sorted_str = ''.join(sorted(word))
if word_len not in preprocessed:
preprocessed[word_len]... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a scrambled string `s` and a dictionary `d` of words. The function should return all possible words from the dictionary that can be formed by reordering the characters in the string `s`. Ensure the solution efficiently handles cases with large dictionaries an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 121,
"level": 1,
"question": "Write a function that takes a scrambled string `s` and a dictionary `d` of words. The function should return all possible words from the dictionary that can be formed by reordering the characters in the string `s`. Ensure the solution efficiently handle... |
def find_visible_buildings(heights):
n = len(heights)
if n == 0:
return []
visible = [False] * n
max_so_far = float('-inf')
for i in range(n-1, -1, -1):
if heights[i] > max_so_far:
visible[i] = True
max_so_far = heights[i]
else:
visible[i] ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a 0-indexed array `heights` representing the heights of buildings in a cityscape. A building is **visible** if there are no taller buildings to its right. Return _an array of booleans where each index `i` represents whether the building at index `i` is visible_.\nAnswer:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 122,
"level": 1,
"question": "You are given a 0-indexed array `heights` representing the heights of buildings in a cityscape. A building is **visible** if there are no taller buildings to its right. Return _an array of booleans where each index `i` represents whether the building at... |
def min_sessions(tasks, sessionTime):
sum_total = sum(tasks)
sum_sessions = (sum_total + sessionTime - 1) // sessionTime
count = sum(1 for t in tasks if t > sessionTime / 2)
return max(sum_sessions, count) | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of positive integers representing the durations of different tasks, and a positive integer `sessionTime`, partition the tasks into the minimum number of sessions such that the sum of task durations in each session is less than or equal to `sessionTime`. Each task must be ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 123,
"level": 1,
"question": "Given an array of positive integers representing the durations of different tasks, and a positive integer `sessionTime`, partition the tasks into the minimum number of sessions such that the sum of task durations in each session is less than or equal to... |
import csv
from datetime import datetime
def get_days_of_week_from_csv(csv_path):
weekdays = []
with open(csv_path, 'r') as file:
reader = csv.reader(file)
for row in reader:
date_str = row[0].strip()
date_obj = datetime.strptime(date_str, '%Y-%m-%d')
weekday... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that reads a CSV file containing a single column of dates in the format 'YYYY-MM-DD' and returns the day of the week for each date. The function should take the file path as an argument and return a list of strings representing the day of the week for each date i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 124,
"level": 1,
"question": "Write a Python function that reads a CSV file containing a single column of dates in the format 'YYYY-MM-DD' and returns the day of the week for each date. The function should take the file path as an argument and return a list of strings representing t... |
from typing import List
def find_student_by_mark(marks: List[int], target_mark: int) -> int:
for index, mark in enumerate(marks):
if mark == target_mark:
return index
return -1 | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\nYou are given a list of integers representing students' marks in an exam. Your task is to find the first occurrence of a student who has scored a specific mark.\n\n#### Function Signature\n```python\ndef find_student_by_mark(marks: List[int], target_mark: int) -> int\n```\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 125,
"level": 1,
"question": "### Question\nYou are given a list of integers representing students' marks in an exam. Your task is to find the first occurrence of a student who has scored a specific mark.\n\n#### Function Signature\n```python\ndef find_student_by_mark(marks: List[in... |
def frequency_count(s):
freq_dict = {}
for char in s:
if not char.isalnum():
continue
lower_char = char.lower()
if lower_char in freq_dict:
freq_dict[lower_char] += 1
else:
freq_dict[lower_char] = 1
return freq_dict | simplelr_Apps | [
{
"content": "Question:\n## Task:\nWrite a function **frequency_count** that takes a string as input and returns a dictionary with the frequency of each character in the string.\n\n### Rules/Note:\n* Ignore spaces and count only alphanumeric characters (a-z, A-Z, 0-9).\n* This function should be case-insensitiv... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 126,
"level": 1,
"question": "## Task:\nWrite a function **frequency_count** that takes a string as input and returns a dictionary with the frequency of each character in the string.\n\n### Rules/Note:\n* Ignore spaces and count only alphanumeric characters (a-z, A-Z, 0-9).\n* This ... |
def is_power_of_two(n: int) -> bool:
if n <= 0:
return False
return (n & (n - 1)) == 0 | simplelr_Data_Structure | [
{
"content": "Question:\n## Scenario\nA software engineer is optimizing a video game engine that often needs to determine whether certain sizes (e.g., buffer sizes) are powers of two. Given the efficiency requirement, it is crucial to implement a function that determines whether a given integer is a power of tw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 127,
"level": 1,
"question": "## Scenario\nA software engineer is optimizing a video game engine that often needs to determine whether certain sizes (e.g., buffer sizes) are powers of two. Given the efficiency requirement, it is crucial to implement a function that determines whethe... |
def minMeetingRooms(intervals):
events = []
for s, e in intervals:
events.append((s, 1))
events.append((e, 0))
events.sort()
current_rooms = 0
max_rooms = 0
for event in events:
if event[1] == 1:
current_rooms += 1
if current_rooms > max_rooms:
... | simplelr_Apps | [
{
"content": "Question:\nA company has a series of meetings represented by a list of time intervals in the format [start, end]. Each meeting time is a pair of integers [si, ei] where `0 <= si < ei <= 24`. Write a function to determine the minimum number of conference rooms required for these meetings.\n\nExampl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 128,
"level": 1,
"question": "A company has a series of meetings represented by a list of time intervals in the format [start, end]. Each meeting time is a pair of integers [si, ei] where `0 <= si < ei <= 24`. Write a function to determine the minimum number of conference rooms requ... |
def wiggle_sort(nums: list[int]) -> None:
for i in range(1, len(nums)):
if i % 2 == 1:
if nums[i-1] >= nums[i]:
nums[i-1], nums[i] = nums[i], nums[i-1]
else:
if nums[i-1] <= nums[i]:
nums[i-1], nums[i] = nums[i], nums[i-1] | simplelr_Data_Structure | [
{
"content": "Question:\n### Wiggle Sort Challenge\n\nYou are given an unsorted integer array `nums`. Your task is to reorder the array such that `nums[0] < nums[1] > nums[2] < nums[3]`. This kind of ordering is known as a \"wiggle sort.\"\n\n### Function Signature\n```python\ndef wiggle_sort(nums: List[int]) -... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 129,
"level": 1,
"question": "### Wiggle Sort Challenge\n\nYou are given an unsorted integer array `nums`. Your task is to reorder the array such that `nums[0] < nums[1] > nums[2] < nums[3]`. This kind of ordering is known as a \"wiggle sort.\"\n\n### Function Signature\n```python\n... |
def reverse_string(s):
return s[::-1] | simplelr_Filter | [
{
"content": "Question:\nHello Qwen, I am preparing for a small coding competition and need to practice problems related to string manipulation and array operations. Can you suggest some beginner-level problems along with sample solutions in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 130,
"level": 1,
"question": "Hello Qwen, I am preparing for a small coding competition and need to practice problems related to string manipulation and array operations. Can you suggest some beginner-level problems along with sample solutions in Python?",
"split": "train"
} |
from typing import List
def is_magic_square(matrix: List[List[int]]) -> bool:
n = len(matrix)
if n == 1:
return True
magic_sum = sum(matrix[0])
# Check each row
for row in matrix:
if sum(row) != magic_sum:
return False
# Check each column
for j in range... | simplelr_Apps | [
{
"content": "Question:\n## Magic Square\n\nA magic square is a square matrix in which the sum of every row, column, and diagonal is the same. Write a function to check if a given matrix is a magic square.\n\n### Function Signature\n```python\ndef is_magic_square(matrix: List[List[int]]) -> bool:\n```\n\n### In... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 131,
"level": 1,
"question": "## Magic Square\n\nA magic square is a square matrix in which the sum of every row, column, and diagonal is the same. Write a function to check if a given matrix is a magic square.\n\n### Function Signature\n```python\ndef is_magic_square(matrix: List[L... |
import math
def polygon_area(n, R):
area = 0.5 * n * R ** 2 * math.sin(2 * math.pi / n)
return round(area, 2) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts two arguments, an integer 'n' representing the number of sides for a regular polygon, and a floating point number 'R' representing the radius of the circumcircle of the polygon. The function should calculate and return the area of the regular polygon. The ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 132,
"level": 1,
"question": "Create a function that accepts two arguments, an integer 'n' representing the number of sides for a regular polygon, and a floating point number 'R' representing the radius of the circumcircle of the polygon. The function should calculate and return the... |
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for i in range(2, n + 1):
c = a + b
a = b
b = c
return b | simplelr_Evol | [
{
"content": "Question:\nWrite a function to compute the nth Fibonacci number using dynamic programming. The Fibonacci sequence is defined as follows: \n- F(0) = 0\n- F(1) = 1\n- F(n) = F(n-1) + F(n-2) for n > 1\n\nThe function should take an integer n and return the nth Fibonacci number, leveraging a bottom-up... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 133,
"level": 1,
"question": "Write a function to compute the nth Fibonacci number using dynamic programming. The Fibonacci sequence is defined as follows: \n- F(0) = 0\n- F(1) = 1\n- F(n) = F(n-1) + F(n-2) for n > 1\n\nThe function should take an integer n and return the nth Fibona... |
def binary_search(arr, goal, k=None):
low = 0
high = len(arr) - 1
if not arr:
return -1
max_iterations = k if k is not None else float('inf')
iterations = 0
while low <= high and iterations < max_iterations:
mid = (low + high) // 2
iterations += 1
if arr... | simplelr_Filter | [
{
"content": "Question:\nCreate a function called `binary_search` that implements a binary search algorithm to find the index of a given goal value in a sorted list. The function should take in three parameters: `arr`, a list of integers sorted in ascending order, `goal`, an integer value to search for, and `k`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 134,
"level": 1,
"question": "Create a function called `binary_search` that implements a binary search algorithm to find the index of a given goal value in a sorted list. The function should take in three parameters: `arr`, a list of integers sorted in ascending order, `goal`, an in... |
import csv
import json
def csv_to_json(csv_path, json_path):
try:
with open(csv_path, 'r') as csv_file:
reader = csv.DictReader(csv_file)
data = []
for row in reader:
data.append(dict(row))
with open(json_path, 'w') as json_file:
... | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python script to convert a CSV file into a JSON file? I want to make sure that the JSON file is properly formatted and each row from the CSV file becomes a separate object in the JSON array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 135,
"level": 1,
"question": "Can you help me with a Python script to convert a CSV file into a JSON file? I want to make sure that the JSON file is properly formatted and each row from the CSV file becomes a separate object in the JSON array.",
"split": "train"
} |
import math
def is_perfect_number(n):
if n < 2:
return False
sum_div = 1 # Start with 1, a proper divisor for n > 1
sqrt_n = int(math.sqrt(n))
for i in range(2, sqrt_n + 1):
if n % i == 0:
sum_div += i
other = n // i
if other != i and other != n:
... | simplelr_Filter | [
{
"content": "Question:\nIn the context of a programming problem, how can we determine if a given number is a perfect number? Specifically, I'm interested in understanding the logic and the steps involved in writing a program to check for perfect numbers.\nAnswer:\nLet's think step by step.\n",
"role": "use... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 136,
"level": 1,
"question": "In the context of a programming problem, how can we determine if a given number is a perfect number? Specifically, I'm interested in understanding the logic and the steps involved in writing a program to check for perfect numbers.",
"split": "train"
} |
def find_index(lst, target):
for index, value in enumerate(lst):
if value == target:
return index
return -1 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns the index of the first occurrence of a given integer in the list. If the integer is not found, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 137,
"level": 1,
"question": "Create a function that takes a list of integers and returns the index of the first occurrence of a given integer in the list. If the integer is not found, return -1.",
"split": "train"
} |
def get_authentication_details(file_path: str, host: str) -> tuple:
import netrc
try:
nrc = netrc.netrc(file_path)
auth = nrc.authenticators(host)
if auth == (None, None, None):
return None
return auth
except FileNotFoundError as fnf:
raise fnf
except ... | simplelr_Docs | [
{
"content": "Question:\n**Objective**: Demonstrate understanding of the `netrc` module for parsing `.netrc` files, handling exceptions, and fetching authentication details.\n\n**Problem Statement**:\n\nYou are required to implement a function `get_authentication_details(file_path: str, host: str) -> tuple` tha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 138,
"level": 1,
"question": "**Objective**: Demonstrate understanding of the `netrc` module for parsing `.netrc` files, handling exceptions, and fetching authentication details.\n\n**Problem Statement**:\n\nYou are required to implement a function `get_authentication_details(file_p... |
def filter_negatives(lst):
if not lst:
return []
if lst[0] >= 0:
return [lst[0]] + filter_negatives(lst[1:])
else:
return filter_negatives(lst[1:]) | simplelr_Filter | [
{
"content": "Question:\nRewrite the following Python function to filter out the negative values from a list of integers using a recursive approach.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 139,
"level": 1,
"question": "Rewrite the following Python function to filter out the negative values from a list of integers using a recursive approach.",
"split": "train"
} |
def prefix_to_postfix(prefix):
tokens = prefix.split()[::-1] # Split the prefix string into tokens and reverse them
stack = '' # Initialize the stack as an empty string
for token in tokens:
if token in {'+', '-', '*', '/', '^'}:
# Need to pop two operands from the stack
... | simplelr_Filter | [
{
"content": "Question:\nDevelop a function to convert a given prefix expression to a postfix expression while strictly using a single loop (no recursive functions allowed). In addition, manually manage a stack to assist in the conversion - do not use any built-in stack functionalities or data structures like l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 140,
"level": 1,
"question": "Develop a function to convert a given prefix expression to a postfix expression while strictly using a single loop (no recursive functions allowed). In addition, manually manage a stack to assist in the conversion - do not use any built-in stack functio... |
from typing import List
def prime_factors(number: int) -> List[int]:
# Validate input
if type(number) is not int:
raise ValueError("number must be an integer")
if number < 1:
raise ValueError("number must be greater than or equal to 1")
if number == 1:
return [1]
factor... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question: Prime Factorization\n\n**Context**:\nPrime factorization involves breaking down a composite number into its prime factors. For example, the number 28 can be factored into 2, 2, and 7, since \\(2 \\times 2 \\times 7 = 28\\).\n\n### Task:\nWrite a function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 141,
"level": 1,
"question": "### Coding Assessment Question: Prime Factorization\n\n**Context**:\nPrime factorization involves breaking down a composite number into its prime factors. For example, the number 28 can be factored into 2, 2, and 7, since \\(2 \\times 2 \\times 7 = 28\\... |
def maxProductOfThree(arr, n):
arr.sort()
option1 = arr[-1] * arr[-2] * arr[-3]
option2 = arr[0] * arr[1] * arr[-1]
return max(option1, option2)
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of N integers, find the maximum product of any three numbers in the array.\nExample 1:\nInput : arr[ ] = {1, 4, 3, -6, -7, 0}\nOutput : 168\nExplanation:\nMaximum product is 168 obtained from -6, -7, 4 \n\nExample 2:\nInput : arr[ ] = {1, 2, 3}\nOutput : 6\n\nYour Task:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 142,
"level": 1,
"question": "Given an array of N integers, find the maximum product of any three numbers in the array.\nExample 1:\nInput : arr[ ] = {1, 4, 3, -6, -7, 0}\nOutput : 168\nExplanation:\nMaximum product is 168 obtained from -6, -7, 4 \n\nExample 2:\nInput : arr[ ] = {1,... |
def longest_repeating_substring(s):
if not s:
return 0
max_length = 1
current_length = 1
current_char = s[0]
for char in s[1:]:
if char == current_char:
current_length += 1
else:
if current_length > max_length:
max_length = current_leng... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s`, determine the length of the longest substring of `s` that consists of the same character. For example, if the input string is \"abbcccddddeeeeedcba\", the output should be 5, since the longest substring with identical characters is \"eeeee\" which has length 5.\nAnsw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 143,
"level": 1,
"question": "Given a string `s`, determine the length of the longest substring of `s` that consists of the same character. For example, if the input string is \"abbcccddddeeeeedcba\", the output should be 5, since the longest substring with identical characters is \... |
def count_even_odd(arr):
even_count = 0
odd_count = 0
for num in arr:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
return [even_count, odd_count] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers and returns an array with two elements: the first being the count of even numbers and the second being the count of odd numbers in the input array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 144,
"level": 1,
"question": "Create a function that takes an array of integers and returns an array with two elements: the first being the count of even numbers and the second being the count of odd numbers in the input array.",
"split": "train"
} |
def dailyTemperatures(arr):
res = [0] * len(arr)
stack = []
for i in range(len(arr)):
while stack and arr[i] > arr[stack[-1]]:
j = stack.pop()
res[j] = i - j
stack.append(i)
return res | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` representing a list of daily temperatures. For each day, you need to tell how many days you have to wait until a warmer temperature. If there is no future day for which this is possible, return `0` for that day. Implement a function that returns ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 145,
"level": 1,
"question": "You are given an array of integers `arr` representing a list of daily temperatures. For each day, you need to tell how many days you have to wait until a warmer temperature. If there is no future day for which this is possible, return `0` for that day. ... |
def find_top_manager(n, reportPairs):
employees = set()
for pair in reportPairs:
employees.add(pair[1])
for i in range(1, n + 1):
if i not in employees:
return i
return -1 | simplelr_Leetcode | [
{
"content": "Question:\nA company has a list of employees, and each employee has a unique ID number. The company also has a list of pairs, where each pair represents a direct reporting relationship between a manager and an employee. Given an integer `n` representing the number of employees and an array `report... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 146,
"level": 1,
"question": "A company has a list of employees, and each employee has a unique ID number. The company also has a list of pairs, where each pair represents a direct reporting relationship between a manager and an employee. Given an integer `n` representing the number... |
def filter_and_sum_even_numbers(numbers):
evens = [num for num in numbers if num % 2 == 0]
evens.sort()
sum_evens = sum(evens)
return evens, sum_evens | simplelr_Filter | [
{
"content": "Question:\nGiven a list of numbers, write a Python function to return a new list containing only the even numbers from the original list, and sort this new list in ascending order. Additionally, the function should return the sum of all the even numbers.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 147,
"level": 1,
"question": "Given a list of numbers, write a Python function to return a new list containing only the even numbers from the original list, and sort this new list in ascending order. Additionally, the function should return the sum of all the even numbers.",
"spli... |
def convert_to_24_hour(time_str):
# Split the input into time and period parts
parts = time_str.split()
if len(parts) != 2:
raise ValueError("Invalid time format")
time_part, period = parts[0], parts[1].upper()
# Check if the period is valid
if period not in ('AM', 'PM'):
... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a 12-hour AM/PM formatted time string (e.g., '02:30 PM') and converts it to a 24-hour time formatted string (e.g., '14:30'). Make sure to handle the edge cases like midnight ('12:00 AM') and noon ('12:00 PM') correctly. Below are a few examples for reference:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 148,
"level": 1,
"question": "Write a function that takes a 12-hour AM/PM formatted time string (e.g., '02:30 PM') and converts it to a 24-hour time formatted string (e.g., '14:30'). Make sure to handle the edge cases like midnight ('12:00 AM') and noon ('12:00 PM') correctly. Below... |
import heapq
def find_shortest_path(edges, start, destination):
# Build the adjacency list
adj = {}
for a, b, d in edges:
if a not in adj:
adj[a] = []
adj[a].append((b, d))
# Initialize distances
distances = {}
for node in adj:
distances[node] = float('i... | simplelr_Apps | [
{
"content": "Question:\nYou are on an expedition to explore a series of connected caves. Each cave connects to other caves through tunnel passages. Your goal is to find the shortest path from a starting cave to a destination cave, but there's a catch: each tunnel can only be used at most once.\n\nGiven a list ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 149,
"level": 1,
"question": "You are on an expedition to explore a series of connected caves. Each cave connects to other caves through tunnel passages. Your goal is to find the shortest path from a starting cave to a destination cave, but there's a catch: each tunnel can only be u... |
def find_single_number(arr):
res = 0
for num in arr:
res ^= num
return res
| simplelr_Taco | [
{
"content": "Question:\nYou are given a list of integers where each integer appears exactly twice, except for one integer which appears only once. \n\nYour task is to find and return the integer that appears only once.\n\nYou need to implement a function `find_single_number(arr)` that takes in a list of intege... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 150,
"level": 1,
"question": "You are given a list of integers where each integer appears exactly twice, except for one integer which appears only once. \n\nYour task is to find and return the integer that appears only once.\n\nYou need to implement a function `find_single_number(ar... |
def reverse_string_by_words(input_string: str) -> str:
words = input_string.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Package | [
{
"content": "Question:\nIn this problem, you are required to create a function named `reverse_string_by_words()` that takes a string as input and returns the string with the order of the words reversed. This function will demonstrate the use of basic string manipulation and list methods in Python.\n\n### Objec... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 151,
"level": 1,
"question": "In this problem, you are required to create a function named `reverse_string_by_words()` that takes a string as input and returns the string with the order of the words reversed. This function will demonstrate the use of basic string manipulation and li... |
def filter_and_count_words(s):
words = s.split()
unique_words = {word.lower() for word in words}
return len(unique_words) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to filter and count the number of words in a given string, where a word is defined as any sequence of characters separated by whitespace. The function should consider both uppercase and lowercase letters as the same word.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 152,
"level": 1,
"question": "Write a python function to filter and count the number of words in a given string, where a word is defined as any sequence of characters separated by whitespace. The function should consider both uppercase and lowercase letters as the same word.",
"sp... |
def is_even(num):
return num % 2 == 0 | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if the input number is even.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 153,
"level": 1,
"question": "Write a function to check if the input number is even.",
"split": "train"
} |
def contains_special_characters(s):
for char in s:
if not char.isalpha() and not char.isdigit():
return True
return False | simplelr_Filter | [
{
"content": "Question:\nGiven a string, how can I write a Python function to check if it contains any special characters? Special characters are defined as any character that is not a letter (a-z, A-Z) or a digit (0-9).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 154,
"level": 1,
"question": "Given a string, how can I write a Python function to check if it contains any special characters? Special characters are defined as any character that is not a letter (a-z, A-Z) or a digit (0-9).",
"split": "train"
} |
def get_value(a, b, key):
return a.get(key, b.get(key)) | simplelr_Filter | [
{
"content": "Question:\nI have two numbers, say `a` and `b`. I want to be able to get a value from `a`, and if it's not in `a` then try and get it from `b`.\n\n### Example\n```python\ndef get_value(a, b, key):\n if key in a:\n return a[key]\n elif key in b:\n return b[key]\n else:\n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 155,
"level": 1,
"question": "I have two numbers, say `a` and `b`. I want to be able to get a value from `a`, and if it's not in `a` then try and get it from `b`.\n\n### Example\n```python\ndef get_value(a, b, key):\n if key in a:\n return a[key]\n elif key in b:\n ... |
def reverse_string(s):
lst = list(s)
left = 0
right = len(lst) - 1
while left < right:
lst[left], lst[right] = lst[right], lst[left]
left += 1
right -= 1
return ''.join(lst)
# Example usage
s = 'HelloWorld1234567890abcdefghi'
print(reverse_string(s)) | simplelr_Filter | [
{
"content": "Question:\nReverse a String in Python but without using the built-in reverse function or slicing. Additionally, consider a large string, for instance 'HelloWorld1234567890abcdefghi'. Demonstrate that your solution works efficiently even in such scenarios and analyse the time complexity of your sol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 156,
"level": 1,
"question": "Reverse a String in Python but without using the built-in reverse function or slicing. Additionally, consider a large string, for instance 'HelloWorld1234567890abcdefghi'. Demonstrate that your solution works efficiently even in such scenarios and analy... |
from typing import List, Tuple
def sort_meetings(meetings: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
return sorted(meetings) | simplelr_Algorithm | [
{
"content": "Question:\n### Sorting the Meeting Times\n\nScheduling and efficiently managing meeting times is a common task in software development. Your objective is to write a function that will take a list of meeting times and return them in sorted order, ensuring that chronological order is maintained.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 157,
"level": 1,
"question": "### Sorting the Meeting Times\n\nScheduling and efficiently managing meeting times is a common task in software development. Your objective is to write a function that will take a list of meeting times and return them in sorted order, ensuring that chro... |
def find_missing_number(nums: list[int]) -> int:
n = len(nums)
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum | simplelr_Algorithm | [
{
"content": "Question:\nFind Missing Number\n\nYou are given a list `nums` containing `n` distinct numbers in the range `[0, n]` inclusive. This means that the list has `n+1` numbers for which one number is missing. Your task is to write a function that finds and returns the missing number from the list.\n\n##... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 158,
"level": 1,
"question": "Find Missing Number\n\nYou are given a list `nums` containing `n` distinct numbers in the range `[0, n]` inclusive. This means that the list has `n+1` numbers for which one number is missing. Your task is to write a function that finds and returns the m... |
def num_to_bin_str(num):
return bin(num)[2:] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `num_to_bin_str` that converts a given non-negative integer to its binary representation as a string. The function should take one parameter: `num` (the non-negative integer to convert). It must return a string representing the binary equivalent of the given inte... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 159,
"level": 1,
"question": "Write a Python function `num_to_bin_str` that converts a given non-negative integer to its binary representation as a string. The function should take one parameter: `num` (the non-negative integer to convert). It must return a string representing the b... |
from typing import Union
def transform_data(data: Union[bytearray, bytes]) -> bytearray:
is_bytearray = isinstance(data, bytearray)
if not is_bytearray:
data = bytearray(data)
mview = memoryview(data)
n = len(mview)
half = n // 2
for i in range(half):
mview[i] = mview[i] * 2
... | simplelr_Docs | [
{
"content": "Question:\n### MemoryView Manipulation\n\nYou are required to implement a function that processes data using `memoryview` objects in Python. The function will accept a bytearray or bytes object and perform a specific transformation, demonstrating an understanding of memoryview creation and manipul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 160,
"level": 1,
"question": "### MemoryView Manipulation\n\nYou are required to implement a function that processes data using `memoryview` objects in Python. The function will accept a bytearray or bytes object and perform a specific transformation, demonstrating an understanding ... |
from datetime import date, timedelta
def get_tomorrow():
today = date.today()
delta = timedelta(days=1)
tomorrow = today + delta
return tomorrow.strftime("%Y-%m-%d") | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `get_tomorrow()` that returns a string representing the date of the day after the current date in the format \"YYYY-MM-DD\". Use the `datetime` module to accomplish this.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 161,
"level": 1,
"question": "Write a Python function `get_tomorrow()` that returns a string representing the date of the day after the current date in the format \"YYYY-MM-DD\". Use the `datetime` module to accomplish this.",
"split": "train"
} |
def encrypt(message):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
encrypted_message = ''
for char in message:
position = alphabet.index(char)
encrypted_message += alphabet[(position + 3) % 26]
return encrypted_message | simplelr_Filter | [
{
"content": "Question:\nSecurity through Obscurity\n================================================\n\nIn this challenge, we will implement a simple cryptographic scheme to\nhide our communication. We will use a very basic substitution cipher to\nreplace each letter in our message with a letter three position... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 162,
"level": 1,
"question": "Security through Obscurity\n================================================\n\nIn this challenge, we will implement a simple cryptographic scheme to\nhide our communication. We will use a very basic substitution cipher to\nreplace each letter in our me... |
def find_min_max(arr):
if len(arr) == 0:
raise ValueError("Array must contain at least one element")
min_val = arr[0]
max_val = arr[0]
for num in arr:
if num < min_val:
min_val = num
if num > max_val:
max_val = num
return (min_val, max_val) | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\nWrite a Python function `find_min_max(arr)` that takes an array of integers and returns a tuple containing the minimum and maximum values in the array without using the built-in `min` and `max` functions.\n\nThe function should implement the following:\n\n* **Input**:\n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 163,
"level": 1,
"question": "### Question\n\nWrite a Python function `find_min_max(arr)` that takes an array of integers and returns a tuple containing the minimum and maximum values in the array without using the built-in `min` and `max` functions.\n\nThe function should implement... |
def evaluate_expressions(expressions):
results = []
for expr in expressions:
try:
result = eval(expr)
results.append(result)
except:
results.append('Error')
return results | simplelr_Evol | [
{
"content": "Question:\nWrite a function that accepts a list of strings where each string represents a mathematical expression containing integers and the basic arithmetic operators (+, -, *, /). Your function should evaluate these expressions and return a list of results. Ensure that division by zero and inva... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 164,
"level": 1,
"question": "Write a function that accepts a list of strings where each string represents a mathematical expression containing integers and the basic arithmetic operators (+, -, *, /). Your function should evaluate these expressions and return a list of results. Ens... |
def find_anagram_indices(s, p):
len_p = len(p)
len_s = len(s)
result = []
if len_p == 0 or len_s < len_p:
return result
# Create frequency count for p
count_p = [0] * 26
for c in p:
count_p[ord(c) - ord('a')] += 1
# Initialize frequency count for the first ... | simplelr_Apps | [
{
"content": "Question:\nWrite a function `find_anagram_indices` that takes two parameters: a string `s` and a string `p`. The function should return a list of starting indices of the anagrams of `p` present in `s`. An anagram is a permutation of a string. The order of output does not matter.\n\nConstraints:\n-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 165,
"level": 1,
"question": "Write a function `find_anagram_indices` that takes two parameters: a string `s` and a string `p`. The function should return a list of starting indices of the anagrams of `p` present in `s`. An anagram is a permutation of a string. The order of output d... |
from typing import Tuple
import audioop
def combine_audio_operations(fragment1: bytes, fragment2: bytes, width: int) -> Tuple[float, bytes]:
# Addition of two fragments
combined_fragment = audioop.add(fragment1, fragment2, width)
# Conversion to u-LAW encoding
ulaw_fragment = audioop.lin2ulaw(comb... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\nWrite a function `combine_audio_operations` that takes in two audio fragments and processes them through a series of transformations using the `audioop` module. The function should add the two fragments, convert them from linear encoding to `u-LAW` encoding, then reverse... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 166,
"level": 1,
"question": "#### Objective\nWrite a function `combine_audio_operations` that takes in two audio fragments and processes them through a series of transformations using the `audioop` module. The function should add the two fragments, convert them from linear encoding... |
def filter_and_sort_even_numbers(numbers):
even_nums = [num for num in numbers if num % 2 == 0]
unique_evens = list(set(even_nums))
sorted_evens = sorted(unique_evens, reverse=True)
return sorted_evens | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a new list containing only the even numbers from the original list, but sorted in descending order. Ensure that the returned list does not have any duplicates.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 167,
"level": 1,
"question": "Create a function that takes a list of integers and returns a new list containing only the even numbers from the original list, but sorted in descending order. Ensure that the returned list does not have any duplicates.",
"split": "train"
} |
def list_intersection(a, b):
result = []
for x in a:
# Check if x is present in b
is_in_b = False
for y in b:
if x == y:
is_in_b = True
break
if is_in_b:
# Check if x is already in the result
is_in_result = False... | simplelr_Filter | [
{
"content": "Question:\nGiven two list a and b, write a Python program to find the intersection of these lists without using any built-in functions.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 168,
"level": 1,
"question": "Given two list a and b, write a Python program to find the intersection of these lists without using any built-in functions.",
"split": "train"
} |
import string
def unique_word_counter(file_path):
try:
with open(file_path, 'r') as file:
text = file.read()
except IOError:
print(f"Error: File {file_path} cannot be opened.")
return {}
# Convert to lowercase and remove punctuation
text = text.lower().translate... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a Python function, `unique_word_counter`, which reads a text file and counts the number of unique words, ignoring case and punctuation. The function should return a dictionary where the keys are the unique words and the values are the counts of their occurre... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 169,
"level": 1,
"question": "You are tasked with creating a Python function, `unique_word_counter`, which reads a text file and counts the number of unique words, ignoring case and punctuation. The function should return a dictionary where the keys are the unique words and the valu... |
def encodeString(s: str) -> str:
stack = []
current_string = ''
current_num = 0
for char in s:
if char.isdigit():
current_num = current_num * 10 + int(char)
elif char == '[':
stack.append((current_string, current_num))
current_string = ''
... | simplelr_Taco | [
{
"content": "Question:\nImplement a function `encodeString(s)` to encode a given string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is repeated exactly `k` times. You may assume that the input string is always valid and consists only of lowercase English al... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 170,
"level": 1,
"question": "Implement a function `encodeString(s)` to encode a given string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is repeated exactly `k` times. You may assume that the input string is always valid and con... |
import os
import errno
def describe_error_code(code: int) -> str:
if code in errno.errorcode:
error_name = errno.errorcode[code]
try:
error_message = os.strerror(code)
except Exception as e:
error_message = f"Error message unavailable: {str(e)}"
return f"Erro... | simplelr_Docs | [
{
"content": "Question:\n#### Problem Statement:\nYou are required to design a utility function that handles errors using the `errno` module. This function should take an integer error code and return a detailed error description. Specifically, the function should do the following:\n\n1. If the error code is pr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 171,
"level": 1,
"question": "#### Problem Statement:\nYou are required to design a utility function that handles errors using the `errno` module. This function should take an integer error code and return a detailed error description. Specifically, the function should do the follow... |
import numpy as np
def generate_matrix_and_find_max():
matrix = np.random.randint(0, 16, size=(4, 4))
max_values = matrix.max(axis=1).tolist()
return matrix, max_values | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that generates a random 4x4 matrix with values ranging from 0 to 15, and then finds the maximum value in each row. The function should return both the generated matrix and the list of maximum values. Use numpy for matrix operations.\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 172,
"level": 1,
"question": "Write a Python function that generates a random 4x4 matrix with values ranging from 0 to 15, and then finds the maximum value in each row. The function should return both the generated matrix and the list of maximum values. Use numpy for matrix operatio... |
import os
import torch
import torch.distributed as dist
def main(rank, world_size):
# Define the shared file path
shared_file = 'torch_dist_init'
init_method = f"file://{os.path.abspath(shared_file)}"
# Initialize the process group with 'gloo' backend
dist.init_process_group(backend='gloo',
... | simplelr_Docs | [
{
"content": "Question:\n**Question 1: Initialization and Collective Operations in `torch.distributed`**\n\nYou are tasked to implement a distributed training setup using PyTorch's `torch.distributed` module. Write a script that:\n\n1. Initializes a distributed process group with the `gloo` backend.\n2. Creates... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 173,
"level": 1,
"question": "**Question 1: Initialization and Collective Operations in `torch.distributed`**\n\nYou are tasked to implement a distributed training setup using PyTorch's `torch.distributed` module. Write a script that:\n\n1. Initializes a distributed process group wi... |
def pigeonhole_sort(arr: list) -> list:
if not arr:
return []
min_num = min(arr)
max_num = max(arr)
range_size = max_num - min_num + 1
holes = [0] * range_size
for num in arr:
index = num - min_num
holes[index] += 1
sorted_arr = []
for i in range(len(holes)):
... | simplelr_Data_Structure | [
{
"content": "Question:\n### **Problem Statement**\n\nYou are given a list of integers. You need to sort the list using an algorithm suitable for when the number of distinct values in the list is relatively low and close in range. Implement the Pigeonhole Sort algorithm to sort the given list. \n\n### **Functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 174,
"level": 1,
"question": "### **Problem Statement**\n\nYou are given a list of integers. You need to sort the list using an algorithm suitable for when the number of distinct values in the list is relatively low and close in range. Implement the Pigeonhole Sort algorithm to sort... |
def get_elements_by_tag(tree, target_tag):
return [node[1] for node in tree if node[0] == target_tag] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to get all the elements under the tree with a given specific tag. You can assume the tree is a list of lists where each sub-list represents a leaf node. Each sub-list has the format `[tag, value]`. For example: `tree = [['root', 'value1'], ['child1', 'value2'], [... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 175,
"level": 1,
"question": "Write a python function to get all the elements under the tree with a given specific tag. You can assume the tree is a list of lists where each sub-list represents a leaf node. Each sub-list has the format `[tag, value]`. For example: `tree = [['root', ... |
def first_non_repeating_char(s):
counts = {}
for char in s:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
for char in s:
if counts[char] == 1:
return char
return "_blank_" | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` containing only lowercase letters, return _the first non-repeating character_ in it. If all characters are repeating, return `\"_blank_\"`. You may assume that the string contains at most one character that is non-repeating.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 176,
"level": 1,
"question": "Given a string `s` containing only lowercase letters, return _the first non-repeating character_ in it. If all characters are repeating, return `\"_blank_\"`. You may assume that the string contains at most one character that is non-repeating.",
"spli... |
def longest_palindromic_substring(s):
n = len(s)
if n == 0:
return ""
# Create a table to store results of subproblems
dp = [[False for _ in range(n)] for _ in range(n)]
max_length = 1 # The maximum length of the palindromic substring found
start = 0 # Starting index of ... | simplelr_Filter | [
{
"content": "Question:\nDevelop a Python program to find the longest \\emph{palindromic} substring in a given string using dynamic programming.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 177,
"level": 1,
"question": "Develop a Python program to find the longest \\emph{palindromic} substring in a given string using dynamic programming.",
"split": "train"
} |
def binary_search(lst, target):
left = 0
right = len(lst) - 1
while left <= right:
mid = (left + right) // 2
if lst[mid] == target:
return mid
elif lst[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 | simplelr_Filter | [
{
"content": "Question:\nYou need to write a function that implements a binary search algorithm on a given sorted list. The function should return the index of the target value if it is in the list, otherwise it should return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 178,
"level": 1,
"question": "You need to write a function that implements a binary search algorithm on a given sorted list. The function should return the index of the target value if it is in the list, otherwise it should return -1.",
"split": "train"
} |
def schedule_deadlines(tasks):
# Sort tasks by deadline and then processing time, both in ascending order
sorted_tasks = sorted(tasks, key=lambda x: (x[1], x[2]))
# Extract the task names from the sorted list
return [task[0] for task in sorted_tasks] | simplelr_Filter | [
{
"content": "Question:\nWhile testing a new proprietary algorithm, you've stumbled upon an issue that affects the scheduling of tasks with deadlines. Specifically, your algorithm is incorrectly scheduling tasks that have the same deadline. To debug this, you want to write a utility function `schedule_deadlines... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 179,
"level": 1,
"question": "While testing a new proprietary algorithm, you've stumbled upon an issue that affects the scheduling of tasks with deadlines. Specifically, your algorithm is incorrectly scheduling tasks that have the same deadline. To debug this, you want to write a ut... |
import heapq
def min_transport_cost(n: int, edges: list[tuple], start: int, end: int) -> int:
if start == end:
return 0
# Build adjacency list
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
# Initialize distances
INF = float('inf')
dist = ... | simplelr_Algorithm | [
{
"content": "Question:\n## Coding Assessment Question\n\n### Scenario\nIn supply chain management, it is crucial to determine the total cost of transporting goods between multiple warehouses. Goods can be moved directly or through intermediate warehouses, with different costs associated with each route, and th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 180,
"level": 1,
"question": "## Coding Assessment Question\n\n### Scenario\nIn supply chain management, it is crucial to determine the total cost of transporting goods between multiple warehouses. Goods can be moved directly or through intermediate warehouses, with different costs ... |
def longest_consecutive_subseq_length(arr):
if not arr:
return 0
num_set = set(arr)
max_length = 0
for num in arr:
if (num - 1) not in num_set:
current_num = num
current_length = 1
while (current_num + 1) in num_set:
c... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function `longest_consecutive_subseq_length(arr)` that finds the length of the longest subsequence of consecutive integers in a given list of integers. The function should not sort the array and should run in O(n) time complexity.\n\nHere's the signature of t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 181,
"level": 1,
"question": "You are required to write a function `longest_consecutive_subseq_length(arr)` that finds the length of the longest subsequence of consecutive integers in a given list of integers. The function should not sort the array and should run in O(n) time comple... |
def findMedianSortedArrays(nums1, nums2):
# Ensure that nums1 is the smaller array to optimize the binary search
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
m = len(nums1)
n = len(nums2)
total = m + n
k = (m + n + 1) // 2 # The position to find the median
low =... | simplelr_Evol | [
{
"content": "Question:\nYou are given the task of finding the median of two sorted arrays. Note that the arrays may have different lengths. Design a function that, given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, returns the median of the two combined datasets.\n\nYour solution sho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 182,
"level": 1,
"question": "You are given the task of finding the median of two sorted arrays. Note that the arrays may have different lengths. Design a function that, given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, returns the median of the two combi... |
from collections import deque
def shortest_path_maze(grid, startRow, startCol):
n = len(grid)
if n == 0:
return -1
if startRow == n-1 and startCol == n-1:
return 0
visited = [[False for _ in range(n)] for _ in range(n)]
queue = deque()
queue.append((startRow, startCol, 0))
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an n x n grid representing a maze where '.' represents an open cell and '#' represents a wall. You are also given the starting coordinates (startRow, startCol) in the maze. Your task is to implement a function that determines the length of the shortest path from the starti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 183,
"level": 1,
"question": "You are given an n x n grid representing a maze where '.' represents an open cell and '#' represents a wall. You are also given the starting coordinates (startRow, startCol) in the maze. Your task is to implement a function that determines the length of... |
def count_distinct_vertical_lines(points):
from collections import defaultdict
x_counts = defaultdict(int)
for point in points:
x = point[0]
x_counts[x] += 1
count = 0
for v in x_counts.values():
if v >= 2:
count += 1
return count | simplelr_Evol | [
{
"content": "Question:\nDescription: You are given a list of `points` on a 2D plane, where each point is represented as `[x, y]`. Your task is to determine the number of distinct vertical lines that can be formed using these points such that each line contains at least two distinct points from the list.\n\nExa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 184,
"level": 1,
"question": "Description: You are given a list of `points` on a 2D plane, where each point is represented as `[x, y]`. Your task is to determine the number of distinct vertical lines that can be formed using these points such that each line contains at least two dis... |
from typing import List
def find_unique_pair(nums: List[int]) -> List[int]:
xor_sum = 0
for num in nums:
xor_sum ^= num
mask = xor_sum & -xor_sum # Get the least significant set bit
a, b = 0, 0
for num in nums:
if num & mask:
a ^= num
else:
... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given an array of integers where exactly two elements appear only once and all other elements appear exactly twice. You need to identify these two unique elements. Implement a function that solves this with a time complexity of O(N) and space complexity of O(1).\n\n### Function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 185,
"level": 1,
"question": "You are given an array of integers where exactly two elements appear only once and all other elements appear exactly twice. You need to identify these two unique elements. Implement a function that solves this with a time complexity of O(N) and space co... |
def findGCD(A, B):
while B != 0:
temp = B
B = A % B
A = temp
return A
| simplelr_Taco | [
{
"content": "Question:\nGiven two integers A and B. Your task is to calculate the greatest common divisor (GCD) of the two numbers and return it.\nExample 1:\nInput:\nA = 48, B = 18\nOutput:\n6\n\nExample 2:\nInput:\nA = 101, B = 103\nOutput:\n1\n\nYour Task:\nYou don't need to read input or print anything. Yo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 186,
"level": 1,
"question": "Given two integers A and B. Your task is to calculate the greatest common divisor (GCD) of the two numbers and return it.\nExample 1:\nInput:\nA = 48, B = 18\nOutput:\n6\n\nExample 2:\nInput:\nA = 101, B = 103\nOutput:\n1\n\nYour Task:\nYou don't need t... |
def sort_records(records):
"""
Sort the list of dictionaries 'records' by 'age' (ascending) and 'score' (descending).
Parameters:
- records: List of dictionaries, where each dictionary contains the keys 'age' and 'score'.
Returns:
- sorted_records: List of dictionaries sorted by 'age' (asc... | simplelr_Package | [
{
"content": "Question:\n**Sorting a List of Dictionaries by Multiple Keys**\n\nYou are tasked with implementing a function that sorts a list of dictionaries by multiple keys. You will sort the list based on two specific keys: `age` and `score`. The primary sorting key is `age` (in ascending order), and the sec... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 187,
"level": 1,
"question": "**Sorting a List of Dictionaries by Multiple Keys**\n\nYou are tasked with implementing a function that sorts a list of dictionaries by multiple keys. You will sort the list based on two specific keys: `age` and `score`. The primary sorting key is `age`... |
def add_minutes(time_str, mins):
hh, mm = map(int, time_str.split(':'))
total = hh * 60 + mm + mins
total %= 1440 # 24*60 to wrap around the day
new_hh = total // 60
new_mm = total % 60
return f"{new_hh:02d}:{new_mm:02d}"
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a string representing a time in the format `HH:MM` (24-hour format) and an integer representing a number of minutes. The function should return the new time after adding the specified number of minutes to the given time. \n\nExamples:\n```\n\"23:45\", 30 -> \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 188,
"level": 1,
"question": "Write a function that takes a string representing a time in the format `HH:MM` (24-hour format) and an integer representing a number of minutes. The function should return the new time after adding the specified number of minutes to the given time. \n\n... |
def longest_substring_with_k_unique_characters(s, k):
if not s or k == 0:
return 0
max_len = 0
freq = [0] * 26
unique_count = 0
left = 0
for right in range(len(s)):
c = s[right]
idx = ord(c) - ord('a')
if freq[idx] == 0:
unique_count += 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Find Longest Substring with K Unique Characters\n\n#### Objective\n\nWrite a function `longest_substring_with_k_unique_characters` that takes as input a string and an integer `k` and returns the length of the longest substring that contains exactly `k` unique characters.\n\n#### Inp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 189,
"level": 1,
"question": "### Find Longest Substring with K Unique Characters\n\n#### Objective\n\nWrite a function `longest_substring_with_k_unique_characters` that takes as input a string and an integer `k` and returns the length of the longest substring that contains exactly ... |
def longest_unique_substring(s: str) -> int:
max_length = 0
left = 0
last_seen = [-1] * 256 # Using extended ASCII
for right in range(len(s)):
c = s[right]
if last_seen[ord(c)] >= left:
left = last_seen[ord(c)] + 1
last_seen[ord(c)] = right
current_length = ... | simplelr_Package | [
{
"content": "Question:\nIn this problem, you will write a function that finds the length of the longest substring of a given string that consists of unique characters. The function should be implemented without using any additional data structures.\n\nImplement the function `longest_unique_substring(s: str) ->... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 190,
"level": 1,
"question": "In this problem, you will write a function that finds the length of the longest substring of a given string that consists of unique characters. The function should be implemented without using any additional data structures.\n\nImplement the function `l... |
def reverse_vowels(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
vowels_list = [char for char in s if char.lower() in vowels]
reversed_vowels = vowels_list[::-1]
i = 0
result = []
for char in s:
if char.lower() in vowels:
result.append(reversed_vowels[i])
i += 1
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse vowels in a given string. The function should take a single string as input and return a new string with all the vowels reversed, while keeping the consonants in their original positions. How can this be achieved?\nAnswer:\nLet's think step by step.\n"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 191,
"level": 1,
"question": "Write a python function to reverse vowels in a given string. The function should take a single string as input and return a new string with all the vowels reversed, while keeping the consonants in their original positions. How can this be achieved?",
... |
def replace_substring(original, substring, replacement):
return original.replace(substring, replacement) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to replace all occurrences of a substring in a string, considering the case sensitivity.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 192,
"level": 1,
"question": "Write a python function to replace all occurrences of a substring in a string, considering the case sensitivity.",
"split": "train"
} |
def schedule_tasks(tasks: list[int], capacities: list[int]) -> bool:
if not tasks:
return True
tasks_sorted = sorted(tasks, reverse=True)
capacities_sorted = sorted(capacities, reverse=True)
for i in range(len(tasks_sorted)):
if i < len(capacities_sorted):
if tasks_sorted[i] ... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are developing a software that schedules tasks for multiple servers. Each server can handle one task at a time and has a predefined capacity. The capacity is defined as the maximum value of task difficulty that the server can handle.\n\nGiven an array of tas... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 193,
"level": 1,
"question": "### Problem Statement\n\nYou are developing a software that schedules tasks for multiple servers. Each server can handle one task at a time and has a predefined capacity. The capacity is defined as the maximum value of task difficulty that the server ca... |
def reverse_words(s: str) -> str:
words = s.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Reverse Words in a String\n\nGiven a string `s`, implement a function `reverse_words(s: str) -> str` that reverses the order of words in the string while preserving whitespace and initial word order within each word.\n\n#### Function Signature:\n```python\ndef reverse_word... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 194,
"level": 1,
"question": "### Question: Reverse Words in a String\n\nGiven a string `s`, implement a function `reverse_words(s: str) -> str` that reverses the order of words in the string while preserving whitespace and initial word order within each word.\n\n#### Function Signa... |
def is_growth_stable(nums):
if len(nums) <= 1:
return True
diff = nums[1] - nums[0]
for i in range(len(nums) - 1):
if nums[i+1] - nums[i] != diff:
return False
return True | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** array of integers `nums`. An array is called \"growth-stable\" if the difference between any two adjacent elements is equal. Determine if the given array `nums` is growth-stable. Return `true` if the array is growth-stable and `false` otherwise.\nAnswer:\nL... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 195,
"level": 1,
"question": "You are given a **0-indexed** array of integers `nums`. An array is called \"growth-stable\" if the difference between any two adjacent elements is equal. Determine if the given array `nums` is growth-stable. Return `true` if the array is growth-stable ... |
def advanced_binary_search(arr: list, target: int) -> int:
if not arr:
return -1
low = 0
high = len(arr) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
result = mid
high = mid - 1 # Continue searching left ... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nCreate an advanced version of the Binary Search algorithm to demonstrate your understanding of search algorithms and optimization techniques. Your task is to implement an efficient and robust solution that excels in handling various edge cases.\n\n### Advanced Bin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 196,
"level": 1,
"question": "### Problem Statement\nCreate an advanced version of the Binary Search algorithm to demonstrate your understanding of search algorithms and optimization techniques. Your task is to implement an efficient and robust solution that excels in handling vario... |
import numpy as np
def compute_principal_inertia(Ixx, Iyy, Izz, Ixy, Ixz, Iyz):
# Construct the inertia tensor
inertia_tensor = np.array([
[Ixx, -Ixy, -Ixz],
[-Ixy, Iyy, -Iyz],
[-Ixz, -Iyz, Izz]
])
# Compute eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.li... | simplelr_Package | [
{
"content": "Question:\nYou are asked to create a function that calculates the principal moments of inertia and the orientation of the principal axes of a rigid body in a three-dimensional space given its mass distribution. The moments of inertia need to be computed with respect to the principal axes through t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 197,
"level": 1,
"question": "You are asked to create a function that calculates the principal moments of inertia and the orientation of the principal axes of a rigid body in a three-dimensional space given its mass distribution. The moments of inertia need to be computed with respe... |
from typing import List, Tuple, Dict
from collections import defaultdict
def calculate_total_sales(transactions: List[Tuple[str, str, float]]) -> Dict[str, float]:
product_totals = defaultdict(float)
for trans in transactions:
product = trans[1]
cost = trans[2]
product_totals[product] +... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n**Context**:\nYou have been given a data analysis task involving a list of transactions. Each transaction consists of an ID, a product name, and a cost. You need to aggregate the data to determine the total cost for each product sold. Your task is to wr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 198,
"level": 1,
"question": "### Coding Assessment Question\n\n**Context**:\nYou have been given a data analysis task involving a list of transactions. Each transaction consists of an ID, a product name, and a cost. You need to aggregate the data to determine the total cost for eac... |
def find_next_fibonacci(n):
a, b = 0, 1
while a <= n:
a, b = b, a + b
return a | simplelr_Evol | [
{
"content": "Question:\nCreate a function called `find_next_fibonacci` to calculate the smallest Fibonacci number greater than a given number `n`. The function should take an integer `n` as input and return the next Fibonacci number that is greater than `n`. \n\nFor example:\n- If the input is `21`, the functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 199,
"level": 1,
"question": "Create a function called `find_next_fibonacci` to calculate the smallest Fibonacci number greater than a given number `n`. The function should take an integer `n` as input and return the next Fibonacci number that is greater than `n`. \n\nFor example:\n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.