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 find_mintemp(temp_list):
mintemp = temp_list[0]
for temp in temp_list:
if temp < mintemp:
mintemp = temp
return mintemp | simplelr_Filter | [
{
"content": "Question:\nfunction find_mintemp(temp_list):\n mintemp = temp_list[0]\n for temp in temp_list:\n if temp < mintemp:\n mintemp = temp\n return mintemp\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1600,
"level": 1,
"question": "function find_mintemp(temp_list):\n mintemp = temp_list[0]\n for temp in temp_list:\n if temp < mintemp:\n mintemp = temp\n return mintemp",
"split": "train"
} |
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
less = []
equal = []
greater = []
for x in arr:
if x < pivot:
less.append(x)
elif x == pivot:
equal.append(x)
else:
greater.append(x)
return quickso... | simplelr_Filter | [
{
"content": "Question:\nHow can I implement the QuickSort algorithm to sort an array of integers?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1601,
"level": 1,
"question": "How can I implement the QuickSort algorithm to sort an array of integers?",
"split": "train"
} |
import collections
def top_k_frequent(nums, k):
count = collections.Counter(nums)
top_elements = count.most_common(k)
return [elem[0] for elem in top_elements] | simplelr_Package | [
{
"content": "Question:\nYou are tasked with writing a function to find the k most frequent elements in an array. The function should make use of the `collections` module in Python, specifically the `Counter` class, to count the frequency of each element.\n\n**Function Name: `top_k_frequent`**\n\n**Parameters:*... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1602,
"level": 1,
"question": "You are tasked with writing a function to find the k most frequent elements in an array. The function should make use of the `collections` module in Python, specifically the `Counter` class, to count the frequency of each element.\n\n**Function Name: `... |
from typing import List, Tuple
def sum_odd_even_positions(arr: List[int]) -> Tuple[int, int]:
odd_sum = 0
even_sum = 0
for i in range(len(arr)):
if i % 2 == 0:
even_sum += arr[i]
else:
odd_sum += arr[i]
return (odd_sum, even_sum) | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of Odd and Even Positions in an Array\n\nWrite a function `sum_odd_even_positions` that takes an array of integers and returns a tuple `(odd_sum, even_sum)` where `odd_sum` is the sum of elements at odd indices (1, 3, 5, ...) and `even_sum` is the sum of elements at even indices... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1603,
"level": 1,
"question": "### Sum of Odd and Even Positions in an Array\n\nWrite a function `sum_odd_even_positions` that takes an array of integers and returns a tuple `(odd_sum, even_sum)` where `odd_sum` is the sum of elements at odd indices (1, 3, 5, ...) and `even_sum` is ... |
def palindromic_sum(arr):
s = sum(arr)
return str(s) == str(s)[::-1] | simplelr_Apps | [
{
"content": "Question:\n*** Palindromic Sum Checker ***\n\nCreate a function that checks whether the sum of the elements of a given integer array is a palindromic number. A palindromic number is a number that remains the same when its digits are reversed (e.g., 121, 909).\n\nYou must return True if the sum is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1604,
"level": 1,
"question": "*** Palindromic Sum Checker ***\n\nCreate a function that checks whether the sum of the elements of a given integer array is a palindromic number. A palindromic number is a number that remains the same when its digits are reversed (e.g., 121, 909).\n\n... |
def find_anagram_substring(s1: str, s2: str) -> int:
m = len(s1)
n = len(s2)
if m > n:
return -1
counts1 = [0] * 256
counts2 = [0] * 256
for i in range(m):
counts1[ord(s1[i])] += 1
counts2[ord(s2[i])] += 1
if counts1 == counts2:
return 0
for j in range... | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function that receives two strings, `s1` and `s2`, and determines whether `s1` is an anagram of a substring of `s2`. If it is, return the start index of the substring in `s2` that forms the anagram. If multiple start indices are possible, return the smallest one. If no such subs... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1605,
"level": 1,
"question": "Write a function that receives two strings, `s1` and `s2`, and determines whether `s1` is an anagram of a substring of `s2`. If it is, return the start index of the substring in `s2` that forms the anagram. If multiple start indices are possible, retur... |
def factorial(n):
"""
Calculate the factorial of a given non-negative integer using recursion.
Args:
n (int): A non-negative integer.
Returns:
int: The factorial of the input number.
"""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)... | simplelr_Filter | [
{
"content": "Question:\nWrite a simple Python function that calculates the factorial of a given number using recursion. Ensure to include a brief docstring explaining the function's purpose. Also, provide a few test cases to demonstrate the correctness of your function.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1606,
"level": 1,
"question": "Write a simple Python function that calculates the factorial of a given number using recursion. Ensure to include a brief docstring explaining the function's purpose. Also, provide a few test cases to demonstrate the correctness of your function.",
"... |
from collections import defaultdict, deque
from typing import List, Tuple
def can_finish_courses(courses: List[Tuple[int, int]]) -> bool:
# Collect all unique nodes (courses and prerequisites)
nodes = set()
for course, prereq in courses:
nodes.add(course)
nodes.add(prereq)
# Build ... | simplelr_Apps | [
{
"content": "Question:\nGiven the following list of courses and their possible prerequisites, write a function that determines whether it is possible to finish all courses. A course cannot be taken if it has a prerequisite that has not yet been completed. The input to the function is a list of tuples where eac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1607,
"level": 1,
"question": "Given the following list of courses and their possible prerequisites, write a function that determines whether it is possible to finish all courses. A course cannot be taken if it has a prerequisite that has not yet been completed. The input to the fun... |
def my_atoi(s):
s = s.strip()
if not s:
return 0
sign = 1
start = 0
if s[0] == '+':
start = 1
elif s[0] == '-':
sign = -1
start = 1
result = 0
for i in range(start, len(s)):
if not s[i].isdigit():
break
digit = int(s[i... | simplelr_Filter | [
{
"content": "Question:\nWrite a function to convert a given string to an integer in Python, handling edge cases like leading/trailing spaces, non-numeric characters, and overflow. Assume the integer range is -2^31 to 2^31 - 1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1608,
"level": 1,
"question": "Write a function to convert a given string to an integer in Python, handling edge cases like leading/trailing spaces, non-numeric characters, and overflow. Assume the integer range is -2^31 to 2^31 - 1.",
"split": "train"
} |
import bz2
def process_data(data: bytes, filename: str) -> bool:
try:
# Compress the data and write it to the file
with bz2.open(filename, 'wb') as f:
f.write(data)
# Read the compressed data back and decompress it
with bz2.open(filename, 'rb') as f:
... | simplelr_Docs | [
{
"content": "Question:\n#### Background\nYou are tasked with implementing a data processing system that involves compressing and decompressing large datasets. To ensure the system works efficiently, you need to handle both one-shot and incremental compression and decompression.\n\n#### Problem Statement\nImple... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1609,
"level": 1,
"question": "#### Background\nYou are tasked with implementing a data processing system that involves compressing and decompressing large datasets. To ensure the system works efficiently, you need to handle both one-shot and incremental compression and decompressio... |
def max_sum_subarray(arr, window_size):
n = len(arr)
if n == 0 or window_size == 0 or window_size > n:
return 0
current_sum = sum(arr[:window_size])
max_sum = current_sum
for i in range(1, n - window_size + 1):
current_sum = current_sum - arr[i - 1] + arr[i + window_size - 1]
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` and an integer `window_size`. Implement a function that finds the maximum sum of any subarray of length `window_size`. A subarray is a contiguous part of an array. Your function should return this maximum sum value.\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1610,
"level": 1,
"question": "You are given an array of integers `arr` and an integer `window_size`. Implement a function that finds the maximum sum of any subarray of length `window_size`. A subarray is a contiguous part of an array. Your function should return this maximum sum va... |
import marshal
def serialize_and_deserialize(data: dict) -> dict:
try:
# Serialize the dictionary to a binary format
serialized_data = marshal.dumps(data)
# Deserialize the binary data back to a dictionary
deserialized_data = marshal.loads(serialized_data)
... | simplelr_Docs | [
{
"content": "Question:\n**Objective**: To design a function that can serialize and deserialize a specific data structure using the `marshal` module, demonstrating an understanding of its capabilities and constraints.\n\n**Question**:\nImplement a function `serialize_and_deserialize(data)` that takes a dictiona... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1611,
"level": 1,
"question": "**Objective**: To design a function that can serialize and deserialize a specific data structure using the `marshal` module, demonstrating an understanding of its capabilities and constraints.\n\n**Question**:\nImplement a function `serialize_and_deser... |
def max_items(inventory, k):
# Sort the inventory by weight in ascending order
sorted_inventory = sorted(inventory, key=lambda x: x[1])
current_weight = 0
selected = []
for item in sorted_inventory:
name, weight = item
if current_weight + weight <= k:
selected.append(name... | simplelr_Codeforces | [
{
"content": "Question:\nYou are working on a text-based adventure game where the player navigates through a dungeon while collecting treasures and fighting monsters. The game allows the player to pick up items that are described by a string. However, the player can only carry a limited amount of items, specifi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1612,
"level": 1,
"question": "You are working on a text-based adventure game where the player navigates through a dungeon while collecting treasures and fighting monsters. The game allows the player to pick up items that are described by a string. However, the player can only carry... |
def mask_credit_card(number):
s = str(number)
if len(s) <= 4:
return s
else:
return '*' * (len(s) - 4) + s[-4:] | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function to mask a credit card number, showing only the last four digits and replacing the rest with asterisks?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1613,
"level": 1,
"question": "How can I create a Python function to mask a credit card number, showing only the last four digits and replacing the rest with asterisks?",
"split": "train"
} |
def in_stock(item, inventory):
if inventory.get(item, 0) > 0:
return "In stock"
else:
return "Out of stock" | simplelr_Apps | [
{
"content": "Question:\nYou need to implement a function to determine if an item is in stock at a store. The store's inventory will be provided as a dictionary, where keys are item names and values are the quantities available. \n\n```python\ndef in_stock(item, inventory):\n pass\n```\n\nThe function should... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1614,
"level": 1,
"question": "You need to implement a function to determine if an item is in stock at a store. The store's inventory will be provided as a dictionary, where keys are item names and values are the quantities available. \n\n```python\ndef in_stock(item, inventory):\n ... |
def top_k(k, nums, desc=False):
if not nums:
return []
sorted_nums = sorted(nums)
if desc:
sorted_nums = sorted_nums[::-1]
return sorted_nums[:k] | simplelr_Filter | [
{
"content": "Question:\nThe goal of this problem is to write a Python function to compute the k smallest (or largest) elements from an array of numbers. This problem is commonly referred to as the \"top-k\" problem.\n\nImplement a function `top_k(k, nums, desc = False)`, which takes an integer `k` and a list o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1615,
"level": 1,
"question": "The goal of this problem is to write a Python function to compute the k smallest (or largest) elements from an array of numbers. This problem is commonly referred to as the \"top-k\" problem.\n\nImplement a function `top_k(k, nums, desc = False)`, whic... |
import email
from typing import Dict, Any
def parse_email(email_bytes: bytes) -> Dict[str, Any]:
msg = email.message_from_bytes(email_bytes)
return {
"from": msg.get("From"),
"to": msg.get("To"),
"subject": msg.get("Subject"),
"date": msg.get("Date"),
"is_multipart": msg... | simplelr_Docs | [
{
"content": "Question:\n### Email Parsing Project\n\n**Objective**: Use the `email.parser` module to implement a function that parses an email message from a bytes-like object, extracts specific headers, and returns a structured representation.\n\n#### Task Details\n\nYou need to write a function called `parse... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1616,
"level": 1,
"question": "### Email Parsing Project\n\n**Objective**: Use the `email.parser` module to implement a function that parses an email message from a bytes-like object, extracts specific headers, and returns a structured representation.\n\n#### Task Details\n\nYou nee... |
def increment_index(array, index):
"""
This function determines which index to increment based on the rules of the awesome sort algorithm.
Parameters:
array (list): A list of integers
index (int): The current index
Returns:
int: The index to increment based on the rules of the awesome sort... | simplelr_Filter | [
{
"content": "Question:\nTo implement the awesome sort algorithm on an array, define a function to check which index to increment in each iteration. \n\n### Awesome Sort Algorithm\n\nThe awesome sort algorithm works as follows:\n\n- It starts with an array and its index, initially at 0.\n- It checks if the curr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1617,
"level": 1,
"question": "To implement the awesome sort algorithm on an array, define a function to check which index to increment in each iteration. \n\n### Awesome Sort Algorithm\n\nThe awesome sort algorithm works as follows:\n\n- It starts with an array and its index, initi... |
def increasing_triplet(nums):
first = second = float('inf')
for num in nums:
if num <= first:
first = num
elif num <= second:
second = num
else:
return True
return False | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns True if there is a sequence of three increasing integers in the list, otherwise, returns False. The function should be efficient even for very large lists. Avoid using nested loops or any solution with higher than linear ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1618,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns True if there is a sequence of three increasing integers in the list, otherwise, returns False. The function should be efficient even for very large lists. Avoid using nested loops or an... |
def is_accepted(transitions, start, final, string):
current_state = start
for char in string:
if current_state not in transitions:
return False
state_transitions = transitions[current_state]
if char not in state_transitions:
return False
current_state = st... | simplelr_Data_Structure | [
{
"content": "Question:\n**Pattern Recognition using Finite Automaton**\n\n### Background\nYou are given a deterministic finite automaton (DFA) that recognizes certain patterns in strings. The DFA operates using a series of state transitions based on characters of the input string. Your task is to write a funct... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1619,
"level": 1,
"question": "**Pattern Recognition using Finite Automaton**\n\n### Background\nYou are given a deterministic finite automaton (DFA) that recognizes certain patterns in strings. The DFA operates using a series of state transitions based on characters of the input st... |
def factorial(n):
"""
This function calculates the factorial of a given number using a loop.
Args:
n: An integer.
Returns:
The factorial of n.
Raises:
ValueError: If n is negative.
"""
if n < 0:
raise ValueError("Factorial is not defined for negative number... | simplelr_Filter | [
{
"content": "Question:\nThis is a Python code snippet that calculates the factorial of a given number using a loop:\n\n```python\ndef factorial(n):\n \"\"\"\n This function calculates the factorial of a given number using a loop.\n\n Args:\n n: An integer.\n\n Returns:\n The factorial of n.\n\n Rais... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1620,
"level": 1,
"question": "This is a Python code snippet that calculates the factorial of a given number using a loop:\n\n```python\ndef factorial(n):\n \"\"\"\n This function calculates the factorial of a given number using a loop.\n\n Args:\n n: An integer.\n\n Returns:... |
def sum_of_missing_numbers(arr: list[int]) -> int:
if not arr:
return 0
present = set(arr)
m = max(arr)
missing_sum = 0
for i in range(m + 1):
if i not in present:
missing_sum += i
return missing_sum
| simplelr_Taco | [
{
"content": "Question:\n## Sum of Missing Numbers\n\n## Overview\n\nGiven a list of integers with both positive and non-negative values, imagine a contiguous range ([0...n]) that fully encompasses all values in the given list, where `n` is the maximum value in the list. Your task is to identify all the numbers... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1621,
"level": 1,
"question": "## Sum of Missing Numbers\n\n## Overview\n\nGiven a list of integers with both positive and non-negative values, imagine a contiguous range ([0...n]) that fully encompasses all values in the given list, where `n` is the maximum value in the list. Your ... |
def valid_ip_with_subnet(ip):
parts = ip.split('/')
if len(parts) != 2:
return False
ip_part, subnet_part = parts
octets = ip_part.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit():
return False
num = int(octet)
... | simplelr_Taco | [
{
"content": "Question:\nCreate a function\n\n```python\nvalid_ip_with_subnet(ip)\n```\n\nthat takes a string `ip` as an input and returns `True` if it is a valid IPv4 address with subnet mask, otherwise returns `False`. A valid IPv4 address with subnet mask is represented as `x.x.x.x/y` where `x` is a number b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1622,
"level": 1,
"question": "Create a function\n\n```python\nvalid_ip_with_subnet(ip)\n```\n\nthat takes a string `ip` as an input and returns `True` if it is a valid IPv4 address with subnet mask, otherwise returns `False`. A valid IPv4 address with subnet mask is represented as ... |
def remove_duplicates(lst):
return list(dict.fromkeys(lst)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove duplicates from a list. The order of elements should be preserved. To demonstrate your function, remove duplicates from the list `[1, 2, 2, 3, 4, 4, 5]`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1623,
"level": 1,
"question": "Write a python function to remove duplicates from a list. The order of elements should be preserved. To demonstrate your function, remove duplicates from the list `[1, 2, 2, 3, 4, 4, 5]`.",
"split": "train"
} |
def combine_lists(a, b):
paired = list(zip(a, b))
paired += a[len(b):]
paired += b[len(a):]
return paired | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that combines two lists into one, with each element from the two lists paired together as tuples. If one list is longer than the other, append the remaining elements as is. For example, combining `[1, 2, 3]` and `['a', 'b']` should result in `[(1, 'a'), (2, 'b'),... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1624,
"level": 1,
"question": "Write a Python function that combines two lists into one, with each element from the two lists paired together as tuples. If one list is longer than the other, append the remaining elements as is. For example, combining `[1, 2, 3]` and `['a', 'b']` sho... |
from collections import Counter
def calculate_probabilities(lst):
if not lst:
return {}
counts = Counter(lst)
total = len(lst)
return {num: count / total for num, count in counts.items()} | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the probabilities of each element in a list. The list contains integer values and the probabilities should be calculated as the ratio of each number's occurrences to the total number of elements in the list.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1625,
"level": 1,
"question": "Write a python function to calculate the probabilities of each element in a list. The list contains integer values and the probabilities should be calculated as the ratio of each number's occurrences to the total number of elements in the list.",
"sp... |
def separate_and_sort(s):
letters = []
numbers = []
for c in s:
if c.isalpha():
letters.append(c)
elif c.isdigit():
numbers.append(c)
# Sort letters case-insensitively
letters.sort(key=lambda x: x.lower())
# Sort numbers by their integer value
numbers.... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that receives a string containing letters and numbers. The function should separate the letters and numbers into two individual strings, sort both strings (with letters sorted alphabetically and numbers sorted in ascending order), and then concatenate them, returning th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1626,
"level": 1,
"question": "Write a function that receives a string containing letters and numbers. The function should separate the letters and numbers into two individual strings, sort both strings (with letters sorted alphabetically and numbers sorted in ascending order), and ... |
def rotate_image(matrix):
if not matrix:
return
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse() | simplelr_Algorithm | [
{
"content": "Question:\n### Rotate Image by 90 Degrees\n\n#### Problem Statement\n\nGiven an `n x n` 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You need to perform this rotation in-place, meaning you should directly modify the input matrix without using extra memory for anothe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1627,
"level": 1,
"question": "### Rotate Image by 90 Degrees\n\n#### Problem Statement\n\nGiven an `n x n` 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You need to perform this rotation in-place, meaning you should directly modify the input matrix wi... |
def filter_elements(arr):
return [value for index, value in enumerate(arr) if index % 2 == 0 and value > 2] | simplelr_Filter | [
{
"content": "Question:\nHere are the instructions:\nGiven an array of integers, implement a function that returns a new array with all elements that are greater than 2 and are in the odd positions in the given array (1-indexed).\nUse list comprehension and the enumerate function to solve this problem.\nAnswer:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1628,
"level": 1,
"question": "Here are the instructions:\nGiven an array of integers, implement a function that returns a new array with all elements that are greater than 2 and are in the odd positions in the given array (1-indexed).\nUse list comprehension and the enumerate funct... |
from typing import List
def insert_into_min_heap(heap: List[int], value: int) -> List[int]:
# Add the new value to the end of the heap
heap.append(value)
# Start from the last element
i = len(heap) - 1
# Sift up the element to maintain the heap property
while i > 0:
parent = (i - 1) // ... | simplelr_Algorithm | [
{
"content": "Question:\n**Title**: Implement a Min-Heap Insertion Function\n\n**Objective**: Write a function to insert a given integer into a min-heap and maintain the min-heap property.\n\n**Function Signature**:\n```python\ndef insert_into_min_heap(heap: List[int], value: int) -> List[int]:\n pass\n```\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1629,
"level": 1,
"question": "**Title**: Implement a Min-Heap Insertion Function\n\n**Objective**: Write a function to insert a given integer into a min-heap and maintain the min-heap property.\n\n**Function Signature**:\n```python\ndef insert_into_min_heap(heap: List[int], value: ... |
def isMountainArray(array):
n = len(array)
if n < 3:
return "NO"
i = 0
# Climb up the mountain to find the peak
while i < n - 1 and array[i] < array[i + 1]:
i += 1
# Check if the peak is at the first or last position
if i == 0 or i == n - 1:
return "NO"
... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes in a list of integers and returns a string indicating whether the list is a valid \"mountain array\". A mountain array is defined as an array that:\n\n1. Has at least 3 elements.\n2. There exists some index i (0 < i < len(array) - 1) such that:\n - `array[0... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1630,
"level": 1,
"question": "Write a function that takes in a list of integers and returns a string indicating whether the list is a valid \"mountain array\". A mountain array is defined as an array that:\n\n1. Has at least 3 elements.\n2. There exists some index i (0 < i < len(ar... |
def longest_mountain(arr):
n = len(arr)
if n < 3:
return 0
left = [1] * n
for i in range(1, n):
if arr[i] > arr[i-1]:
left[i] = left[i-1] + 1
else:
left[i] = 1
right = [1] * n
for i in range(n-2, -1, -1):
if arr[i] > arr[i+1]:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `arr`. A **mountain subarray** is a subarray that includes at least three elements and satisfies the following condition: there exists some index `k` with `0 < k < length of subarray - 1` such that:\n\n- arr[k] > arr[k-1]\n- arr[k] > arr[k+1]\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1631,
"level": 1,
"question": "You are given a **0-indexed** integer array `arr`. A **mountain subarray** is a subarray that includes at least three elements and satisfies the following condition: there exists some index `k` with `0 < k < length of subarray - 1` such that:\n\n- arr[... |
from typing import List
def find_unique_user_id(log_entries: List[int]) -> int:
result = 0
for num in log_entries:
result ^= num
return result | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are assigned a task to analyze logs from a security system. Each log entry corresponds to an activity by a user represented by an integer userID. In this list, every userID appears twice, except for one userID which appears only once. You need to efficiently identify t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1632,
"level": 1,
"question": "### Scenario\nYou are assigned a task to analyze logs from a security system. Each log entry corresponds to an activity by a user represented by an integer userID. In this list, every userID appears twice, except for one userID which appears only once.... |
from typing import List, Tuple, Dict
def categorize_foods(foods: List[Tuple[str, int]]) -> Dict[str, str]:
low = []
medium = []
high = []
for name, calories in foods:
if calories <= 200:
low.append(name)
elif 201 <= calories <= 500:
medium.append(name)
el... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context\nYou are working for a company that builds software for dietary analysis. One required feature is to categorize foods based on their calorie counts and then generate a summary of categories as strings. Your task is to implement this feature... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1633,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context\nYou are working for a company that builds software for dietary analysis. One required feature is to categorize foods based on their calorie counts and then generate a summary of categories as strings. You... |
def generate_fibonacci(n):
# Check if n is a non-negative integer and not a boolean
if not (isinstance(n, int) and type(n) is int and n >= 0):
raise ValueError("Input must be a non-negative integer.")
if n == 0:
return []
elif n == 1:
return [0]
else:
fib = [0, 1... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that generates the Fibonacci sequence up to a given number of elements. The function should be written in Python, and it should return a list containing the sequence. The function should also include error handling to ensure that the input is a non-negative integer.\nA... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1634,
"level": 1,
"question": "Create a function that generates the Fibonacci sequence up to a given number of elements. The function should be written in Python, and it should return a list containing the sequence. The function should also include error handling to ensure that the ... |
def to_lowercase_and_check_palindrome(s):
lower_str = s.lower()
is_palindrome = lower_str == lower_str[::-1]
return (lower_str, is_palindrome) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an input of a string and converts all the characters to lowercase. Then, it should check if the resulting string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. The function s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1635,
"level": 1,
"question": "Create a function that takes an input of a string and converts all the characters to lowercase. Then, it should check if the resulting string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters which reads the same ... |
from typing import List
def allocate_tasks(n: int, m: int, preferences: List[List[int]]) -> List[int]:
available = set(range(1, n + 1))
allocation = []
for intern in preferences:
task = 0
for t in intern:
if t in available:
task = t
available.remo... | simplelr_Codeforces | [
{
"content": "Question:\nA company has ‘m’ interns who can accomplish daily tasks individually. Every day the interns are available at the start of the day to choose their tasks, and each task can only be handled by one intern at a time. There are ‘n’ tasks available each day. \n\nThe company has an allocation ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1636,
"level": 1,
"question": "A company has ‘m’ interns who can accomplish daily tasks individually. Every day the interns are available at the start of the day to choose their tasks, and each task can only be handled by one intern at a time. There are ‘n’ tasks available each day.... |
def num_decodings(s: str) -> int:
if not s:
return 0
n = len(s)
if s[0] == '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 '1' <= s[i-1] <= '9':
dp[i] += dp[i... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Problem Statement\n\nYou are given a non-negative integer. Your task is to write a function that returns the number of ways to decode it, as per the traditional mapping used in encoding messages, where 'A' = 1, 'B' = 2, ..., 'Z' = 26 (i.e., '1' -> ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1637,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Problem Statement\n\nYou are given a non-negative integer. Your task is to write a function that returns the number of ways to decode it, as per the traditional mapping used in encoding messages, where 'A' = 1, 'B... |
def repeat_each_char(input_str, n):
if n == 0 or not input_str:
return ''
return ''.join([char * n for char in input_str])
| simplelr_Taco | [
{
"content": "Question:\nYou are given a string of characters and a non-negative integer `n`. Your task is to implement the function `repeat_each_char(input_str, n)`, which returns a new string where each character in the input string is repeated `n` times.\n\nFor example, if the input string is \"abc\" and `n`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1638,
"level": 1,
"question": "You are given a string of characters and a non-negative integer `n`. Your task is to implement the function `repeat_each_char(input_str, n)`, which returns a new string where each character in the input string is repeated `n` times.\n\nFor example, if ... |
def bubble_sort(lst):
arr = lst.copy()
swap_count = 0
n = len(arr)
for i in range(n - 1):
swapped = False
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swap_count += 1
swapped = True
... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns the list sorted in ascending order using the bubble sort algorithm. Additionally, the function should count and return the number of swaps made during the sorting process.\nAnswer:\nLet's think step by step.\n",
"role": "use... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1639,
"level": 1,
"question": "Write a function that takes a list of integers and returns the list sorted in ascending order using the bubble sort algorithm. Additionally, the function should count and return the number of swaps made during the sorting process.",
"split": "train"
... |
def array_diff(list1: list[int], list2: list[int]) -> list[int]:
set2 = set(list2)
result = []
for num in list1:
if num not in set2:
result.append(num)
return result | simplelr_Algorithm | [
{
"content": "Question:\n### Array Difference Function\n\nYou are tasked with writing a function that takes two lists of integers and returns a list of integers that are present in the first list but not in the second.\n\n#### Function Signature\n```python\ndef array_diff(list1: list[int], list2: list[int]) -> ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1640,
"level": 1,
"question": "### Array Difference Function\n\nYou are tasked with writing a function that takes two lists of integers and returns a list of integers that are present in the first list but not in the second.\n\n#### Function Signature\n```python\ndef array_diff(list... |
def length_of_longest_substring(s):
last_seen = {}
start = 0
max_length = 0
for i, char in enumerate(s):
if char in last_seen and last_seen[char] >= start:
start = last_seen[char] + 1
last_seen[char] = i
current_length = i - start + 1
if current_length > max_l... | simplelr_Leetcode | [
{
"content": "Question:\nWrite a function that receives a string containing lowercase English letters and returns the length of the longest substring with all distinct characters. For example, given the input \"abcabcbb\", the output should be 3 because the longest substring with all distinct characters is \"ab... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1641,
"level": 1,
"question": "Write a function that receives a string containing lowercase English letters and returns the length of the longest substring with all distinct characters. For example, given the input \"abcabcbb\", the output should be 3 because the longest substring w... |
import numpy as np
def evaluate_matrix(A: np.ndarray) -> np.ndarray:
return np.sign(A) | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function `evaluate_matrix` that evaluates the elements of a given 2D matrix `A` and replaces its elements according to specific conditions. The function will:\n\n1. Accept parameter: a 2D NumPy array `A`.\n2. Iterate through each element `A[i, j]` of the arra... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1642,
"level": 1,
"question": "You are required to write a function `evaluate_matrix` that evaluates the elements of a given 2D matrix `A` and replaces its elements according to specific conditions. The function will:\n\n1. Accept parameter: a 2D NumPy array `A`.\n2. Iterate through... |
from typing import List
def custom_exchange_sort(arr: List[int]) -> List[int]:
for i in range(len(arr)):
min_val = arr[i]
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < min_val:
min_val = arr[j]
min_index = j
if min_index != i:... | simplelr_Data_Structure | [
{
"content": "Question:\n## Problem Statement\n\nYou are given an unsorted list of integers. Your task is to implement a function `custom_exchange_sort` that sorts the list in ascending order using the Exchange Sort algorithm. However, the challenge is to modify the traditional Exchange Sort to minimize the num... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1643,
"level": 1,
"question": "## Problem Statement\n\nYou are given an unsorted list of integers. Your task is to implement a function `custom_exchange_sort` that sorts the list in ascending order using the Exchange Sort algorithm. However, the challenge is to modify the traditiona... |
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for _ in range(2, n + 1):
c = a + b
a = b
b = c
return b | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the Fibonacci number at a given position in the sequence without using recursion. The solution should be efficient for large numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1644,
"level": 1,
"question": "Write a function to calculate the Fibonacci number at a given position in the sequence without using recursion. The solution should be efficient for large numbers.",
"split": "train"
} |
from collections import deque
def tail(file_path, n=10):
with open(file_path, 'r') as f:
lines = deque(f, maxlen=n)
return ''.join(lines) | simplelr_Evol | [
{
"content": "Question:\nWrite a function that emulates a UNIX `tail` command, which outputs the last 10 lines of a text file. Your function should accept two parameters: the file path and the number of lines to output (defaulting to 10 if not specified). You must ensure the function efficiently handles large f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1645,
"level": 1,
"question": "Write a function that emulates a UNIX `tail` command, which outputs the last 10 lines of a text file. Your function should accept two parameters: the file path and the number of lines to output (defaulting to 10 if not specified). You must ensure the f... |
def remove_duplicates(input_list):
seen = set()
unique_list = []
for num in input_list:
if num not in seen:
seen.add(num)
unique_list.append(num)
return unique_list | simplelr_Filter | [
{
"content": "Question:\nWrite a function to remove all duplicates from a given list of integers and return a list of the unique elements. The order of the elements in the returned list should be the same as their first occurrence in the input list. Additionally, the function should be efficient in terms of tim... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1646,
"level": 1,
"question": "Write a function to remove all duplicates from a given list of integers and return a list of the unique elements. The order of the elements in the returned list should be the same as their first occurrence in the input list. Additionally, the function ... |
import re
from collections import Counter
def most_occuring_word(filepath: str) -> list:
with open(filepath, 'r') as f:
text = f.read()
words = re.findall(r"[a-zA-Z']+", text)
words = [word.lower() for word in words]
if not words:
return []
counts = Counter(words)
max_count = ma... | simplelr_Package | [
{
"content": "Question:\nIn this problem, you will create a function named `most_occuring_word` that reads a specified text file and returns the word that appears most frequently in the file. In the case of a tie, return all words that have the highest frequency, sorted lexicographically.\n\nThe function should... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1647,
"level": 1,
"question": "In this problem, you will create a function named `most_occuring_word` that reads a specified text file and returns the word that appears most frequently in the file. In the case of a tie, return all words that have the highest frequency, sorted lexico... |
def second_occurrence_index(arr, target):
count = 0
for index, value in enumerate(arr):
if value == target:
count += 1
if count == 2:
return index
return -1 | simplelr_Filter | [
{
"content": "Question:\nGiven an array of integers, how can I find the index of the second occurrence of a given integer in the array? If the integer does not occur at least twice, the function should return -1. Can you provide a Python function to accomplish this?\nAnswer:\nLet's think step by step.\n",
"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1648,
"level": 1,
"question": "Given an array of integers, how can I find the index of the second occurrence of a given integer in the array? If the integer does not occur at least twice, the function should return -1. Can you provide a Python function to accomplish this?",
"split... |
import numpy as np
from sklearn.decomposition import IncrementalPCA
def incremental_pca_transform(data_path: str, n_components: int, batch_size: int) -> np.ndarray:
"""
Perform Incremental PCA on a large dataset stored in a memory-mapped file.
Parameters:
- data_path (str): Path to the memory-mapped f... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\nImplement a function that leverages Incremental PCA to reduce the dimensionality of a large dataset that does not fit into memory all at once. This will test your understanding of both the core PCA concept and the practical application of Incremental PCA for handling lar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1649,
"level": 1,
"question": "#### Objective\nImplement a function that leverages Incremental PCA to reduce the dimensionality of a large dataset that does not fit into memory all at once. This will test your understanding of both the core PCA concept and the practical application ... |
def reverse_string(s):
# Collect all alphabetic characters from the string
letters = [c for c in s if c.isalpha()]
reversed_letters = letters[::-1]
# Create an iterator for the reversed letters
reversed_iter = iter(reversed_letters)
# Build the result string
result = []
for c i... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse a string in Python. The function should also ensure that the reversed string maintains the case of each character and only reverses alphabetic characters while ignoring non-alphabetic characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1650,
"level": 1,
"question": "Write a function to reverse a string in Python. The function should also ensure that the reversed string maintains the case of each character and only reverses alphabetic characters while ignoring non-alphabetic characters.",
"split": "train"
} |
def count_occurrences(string, char):
return string.count(char) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string and a character as input, and returns the count of occurrences of the character in the string. The function should be case-sensitive.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1651,
"level": 1,
"question": "Create a function that takes a string and a character as input, and returns the count of occurrences of the character in the string. The function should be case-sensitive.",
"split": "train"
} |
def length_of_longest_substring_two_distinct(s):
char_count = {}
max_length = 0
left = 0
for right in range(len(s)):
c = s[right]
char_count[c] = char_count.get(c, 0) + 1
# Shrink the window from the left if there are more than two distinct characters
while len(c... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `str` containing only lowercase alphabets. Your task is to find the length of the longest substring that contains at most two distinct characters. Return _the length of the longest substring_.\n\nExample:\n```plaintext\nInput: str = \"abcba\"\nOutput: 3\nExplanati... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1652,
"level": 1,
"question": "You are given a string `str` containing only lowercase alphabets. Your task is to find the length of the longest substring that contains at most two distinct characters. Return _the length of the longest substring_.\n\nExample:\n```plaintext\nInput: st... |
def calculate_fibonacci(n):
if n < 0:
raise ValueError("n must be a non-negative integer")
elif n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for i in range(2, n + 1):
next_val = a + b
a = b
b = next_val
return b | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function named `calculate_fibonacci` that computes the n-th element of the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence goes like this: 0, 1, 1, 2, 3, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1653,
"level": 1,
"question": "Write a Python function named `calculate_fibonacci` that computes the n-th element of the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The seque... |
import torch
def optimize_matrix_multiplication(tensor_a: torch.Tensor, tensor_b: torch.Tensor) -> torch.Tensor:
# Check if CUDA is available and configure backends if so
if torch.cuda.is_available():
torch.backends.cuda.matmul.allow_tf32 = True # Enable TensorFloat-32
torch.backends.cudnn.ena... | simplelr_Docs | [
{
"content": "Question:\n**Objective:**\nCreate a PyTorch function that optimizes a tensor operation by leveraging available backends and their configurations.\n\n**Problem Statement:**\nImplement a function `optimize_matrix_multiplication` in PyTorch that performs matrix multiplication between two given tensor... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1654,
"level": 1,
"question": "**Objective:**\nCreate a PyTorch function that optimizes a tensor operation by leveraging available backends and their configurations.\n\n**Problem Statement:**\nImplement a function `optimize_matrix_multiplication` in PyTorch that performs matrix mult... |
def max_product_of_three(nums):
nums.sort()
return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1])
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers, write a method to return the maximum product of any three numbers from the array.\n\nFor example:\n\n```\n[1, 10, 2, 6, 5, 3] ==> 300\n```\n\nIn this example, the maximum product of any three numbers (10, 6, 5) is 300.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1655,
"level": 1,
"question": "Given an array of integers, write a method to return the maximum product of any three numbers from the array.\n\nFor example:\n\n```\n[1, 10, 2, 6, 5, 3] ==> 300\n```\n\nIn this example, the maximum product of any three numbers (10, 6, 5) is 300.",
"... |
def merge_sorted_arrays(array1, array2):
i = 0
j = 0
result = []
while i < len(array1) and j < len(array2):
if array1[i] < array2[j]:
result.append(array1[i])
i += 1
else:
result.append(array2[j])
j += 1
result += array1[i:]
result ... | simplelr_Apps | [
{
"content": "Question:\nWrite a function `merge_sorted_arrays(array1, array2)` that takes two sorted arrays of integers and returns a single sorted array that contains all the elements of `array1` and `array2`. The resulting array should also be sorted in ascending order. You may assume that neither array cont... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1656,
"level": 1,
"question": "Write a function `merge_sorted_arrays(array1, array2)` that takes two sorted arrays of integers and returns a single sorted array that contains all the elements of `array1` and `array2`. The resulting array should also be sorted in ascending order. You... |
def merge_and_sort_lists(list1, list2):
return sorted(set(list1 + list2)) | simplelr_Package | [
{
"content": "Question:\n**Problem Statement:**\n\nYour task is to create a function `merge_and_sort_lists` which takes two lists of integers and returns a merged list that is sorted in ascending order. The function should ensure that the resulting list contains only unique integers.\n\n**Input:**\n- `list1`: A... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1657,
"level": 1,
"question": "**Problem Statement:**\n\nYour task is to create a function `merge_and_sort_lists` which takes two lists of integers and returns a merged list that is sorted in ascending order. The function should ensure that the resulting list contains only unique in... |
from typing import List
def longest_consecutive_subsequence_length(arr: List[int]) -> int:
if not arr:
return 0
num_set = set(arr)
max_length = 0
for num in arr:
if (num - 1) not in num_set:
current_length = 1
next_num = num + 1
while next_num in num_... | simplelr_Evol | [
{
"content": "Question:\nImplement a function `longest_consecutive_subsequence_length(arr)` that takes an array of integers `arr` and returns the length of the longest consecutive elements sequence.\n\n**Function Signature:**\n```python\ndef longest_consecutive_subsequence_length(arr: List[int]) -> int:\n```\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1658,
"level": 1,
"question": "Implement a function `longest_consecutive_subsequence_length(arr)` that takes an array of integers `arr` and returns the length of the longest consecutive elements sequence.\n\n**Function Signature:**\n```python\ndef longest_consecutive_subsequence_len... |
def reverse_complement_and_double(s):
# Create a translation table for complementary bases
translation_table = str.maketrans('ATCG', 'TAGC')
# Translate each base to its complement
complement = s.translate(translation_table)
# Reverse the complemented string to get the reverse complement
reverse... | simplelr_Filter | [
{
"content": "Question:\nGiven a DNA sequence, reverse complement the DNA molecules by creating an opposite and complementary base pairing sequence:\n\nA pairs with T\nC pairs with G\n\nThen, take the reversed sequence and double it.\n\nHow would you do it programmatically in Python?\nAnswer:\nLet's think step ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1659,
"level": 1,
"question": "Given a DNA sequence, reverse complement the DNA molecules by creating an opposite and complementary base pairing sequence:\n\nA pairs with T\nC pairs with G\n\nThen, take the reversed sequence and double it.\n\nHow would you do it programmatically in ... |
from collections import Counter
def are_anagrams(s1, s2):
if len(s1) != len(s2):
return False
return Counter(s1) == Counter(s2) | simplelr_Filter | [
{
"content": "Question:\nWhat is the most efficient way to check if two strings are anagrams in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1660,
"level": 1,
"question": "What is the most efficient way to check if two strings are anagrams in Python?",
"split": "train"
} |
def find_oldest_person(people):
if not people:
return None
oldest = people[0]
for person in people[1:]:
if person['age'] > oldest['age']:
oldest = person
return oldest | simplelr_Filter | [
{
"content": "Question:\nI have an object that contains a list of dictionaries where each dictionary represents a person with their name and age. I want to write a function that finds the oldest person in the list.\n\nHere is my object:\n```python\npeople = [\n {\"name\": \"John\", \"age\": 25},\n {\"name... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1661,
"level": 1,
"question": "I have an object that contains a list of dictionaries where each dictionary represents a person with their name and age. I want to write a function that finds the oldest person in the list.\n\nHere is my object:\n```python\npeople = [\n {\"name\": \... |
def binary_to_decimal(binary_str):
return int(binary_str, 2) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert a given string from binary to decimal. The binary string will only contain '1's and '0's.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1662,
"level": 1,
"question": "Write a python function to convert a given string from binary to decimal. The binary string will only contain '1's and '0's.",
"split": "train"
} |
def min_sum_subarray(arr):
if not arr:
return None
current_min = global_min = arr[0]
for num in arr[1:]:
current_min = min(num, current_min + num)
if current_min < global_min:
global_min = current_min
return global_min | simplelr_Filter | [
{
"content": "Question:\n### Our task is to implement a function `min_sum_subarray` in Python that calculates the minimum sum of a subarray within a given 1D array of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1663,
"level": 1,
"question": "### Our task is to implement a function `min_sum_subarray` in Python that calculates the minimum sum of a subarray within a given 1D array of integers.",
"split": "train"
} |
def first_unique_char(s: str) -> str:
counts = [0] * 26
for char in s:
counts[ord(char) - ord('a')] += 1
for char in s:
if counts[ord(char) - ord('a')] == 1:
return char
return "" | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n**Context:**\nData streams are commonplace in many real-world applications, and efficiently processing a continuous flow of data entries is a valuable skill. One of the fundamental tasks in handling data streams is identifying unique elements in the str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1664,
"level": 1,
"question": "### Coding Assessment Question\n\n**Context:**\nData streams are commonplace in many real-world applications, and efficiently processing a continuous flow of data entries is a valuable skill. One of the fundamental tasks in handling data streams is ide... |
def shortest_subsequence_with_k_distinct(sequence: str, k: int) -> int:
distinct_count = len(set(sequence))
if distinct_count >= k:
return k
else:
return -1 | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\n\nGiven a string `sequence` and an integer `k`, your task is to find the length of the shortest subsequence of `sequence` that contains at least `k` distinct characters. If no such subsequence exists, return -1.\n\n### Requirements:\n- You are to write a function... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1665,
"level": 1,
"question": "### Problem Statement:\n\nGiven a string `sequence` and an integer `k`, your task is to find the length of the shortest subsequence of `sequence` that contains at least `k` distinct characters. If no such subsequence exists, return -1.\n\n### Requireme... |
from collections import deque
def shortest_path(graph: dict, start: str, end: str) -> list:
if start not in graph or end not in graph:
return []
if start == end:
return [start]
queue = deque([start])
visited = {start}
parent = {}
found = False
while queue and not f... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n**Objective**: Evaluate candidates' ability to work with graph data structures, particularly in traversal and shortest path algorithms.\n\n**Background**:\nGraphs are a fundamental data structure used in various domains, including social networks, web l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1666,
"level": 1,
"question": "### Coding Assessment Question\n\n**Objective**: Evaluate candidates' ability to work with graph data structures, particularly in traversal and shortest path algorithms.\n\n**Background**:\nGraphs are a fundamental data structure used in various domain... |
def length_of_longest_substring(s):
char_index = {} # Dictionary to store the last index of each character
max_length = 0
start = 0 # Start of the current window
for end in range(len(s)):
char = s[end]
# If the character is in the dictionary and its last index is >= start, move the st... | simplelr_Taco | [
{
"content": "Question:\nGiven a string that consists of lowercase letters and possibly spaces, determine the length of the longest substring without repeating characters.\n\nWrite a function that takes a single string input and returns an integer representing the length of the longest substring without repeati... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1667,
"level": 1,
"question": "Given a string that consists of lowercase letters and possibly spaces, determine the length of the longest substring without repeating characters.\n\nWrite a function that takes a single string input and returns an integer representing the length of th... |
def maximize_tasks(tasks: list[tuple[int, int]]) -> int:
# Sort tasks based on their end times
sorted_tasks = sorted(tasks, key=lambda x: x[1])
count = 0
last_end = 0 # Initialize with 0 since task start times are non-negative
for task in sorted_tasks:
start, end = task
if star... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Task Scheduling Optimization\n\n**Scenario**: Imagine you are tasked with optimizing a task scheduling system where multiple tasks need to be scheduled without an overlap. Each task has a start time and an end time, and you need to allocate these tasks in such a way that m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1668,
"level": 1,
"question": "### Question: Task Scheduling Optimization\n\n**Scenario**: Imagine you are tasked with optimizing a task scheduling system where multiple tasks need to be scheduled without an overlap. Each task has a start time and an end time, and you need to alloca... |
def move_zeroes(nums):
writePointer = 0
n = len(nums)
for i in range(n):
if nums[i] != 0:
nums[writePointer] = nums[i]
writePointer += 1
for j in range(writePointer, n):
nums[j] = 0 | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums`, move all zeros to the end of the array while maintaining the relative order of the non-zero elements. Implement a function that modifies the array in-place and returns nothing. For example, given `nums = [0, 1, 0, 3, 12]`, your function should modify `nums... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1669,
"level": 1,
"question": "Given an integer array `nums`, move all zeros to the end of the array while maintaining the relative order of the non-zero elements. Implement a function that modifies the array in-place and returns nothing. For example, given `nums = [0, 1, 0, 3, 12]`... |
def list_intersection(list_a: list, list_b: list) -> list:
"""
:param list_a: a list of numbers
:param list_b: a list of numbers
:return: a list containing the unique elements that are present in both list_a and list_b in the order of their first occurrence in list_a
Raises:
TypeError: If e... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given two lists of integers. Your task is to implement a function that finds the intersection of these two lists. The intersection of two lists is a new list that contains only the elements that are present in both lists. The elements in the intersection... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1670,
"level": 1,
"question": "### Problem Statement\n\nYou are given two lists of integers. Your task is to implement a function that finds the intersection of these two lists. The intersection of two lists is a new list that contains only the elements that are present in both list... |
def string_length(s):
return len(s) | simplelr_Filter | [
{
"content": "Question:\nCan you explain how to create a simple function in Python that returns the length of a given string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1671,
"level": 1,
"question": "Can you explain how to create a simple function in Python that returns the length of a given string?",
"split": "train"
} |
import math
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True | simplelr_Filter | [
{
"content": "Question:\nCreate a Python code snippet for a function that checks if a given number is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1672,
"level": 1,
"question": "Create a Python code snippet for a function that checks if a given number is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.",
"split": "train"
} |
def find_first_decreasing_index(sequence):
for i in range(1, len(sequence)):
if sequence[i] < sequence[i-1]:
return i
return -1 | simplelr_Filter | [
{
"content": "Question:\nGiven a sequence of numbers, write a Python function that finds and returns the index of the first element in the sequence that is smaller than its predecessor. If all elements are in non-decreasing order, the function should return -1. The function should be efficient and concise.\nAns... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1673,
"level": 1,
"question": "Given a sequence of numbers, write a Python function that finds and returns the index of the first element in the sequence that is smaller than its predecessor. If all elements are in non-decreasing order, the function should return -1. The function sh... |
from typing import Union, List
def validate_password(password: str) -> Union[bool, List[str]]:
errors = []
# Check password length
if len(password) < 8:
errors.append("Password must be at least 8 characters long")
# Check for at least one uppercase letter
if not any(c.isupper() fo... | simplelr_Algorithm | [
{
"content": "Question:\nPassword Strength Validator\n\n#### Objective\nCreate a `validate_password` function that checks if a given password is strong based on specific criteria. The function should also suggest improvements if the password does not meet the criteria.\n\n#### Problem Statement\nA strong passwo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1674,
"level": 1,
"question": "Password Strength Validator\n\n#### Objective\nCreate a `validate_password` function that checks if a given password is strong based on specific criteria. The function should also suggest improvements if the password does not meet the criteria.\n\n####... |
def count_odd_numbers(n):
count = 0
for i in range(n):
if i % 2 != 0:
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\ndef count_odd_numbers(n):\n count = 0\n for i in range(n):\n if i % 2 != 0:\n count += 1\n return count\n\nprint(count_odd_numbers(10))\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1675,
"level": 1,
"question": "def count_odd_numbers(n):\n count = 0\n for i in range(n):\n if i % 2 != 0:\n count += 1\n return count\n\nprint(count_odd_numbers(10))",
"split": "train"
} |
def factorial(n):
if n < 0:
return -1
elif n == 0:
return 1
else:
return n * factorial(n - 1) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the factorial of a number. The function should take an integer as input and return the factorial of that number. If the input is less than 0, the function should return -1 to indicate an invalid input. The factorial of 0 is defined to be 1. Use recursion to... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1676,
"level": 1,
"question": "Write a function to calculate the factorial of a number. The function should take an integer as input and return the factorial of that number. If the input is less than 0, the function should return -1 to indicate an invalid input. The factorial of 0 i... |
import fnmatch
def search_files(file_tags: dict, pattern: str) -> list:
result = set()
for filename, tags in file_tags.items():
for tag in tags:
if fnmatch.fnmatch(tag, pattern):
result.add(filename)
break
return sorted(result)
| simplelr_Docs | [
{
"content": "Question:\n**Problem Statement:**\n\nYou are developing a file management system where users can tag their files with different labels. You need to implement a search functionality that allows users to find files based on patterns in their tags, using Unix shell-style wildcards.\n\nImplement a fun... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1677,
"level": 1,
"question": "**Problem Statement:**\n\nYou are developing a file management system where users can tag their files with different labels. You need to implement a search functionality that allows users to find files based on patterns in their tags, using Unix shell-... |
from collections import defaultdict
def find_duplicates(nums):
counts = defaultdict(int)
for num in nums:
counts[num] += 1
result = [k for k, v in counts.items() if v > 1]
result.sort()
return result
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, write a function to find all such elements in the list which appear strictly more than once and return these elements sorted in ascending order. If no such element is found, return an empty list.\n\nYour solution should be efficient in terms of both time and sp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1678,
"level": 1,
"question": "Given a list of integers, write a function to find all such elements in the list which appear strictly more than once and return these elements sorted in ascending order. If no such element is found, return an empty list.\n\nYour solution should be eff... |
def extract_unique_elements(input_list):
seen = {}
unique_list = []
for element in input_list:
if element not in seen:
seen[element] = True
unique_list.append(element)
return unique_list | simplelr_Filter | [
{
"content": "Question:\nDevelop a Python function that iterates through a given list and extracts the unique elements, maintaining their original sequence. This must be achieved without the aid of in-built list functions for uniqueness.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1679,
"level": 1,
"question": "Develop a Python function that iterates through a given list and extracts the unique elements, maintaining their original sequence. This must be achieved without the aid of in-built list functions for uniqueness.",
"split": "train"
} |
def banking_operations(transactions):
current_balance = 0.0
results = []
for operation, amount in transactions:
if operation == 'deposit':
current_balance += amount
elif operation == 'withdrawal':
if current_balance >= amount:
current_balance -= amount... | simplelr_Package | [
{
"content": "Question:\nDevelop a function that simulates a basic banking system where a user can perform deposit, withdrawal, and balance inquiry operations. The function should take a list of transactions as input, where each transaction is represented by a tuple of the form (operation, amount). The operatio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1680,
"level": 1,
"question": "Develop a function that simulates a basic banking system where a user can perform deposit, withdrawal, and balance inquiry operations. The function should take a list of transactions as input, where each transaction is represented by a tuple of the for... |
def find_kth_largest(nums: list, k: int) -> int:
sorted_nums = sorted(nums, reverse=True)
return sorted_nums[k-1] | simplelr_Evol | [
{
"content": "Question:\nYou are given an unsorted integer array and an integer `k`. Write a function to find the k-th largest element in the array. Your solution should have a time complexity of O(n log n).\n\ndef find_kth_largest(nums: list, k: int):\n \"\"\"\n find_kth_largest(nums, k) takes a list of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1681,
"level": 1,
"question": "You are given an unsorted integer array and an integer `k`. Write a function to find the k-th largest element in the array. Your solution should have a time complexity of O(n log n).\n\ndef find_kth_largest(nums: list, k: int):\n \"\"\"\n find_kt... |
def prime_factors(n: int) -> list[int]:
if n < 2:
raise ValueError("n must be greater than or equal to 2")
factors = []
# Handle the factor 2 separately
while n % 2 == 0:
factors.append(2)
n = n // 2
# Now n must be odd, start from 3
i = 3
while i * i <= n:
wh... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement: Optimized Prime Factorization\n\nDesign a function to compute the prime factorization of an integer `n` using an efficient algorithm. The function should handle edge cases, ensure optimal performance for large `n`, and correctly manage system resources.\n\n### Req... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1682,
"level": 1,
"question": "### Problem Statement: Optimized Prime Factorization\n\nDesign a function to compute the prime factorization of an integer `n` using an efficient algorithm. The function should handle edge cases, ensure optimal performance for large `n`, and correctly ... |
def binary_search(nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1 | simplelr_Filter | [
{
"content": "Question:\nYou are given a sorted array of distinct integers and a target value.\n\nReturn the index if the target value is found in the array, otherwise return -1.\n\nYou must write an algorithm with O(log n) runtime complexity.\n\n Example:\n\n```\nInput: nums = [-1,0,3,5,9,12], target = 9\nOutp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1683,
"level": 1,
"question": "You are given a sorted array of distinct integers and a target value.\n\nReturn the index if the target value is found in the array, otherwise return -1.\n\nYou must write an algorithm with O(log n) runtime complexity.\n\n Example:\n\n```\nInput: nums ... |
from typing import List
def maximize_units_sold(prices: List[int], budget: int) -> int:
min_price = min(prices)
return budget // min_price | simplelr_Codeforces | [
{
"content": "Question:\nYou are managing an online store and preparing for a big sale event. You have a list of products with their respective prices, and you want to maximize the number of units sold given a budget. Each product can be bought multiple times as long as the budget allows.\n\nWrite a function `m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1684,
"level": 1,
"question": "You are managing an online store and preparing for a big sale event. You have a list of products with their respective prices, and you want to maximize the number of units sold given a budget. Each product can be bought multiple times as long as the bu... |
def convert_users_to_dict(users):
return {user["id"]: {"name": user["name"], "email": user["email"]} for user in users} | simplelr_Filter | [
{
"content": "Question:\nI have an API that returns a list of objects, each object representing a user with a unique id, name, and email. Here is the response from the API:\n\n```\n[\n {\n \"id\": 1,\n \"name\": \"John Doe\",\n \"email\": \"john@example.com\"\n },\n {\n \"id\": 2,\n \"name\": ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1685,
"level": 1,
"question": "I have an API that returns a list of objects, each object representing a user with a unique id, name, and email. Here is the response from the API:\n\n```\n[\n {\n \"id\": 1,\n \"name\": \"John Doe\",\n \"email\": \"john@example.com\"\n },\n... |
from collections import Counter
def process_items(items):
if not items:
return {}
total = len(items)
counts = Counter(items)
result = {}
for num in counts:
count = counts[num]
percentage = (count / total) * 100
result[num] = {'count': count, 'percentage': percentage}... | simplelr_Filter | [
{
"content": "Question:\nGiven a Python function `process_items`, which takes a list of integers and returns a dictionary with the frequency of each integer, how can I modify this function to also include the percentage of the total count that each integer represents? Additionally, please ensure the function ha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1686,
"level": 1,
"question": "Given a Python function `process_items`, which takes a list of integers and returns a dictionary with the frequency of each integer, how can I modify this function to also include the percentage of the total count that each integer represents? Addition... |
def longest_common_subsequence(str1: str, str2: str) -> int:
m = len(str1)
n = len(str2)
# Create a table with (m+1) rows and (n+1) columns, initialized to zero
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i-1] == str... | simplelr_Algorithm | [
{
"content": "Question:\n### Longest Common Subsequence Problem with Dynamic Programming\n\n#### Objective\nGiven two strings, write a function to find the length of their longest common subsequence using dynamic programming to optimize the solution.\n\n#### Implementation Requirements\n* Implement a function `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1687,
"level": 1,
"question": "### Longest Common Subsequence Problem with Dynamic Programming\n\n#### Objective\nGiven two strings, write a function to find the length of their longest common subsequence using dynamic programming to optimize the solution.\n\n#### Implementation Req... |
def find_subsets(nums):
subsets = [[]]
for num in nums:
subsets += [curr + [num] for curr in subsets]
return subsets | simplelr_Filter | [
{
"content": "Question:\ndef find_subsets(nums):\n subsets = [[]]\n for num in nums:\n subsets += [curr + [num] for curr in subsets]\n return subsets\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1688,
"level": 1,
"question": "def find_subsets(nums):\n subsets = [[]]\n for num in nums:\n subsets += [curr + [num] for curr in subsets]\n return subsets",
"split": "train"
} |
def reverse_list(lst):
return lst[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to return a reversed copy of a given list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1689,
"level": 1,
"question": "Write a python function to return a reversed copy of a given list.",
"split": "train"
} |
def first_non_repeating_character(s):
# Create a dictionary to hold the frequency of each character
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
# Iterate through the string again to find the first non-repeating character
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the first non-repeating character in a given string and return its index. If all characters are repeating, return -1. The function should have a time complexity of O(n), where n is the length of the string.\nAnswer:\nLet's think step by step.\n",
"rol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1690,
"level": 1,
"question": "Write a Python function to find the first non-repeating character in a given string and return its index. If all characters are repeating, return -1. The function should have a time complexity of O(n), where n is the length of the string.",
"split": ... |
def stem_word(word, stem_type):
xu_rules = [
("daxu", "xu"), ("maxu", "xu"), ("raxu", "xu"), ("saxu", "xu"),
("xu", ""), ("sa", ""), ("xo", "u")
]
iq_rules = [
("daq", "iq"), ("maq", "iq"), ("niq", "iq"), ("raq", "iq"),
("siq", "iq"), ("u", ""), ("n", "i")
]
if s... | simplelr_Filter | [
{
"content": "Question:\nStemming is a form of word normalization that reduces words to their base or dictionary form, usually by removing suffixes. Different languages have different stemming algorithms. Here is a dictionary for a hypothetical language with two stems, \"xu\" or \"iq\", where the suffix rule... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1691,
"level": 1,
"question": "Stemming is a form of word normalization that reduces words to their base or dictionary form, usually by removing suffixes. Different languages have different stemming algorithms. Here is a dictionary for a hypothetical language with two stems, \"xu... |
def char_frequency(s):
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
return counts | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to count the frequency of each character in a given string. The function should return a dictionary where keys are characters and values are their respective counts.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1692,
"level": 1,
"question": "Write a Python function to count the frequency of each character in a given string. The function should return a dictionary where keys are characters and values are their respective counts.",
"split": "train"
} |
def multiplication_table():
rows = []
for i in range(1, 10):
row = '\t'.join(str(i * j) for j in range(1, 10))
rows.append(row)
return '\n'.join(rows) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that generates a multiplication table for numbers from 1 to 9. The function should return the table as a string, with each row of the table separated by a newline character and each product separated by a tab character.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1693,
"level": 1,
"question": "Write a Python function that generates a multiplication table for numbers from 1 to 9. The function should return the table as a string, with each row of the table separated by a newline character and each product separated by a tab character.",
"spl... |
def length_of_longest_substring(s):
last_seen = {}
max_length = 0
start = 0
for i, c in enumerate(s):
if c in last_seen and last_seen[c] >= start:
start = last_seen[c] + 1
last_seen[c] = i
current_length = i - start + 1
if current_length > max_length:
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string `s` as input and returns the length of the longest substring of `s` that does not contain any repeating characters. If `s` is empty or does not contain any unique characters, the function should return 0.\nAnswer:\nLet's think step by step.\n"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1694,
"level": 1,
"question": "Write a Python function that takes a string `s` as input and returns the length of the longest substring of `s` that does not contain any repeating characters. If `s` is empty or does not contain any unique characters, the function should return 0.",
... |
def rotate(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i+1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse()
| simplelr_Taco | [
{
"content": "Question:\nGiven a square matrix `matrix`, write a function to rotate the matrix to the right by 90 degrees in-place. The rotation must be achieved without utilizing any extra space for another matrix to hold the rotated values, i.e., it should be done with constant space complexity.\n\nThe functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1695,
"level": 1,
"question": "Given a square matrix `matrix`, write a function to rotate the matrix to the right by 90 degrees in-place. The rotation must be achieved without utilizing any extra space for another matrix to hold the rotated values, i.e., it should be done with const... |
def maxScore(cards, k):
n = len(cards)
prefix = [0] * (n + 1)
for i in range(1, n + 1):
prefix[i] = prefix[i-1] + cards[i-1]
suffix = [0] * (n + 1)
current_sum = 0
for i in range(1, n + 1):
current_sum += cards[n - i]
suffix[i] = current_sum
max_score = 0
... | simplelr_Apps | [
{
"content": "Question:\nYou are given an array of integers cards where cards[i] represents the value of the ith card. You are also given an integer k indicating the number of cards you can draw from the deck. In each turn, you can choose to draw one card from either the beginning or the end of the deck and add... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1696,
"level": 1,
"question": "You are given an array of integers cards where cards[i] represents the value of the ith card. You are also given an integer k indicating the number of cards you can draw from the deck. In each turn, you can choose to draw one card from either the begin... |
def reverse_number(n):
if n < 0:
sign = -1
num = abs(n)
else:
sign = 1
num = n
reversed_str = str(num)[::-1]
reversed_num = int(reversed_str)
return sign * reversed_num | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes an integer as input and returns the integer with its digits reversed. If the number is negative, ensure that the negative sign remains at the front of the reversed number. For example:\n\n```python\nreverse_number(123) == 321\nreverse_number(-456) == -654\nre... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1697,
"level": 1,
"question": "Write a function that takes an integer as input and returns the integer with its digits reversed. If the number is negative, ensure that the negative sign remains at the front of the reversed number. For example:\n\n```python\nreverse_number(123) == 32... |
from datetime import datetime, timedelta
def business_days_between(start_date: str, end_date: str) -> int:
start = datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.strptime(end_date, "%Y-%m-%d")
business_days = 0
current_date = start
while current_date <= end:
if current_d... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function related to date and time operations using the `datetime` library in Python. Specifically, you need to create a function `business_days_between(start_date, end_date)` that calculates the number of business days between two given dates, excluding weeke... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1698,
"level": 1,
"question": "You are required to write a function related to date and time operations using the `datetime` library in Python. Specifically, you need to create a function `business_days_between(start_date, end_date)` that calculates the number of business days betwe... |
from typing import List
def max_difference(arr: List[int]) -> int:
if len(arr) < 2:
return -1
min_so_far = arr[0]
max_diff = -1
for num in arr[1:]:
if num > min_so_far:
current_diff = num - min_so_far
if current_diff > max_diff:
max_diff... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nA tech startup is developing a smart application for monitoring the health metrics of its users. One of the key features involves analyzing the variations in the users' heart rates over a certain period. Part of this task requires calculating the maximum difference between ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1699,
"level": 1,
"question": "### Context\nA tech startup is developing a smart application for monitoring the health metrics of its users. One of the key features involves analyzing the variations in the users' heart rates over a certain period. Part of this task requires calculat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.