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 decode(arr, first):
res = [first]
for num in arr:
next_val = res[-1] ^ num
res.append(next_val)
return res | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `arr` representing the encoded numbers, and an integer `first`, return _the original array as an integer array_. The encoded array is created using the following rule:\n\n encoded[i] = arr[i] XOR arr[i + 1]\n\nYour task is to decode the array and provide the or... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1900,
"level": 1,
"question": "Given an integer array `arr` representing the encoded numbers, and an integer `first`, return _the original array as an integer array_. The encoded array is created using the following rule:\n\n encoded[i] = arr[i] XOR arr[i + 1]\n\nYour task is to ... |
def lower_words(words):
return [word for word in words if word[0].islower()] | simplelr_Filter | [
{
"content": "Question:\nThis is a coding challenge.\n\n **Challenge:**\n\n Write a function that takes a list of strings as input (`words`) and returns a new list containing only the words that start with a lowercase letter.\n\n\n **Examples:**\n\n ```\n lower_words([\"Hello\", \"world\", \"python\", \"IS\", \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1901,
"level": 1,
"question": "This is a coding challenge.\n\n **Challenge:**\n\n Write a function that takes a list of strings as input (`words`) and returns a new list containing only the words that start with a lowercase letter.\n\n\n **Examples:**\n\n ```\n lower_words([\"Hello\... |
def count_partitions(n: int) -> int:
if n == 0:
return 1 # As per the definition, though the problem states n >=1
dp = [0] * (n + 1)
dp[0] = 1 # Base case
for i in range(1, n + 1):
sum_p = 0
m = 1
while True:
g = m * (3 * m - 1) // 2
if... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are working on a combinatorial problem related to counting partitions. A partition of a positive integer \\( n \\) is a way of writing \\( n \\) as a sum of positive integers. Two sums that differ only in the order of their addends are considered the same partition. Yo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1902,
"level": 1,
"question": "### Scenario\nYou are working on a combinatorial problem related to counting partitions. A partition of a positive integer \\( n \\) is a way of writing \\( n \\) as a sum of positive integers. Two sums that differ only in the order of their addends ar... |
def normalize_and_sort_unicode(input_file: str, output_file: str) -> None:
import unicodedata
try:
with open(input_file, 'r', encoding='utf-8') as f:
content = f.read()
normalized_content = unicodedata.normalize('NFC', content)
sorted_characters = sorted(normalized_content,... | simplelr_Docs | [
{
"content": "Question:\n### Advanced Unicode Handling in Python\n\n**Objective**: The goal of this task is to implement a function that demonstrates advanced handling of Unicode strings in Python. The function should read a text file containing Unicode text, normalize the text, and then write it to a new file ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1903,
"level": 1,
"question": "### Advanced Unicode Handling in Python\n\n**Objective**: The goal of this task is to implement a function that demonstrates advanced handling of Unicode strings in Python. The function should read a text file containing Unicode text, normalize the tex... |
def sum_multiples(inputList, multiple):
if multiple == 0:
return 0
total = 0
for num in inputList:
if num % multiple == 0:
total += num
return total
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns the sum of all integers that are multiples of a given integer.\n\nThe function should accept a list of integers (inputList) and a single integer (multiple) as parameters. It should return the sum of all the numbers in the list t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1904,
"level": 1,
"question": "Write a function that takes a list of integers and returns the sum of all integers that are multiples of a given integer.\n\nThe function should accept a list of integers (inputList) and a single integer (multiple) as parameters. It should return the s... |
import bisect
def kthSmallest(mat, k):
if not mat or not mat[0]:
return None # Handle empty matrix case
m = len(mat)
n = len(mat[0])
low = mat[0][0]
high = mat[-1][-1]
while low < high:
mid = (low + high) // 2
count = 0
for row in mat:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a matrix `mat` of size `m x n` and an integer `k`, write an algorithm to find the `k-th` smallest element in the matrix. Each row and column of the matrix is sorted in ascending order. Note that it is the `k-th` smallest element _in the sorted order_, not the `k-th` distinct eleme... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1905,
"level": 1,
"question": "Given a matrix `mat` of size `m x n` and an integer `k`, write an algorithm to find the `k-th` smallest element in the matrix. Each row and column of the matrix is sorted in ascending order. Note that it is the `k-th` smallest element _in the sorted or... |
def is_grid_fully_covered(rows: int, cols: int, objects: list) -> bool:
covered = set()
for obj in objects:
for cell in obj:
covered.add(cell)
required = set((r, c) for r in range(rows) for c in range(cols))
uncovered = required - covered
if not uncovered:
retur... | simplelr_Algorithm | [
{
"content": "Question:\n## Matrix Coverage Check\n\n### Context\n\nYou are working on a grid-based game where you need to manage different objects placed on an MxN grid. A common requirement is to check if all cells in the grid are covered by objects. Each object can be represented as a list of cells it covers... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1906,
"level": 1,
"question": "## Matrix Coverage Check\n\n### Context\n\nYou are working on a grid-based game where you need to manage different objects placed on an MxN grid. A common requirement is to check if all cells in the grid are covered by objects. Each object can be repre... |
import re
def convert_string_to_int_list(s):
numbers = re.findall(r'[-+]?\d+\.?\d*|[-+]?\.\d+', s)
int_list = []
for num in numbers:
if '.' in num:
continue
int_list.append(int(num))
return int_list | simplelr_Filter | [
{
"content": "Question:\nPlease provide a Python function that converts a string of space-separated numbers into a list of integers. The function should be able to handle any number of numbers in the string and should ignore any non-numeric characters between the numbers. For example, the string \"12 abc 34.5 5... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1907,
"level": 1,
"question": "Please provide a Python function that converts a string of space-separated numbers into a list of integers. The function should be able to handle any number of numbers in the string and should ignore any non-numeric characters between the numbers. For ... |
def print_documentation(func):
"""
Prints the docstring of the given function or method.
If no docstring is available, it informs the user.
"""
if func.__doc__:
print(func.__doc__)
else:
print("No documentation available for this function.")
# Example usage:
print_documentation(... | simplelr_Filter | [
{
"content": "Question:\nHow can I create a function in Python that automatically prints the documentation of any given function or method?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1908,
"level": 1,
"question": "How can I create a function in Python that automatically prints the documentation of any given function or method?",
"split": "train"
} |
def list_length(lst):
count = 0
for _ in lst:
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list as an argument and returns the length of the list. Your function should not use the built-in `len()` function.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1909,
"level": 1,
"question": "Write a Python function that takes a list as an argument and returns the length of the list. Your function should not use the built-in `len()` function.",
"split": "train"
} |
from typing import List
def canSegmentString(s: str, words: List[str]) -> bool:
word_set = set(words)
if not word_set:
return len(s) == 0
max_len = max(len(w) for w in word_set)
n = len(s)
dp = [False] * (n + 1)
dp[0] = True # An empty string is a valid segment
for i in range(1, n ... | simplelr_Apps | [
{
"content": "Question:\nGiven a string `s` and a list of words `words`, determine if `s` can be segmented into a space-separated sequence of one or more dictionary words from `words`. Return True if possible, otherwise return False.\n\nExample:\n```\ns = \"leetcode\"\nwords = [\"leet\", \"code\"]\nOutput: True... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1910,
"level": 1,
"question": "Given a string `s` and a list of words `words`, determine if `s` can be segmented into a space-separated sequence of one or more dictionary words from `words`. Return True if possible, otherwise return False.\n\nExample:\n```\ns = \"leetcode\"\nwords =... |
def find_books(books, search_criteria):
result = []
for book in books:
if all(book.get(key) == value for key, value in search_criteria.items()):
result.append(book['title'])
return result | simplelr_Apps | [
{
"content": "Question:\nYou are tasked with developing a function for a book cataloging application. Your function will take in a list of dictionaries representing books and a dictionary representing specific search criteria. The function should return a list of titles of the books that match all of the provid... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1911,
"level": 1,
"question": "You are tasked with developing a function for a book cataloging application. Your function will take in a list of dictionaries representing books and a dictionary representing specific search criteria. The function should return a list of titles of the... |
def minimum_moves(initial, target):
total = 0
for i in range(4):
c = int(initial[i])
t = int(target[i])
diff = abs(c - t)
total += min(diff, 10 - diff)
return total | simplelr_Code_Contests | [
{
"content": "Question:\nThe problem you need to solve is finding a locked combination with the minimum number of moves. There are 4 wheels (each marked with numbers from 0 to 9, inclusive) on a lock, and you are given the initial position of each wheel as a 4-digit string. You aim to achieve the target positio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1912,
"level": 1,
"question": "The problem you need to solve is finding a locked combination with the minimum number of moves. There are 4 wheels (each marked with numbers from 0 to 9, inclusive) on a lock, and you are given the initial position of each wheel as a 4-digit string. Yo... |
def canConstruct(s: str, words: list) -> bool:
if not s:
return True # Although per problem statement, s is non-empty
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
for i in range(n + 1):
if dp[i]:
for word in words:
word_len = len(word)
i... | simplelr_Taco | [
{
"content": "Question:\nWrite a Python function to check if a string can be constructed using words from a given list of words. Each word in the list can be used multiple times. The function should return True if the string can be constructed, and False otherwise.\n\nInput:\nThe function will receive two input... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1913,
"level": 1,
"question": "Write a Python function to check if a string can be constructed using words from a given list of words. Each word in the list can be used multiple times. The function should return True if the string can be constructed, and False otherwise.\n\nInput:\n... |
from collections import deque
def is_merge(s: str, part1: str, part2: str) -> bool:
len_s = len(s)
len_p1 = len(part1)
len_p2 = len(part2)
if len_p1 + len_p2 != len_s:
return False
if len_p1 == 0:
return part2 == s
if len_p2 == 0:
return part1 == s
# I... | simplelr_Data_Structure | [
{
"content": "Question:\n### Interactive String Merge Validation\n\nIn this task, you will implement a function to determine if a given string `s` can be formed by merging characters from two strings `part1` and `part2` such that their characters are in the same order as in `s`.\n\n#### Function Signature\n```p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1914,
"level": 1,
"question": "### Interactive String Merge Validation\n\nIn this task, you will implement a function to determine if a given string `s` can be formed by merging characters from two strings `part1` and `part2` such that their characters are in the same order as in `s... |
def count_unique_characters(s):
lower_s = s.lower()
unique_chars = set(lower_s)
return len(unique_chars) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to count the number of unique characters in a given string. The function should return the count of distinct characters, ignoring case sensitivity. For example, the string \"HelloWorld\" should return 7, as there are 7 unique characters ('H', 'e', 'l', 'o', 'W', 'r', 'd... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1915,
"level": 1,
"question": "Write a function to count the number of unique characters in a given string. The function should return the count of distinct characters, ignoring case sensitivity. For example, the string \"HelloWorld\" should return 7, as there are 7 unique character... |
def is_unique_peak_journey(arr):
n = len(arr)
if n < 3:
return False
# Find the peak where the sequence stops increasing
i = 0
while i < n - 1 and arr[i] < arr[i + 1]:
i += 1
# Peak cannot be the first or last element
if i == 0 or i == n - 1:
return False
... | simplelr_Code_Contests | [
{
"content": "Question:\nMarina loves hiking and she has a collection of GPS tracks of her adventurous journeys. Each track is represented by an array of positive integers where each integer indicates the altitude at different points along the journey. Marina noticed a peculiar pattern in some of her journeys —... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1916,
"level": 1,
"question": "Marina loves hiking and she has a collection of GPS tracks of her adventurous journeys. Each track is represented by an array of positive integers where each integer indicates the altitude at different points along the journey. Marina noticed a peculia... |
def removeKdigits(num, k):
stack = []
for d in num:
while k > 0 and stack and stack[-1] > d:
stack.pop()
k -= 1
stack.append(d)
if k > 0:
stack = stack[:-k] if len(stack) > k else []
res = ''.join(stack).lstrip('0')
return res if res else '0' | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `num` representing a **non-negative integer** and a positive integer `k`. You are allowed to remove up to `k` digits from `num` to form a new number, which should be the **smallest possible**. Return _the smallest number_ that can be formed by removing up to `k` d... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1917,
"level": 1,
"question": "You are given a string `num` representing a **non-negative integer** and a positive integer `k`. You are allowed to remove up to `k` digits from `num` to form a new number, which should be the **smallest possible**. Return _the smallest number_ that ca... |
def min_subarrays(s):
if not s:
return 0
count = 1
for i in range(1, len(s)):
if s[i] != s[i-1]:
count += 1
return count
| simplelr_Taco | [
{
"content": "Question:\nThere are several types of fruits in a basket, each type represented by a lowercase English letter. Given a string representing the basket's fruits, determine the minimum number of subarrays needed to group the identical fruits together. A subarray is a contiguous subsequence of the arr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1918,
"level": 1,
"question": "There are several types of fruits in a basket, each type represented by a lowercase English letter. Given a string representing the basket's fruits, determine the minimum number of subarrays needed to group the identical fruits together. A subarray is ... |
def find_anagrams(s, target):
target_len = len(target)
s_len = len(s)
result = []
if target_len == 0 or s_len == 0 or target_len > s_len:
return result
target_counts = [0] * 26
for c in target:
target_counts[ord(c) - ord('a')] += 1
window_counts = [0] * 26
... | simplelr_Filter | [
{
"content": "Question:\nGiven a string containing only lowercase letters, find all anagrams of a given target string.\n\nExample 1:\nInput: s = \"abab\", target = \"ab\"\nOutput: [0, 1]\nExplanation: The anagrams of \"ab\" in \"abab\" start at indices 0 and 1.\n\nExample 2:\nInput: s = \"abcd\", target = \"cd\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1919,
"level": 1,
"question": "Given a string containing only lowercase letters, find all anagrams of a given target string.\n\nExample 1:\nInput: s = \"abab\", target = \"ab\"\nOutput: [0, 1]\nExplanation: The anagrams of \"ab\" in \"abab\" start at indices 0 and 1.\n\nExample 2:\n... |
def count_characters(s):
char_dict = {}
for char in s:
char_lower = char.lower()
if char_lower == ' ':
continue
if char_lower in char_dict:
char_dict[char_lower] += 1
else:
char_dict[char_lower] = 1
return char_dict | simplelr_Filter | [
{
"content": "Question:\nCreate a function in Python that takes a string and returns a dictionary with the count of each character in the string, ignoring case and excluding spaces.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1920,
"level": 1,
"question": "Create a function in Python that takes a string and returns a dictionary with the count of each character in the string, ignoring case and excluding spaces.",
"split": "train"
} |
def find_index(lst, num):
try:
return lst.index(num)
except ValueError:
return -1 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes 3 inputs, a list, and an integer. Check if the integer exists in the list. If it does, return its index. If it doesn't, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1921,
"level": 1,
"question": "Create a function that takes 3 inputs, a list, and an integer. Check if the integer exists in the list. If it does, return its index. If it doesn't, return -1.",
"split": "train"
} |
def all_even(numbers):
return all(num % 2 == 0 for num in numbers) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if all the numbers in a list are even. If so, return `True`. Otherwise, return `False`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1922,
"level": 1,
"question": "Create a function that checks if all the numbers in a list are even. If so, return `True`. Otherwise, return `False`.",
"split": "train"
} |
def max_product_of_two(nums):
sorted_nums = sorted(nums)
product1 = sorted_nums[-1] * sorted_nums[-2]
product2 = sorted_nums[0] * sorted_nums[1]
return max(product1, product2) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an input array and returns the maximum product of any two distinct numbers in the array. The array will have at least two numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1923,
"level": 1,
"question": "Create a function that takes an input array and returns the maximum product of any two distinct numbers in the array. The array will have at least two numbers.",
"split": "train"
} |
def is_prime(n: int) -> bool:
"""
Check if a number is a prime number.
Args:
n (int): The number to check for primality.
Returns:
bool: True if n is a prime number, False otherwise.
Raises:
ValueError: If n is not an integer or is a negative integer.
E... | simplelr_Docs | [
{
"content": "Question:\n### Question: Testing Interactive Examples in Docstrings with `doctest`\n\nYou are tasked with creating a module that includes a function and its corresponding docstring examples. You will then write code to automatically test these examples using the `doctest` module.\n\n#### 1. Functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1924,
"level": 1,
"question": "### Question: Testing Interactive Examples in Docstrings with `doctest`\n\nYou are tasked with creating a module that includes a function and its corresponding docstring examples. You will then write code to automatically test these examples using the ... |
def count_decodings(encoded_message):
s = encoded_message
n = len(s)
if n == 0:
return 0 # Though per constraints, this case shouldn't occur
dp = [0] * (n + 1)
dp[0] = 1 # Base case: empty string has one way to be decoded
for i in range(1, n + 1):
# Check for single digit
... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nYou are tasked with designing a function that decodes messages encoded as number sequences where each number corresponds to a letter (1 -> 'A', 2 -> 'B', ..., 26 -> 'Z'). Given the mapping rules, the function should return the total number of ways the input number sequenc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1925,
"level": 1,
"question": "#### Scenario\nYou are tasked with designing a function that decodes messages encoded as number sequences where each number corresponds to a letter (1 -> 'A', 2 -> 'B', ..., 26 -> 'Z'). Given the mapping rules, the function should return the total numb... |
def rank_players(scores):
# Accumulate scores into a dictionary
score_dict = {}
for name, score in scores:
if name in score_dict:
score_dict[name] += score
else:
score_dict[name] = score
# Convert the dictionary into a list of (name, total) tuples
players... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nA text-based game needs to keep track of player scores over several rounds, and it must rank the players based on their cumulative scores. Your task is to implement the ranking logic. The system should take player names and their scores as input and return the players rank... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1926,
"level": 1,
"question": "### Scenario\nA text-based game needs to keep track of player scores over several rounds, and it must rank the players based on their cumulative scores. Your task is to implement the ranking logic. The system should take player names and their scores a... |
def is_palindrome(lst):
return lst == lst[::-1] | simplelr_Filter | [
{
"content": "Question:\nObjective: To implement a program in Python that takes a list of integers as input and determines if it is a palindrome.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1927,
"level": 1,
"question": "Objective: To implement a program in Python that takes a list of integers as input and determines if it is a palindrome.",
"split": "train"
} |
def find_max(arr):
if not arr:
return None
max_value = arr[0]
for num in arr[1:]:
if num > max_value:
max_value = num
return max_value | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the maximum value in a given array without using the built-in `max()` function. You can use basic programming constructs such as loops and conditionals.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1928,
"level": 1,
"question": "Write a function to find the maximum value in a given array without using the built-in `max()` function. You can use basic programming constructs such as loops and conditionals.",
"split": "train"
} |
def most_frequent_element(input_list):
# Check if input is a list
if not isinstance(input_list, list):
raise TypeError("Input must be a list.")
# Check all elements are integers and of type int
for element in input_list:
if type(element) is not int:
raise ValueError("All... | simplelr_Evol | [
{
"content": "Question:\nDesign a Python function named 'most_frequent_element' that takes a list of integers as input and returns the integer that appears most frequently in the list. If there are multiple integers with the same highest frequency, return the smallest one. Handle potential exceptions such as in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1929,
"level": 1,
"question": "Design a Python function named 'most_frequent_element' that takes a list of integers as input and returns the integer that appears most frequently in the list. If there are multiple integers with the same highest frequency, return the smallest one. Han... |
def transform_string(sentence: str) -> str:
trans_map = {
'A': 'B',
'B': 'C',
'C': 'A',
'a': 'b',
'b': 'c',
'c': 'a'
}
result = []
for c in sentence:
result.append(trans_map.get(c, c))
return ''.join(result) | simplelr_Apps | [
{
"content": "Question:\n---\n# Background\n\nYou have recently joined a programming class and have to complete a series of exercises on string manipulation in Python. For one of the exercises, you need to write a program that transforms strings according to a set of rules.\n\n# Rules\nSpecific letters in the s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1930,
"level": 1,
"question": "---\n# Background\n\nYou have recently joined a programming class and have to complete a series of exercises on string manipulation in Python. For one of the exercises, you need to write a program that transforms strings according to a set of rules.\n\... |
from typing import List
def rotate_image(matrix: List[List[int]]) -> None:
"""
Rotates the given MxN matrix by 90 degrees clockwise in place.
Args:
matrix (List[List[int]]): An MxN list of lists representing the image.
"""
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
retur... | simplelr_Evol | [
{
"content": "Question:\n**Given an image represented as an MxN matrix of pixel values, design a function in Python to perform a clockwise rotation of the image by 90 degrees. Your function should modify the matrix in place and not use any additional matrix or list for the transformation.**\n\n### Requirements:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1931,
"level": 1,
"question": "**Given an image represented as an MxN matrix of pixel values, design a function in Python to perform a clockwise rotation of the image by 90 degrees. Your function should modify the matrix in place and not use any additional matrix or list for the tra... |
def rearrange_string(s: str) -> str:
letters = []
digits = []
specials = []
for c in s:
if c.isalpha():
letters.append(c)
elif c.isdigit():
digits.append(c)
else:
specials.append(c)
letters_sorted = sorted(letters)
digits_sorted = sorte... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given a string containing alphanumeric characters and special characters (`!`, `@`, `#`, `$`, `%`, `^`, `&`, `*`). Your task is to rearrange the string so that all letters appear in alphabetical order, followed by all digits in numerical order, and final... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1932,
"level": 1,
"question": "### Problem Statement\n\nYou are given a string containing alphanumeric characters and special characters (`!`, `@`, `#`, `$`, `%`, `^`, `&`, `*`). Your task is to rearrange the string so that all letters appear in alphabetical order, followed by all d... |
def find_unique_integer(arr: list) -> int:
unique = 0
for num in arr:
unique ^= num
return unique | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge\n\n#### Context:\nYou are given a sequence of integers where each integer appears twice except for one unique integer that appears only once.\n\n#### Objective:\nWrite a function `find_unique_integer(arr: List[int]) -> int` that takes a list of integers and returns ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1933,
"level": 1,
"question": "### Coding Challenge\n\n#### Context:\nYou are given a sequence of integers where each integer appears twice except for one unique integer that appears only once.\n\n#### Objective:\nWrite a function `find_unique_integer(arr: List[int]) -> int` that ta... |
def calculate_salary(hourly_wage, hours_worked):
return hourly_wage * hours_worked | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the total salary for an employee based on their hourly wage and the number of hours worked. The function should take two parameters: `hourly_wage` (a float representing the employee's hourly wage) and `hours_worked` (an integer representing the numbe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1934,
"level": 1,
"question": "Write a python function to calculate the total salary for an employee based on their hourly wage and the number of hours worked. The function should take two parameters: `hourly_wage` (a float representing the employee's hourly wage) and `hours_worked`... |
def reverse_digits(n):
return str(n)[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to print the digits of a given integer in reverse order. For example, if the input is 432, the output should be '234'. Assume the input will always be a positive integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1935,
"level": 1,
"question": "Write a python function to print the digits of a given integer in reverse order. For example, if the input is 432, the output should be '234'. Assume the input will always be a positive integer.",
"split": "train"
} |
def unique_paths_with_obstacles(grid):
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
# Check if the start or end is blocked
if grid[0][0] == 1 or grid[m-1][n-1] == 1:
return 0
# Initialize DP table
dp = [[0]*n for _ in range(m)]
dp[0][0] = 1 # Starting poi... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a grid where each cell is initially either empty (`0`) or filled with an obstacle (`1`). You need to find the number of unique paths from the top-left cell (grid[0][0]) to the bottom-right cell (grid[m-1][n-1]), but the path must avoid obstacles. You can only move either d... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1936,
"level": 1,
"question": "You are given a grid where each cell is initially either empty (`0`) or filled with an obstacle (`1`). You need to find the number of unique paths from the top-left cell (grid[0][0]) to the bottom-right cell (grid[m-1][n-1]), but the path must avoid ob... |
def longest_common_subsequence(s1, s2):
m = len(s1)
n = len(s2)
# Create a matrix with (m+1) rows and (n+1) columns, initialized to zero
matrix = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with writing a Python function `longest_common_subsequence` that finds the longest common subsequence between two strings. The function should return the length of this subsequence.\n\nThe function `longest_common_subsequence` should:\n1. Take two arguments `s1` and `s2`,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1937,
"level": 1,
"question": "You are tasked with writing a Python function `longest_common_subsequence` that finds the longest common subsequence between two strings. The function should return the length of this subsequence.\n\nThe function `longest_common_subsequence` should:\n1... |
def is_form_valid(form):
return len(set(form)) == len(form) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to determine if a particular form is valid or not. The form is defined using a string where each character represents a different field. The function should check if the form is valid, i.e., it should not have any repeating fields (characters).\nAnswer:\nLet's think ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1938,
"level": 1,
"question": "Write a function to determine if a particular form is valid or not. The form is defined using a string where each character represents a different field. The function should check if the form is valid, i.e., it should not have any repeating fields (cha... |
from typing import List
def rotate_matrix(matrix: List[List[int]]) -> None:
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_Package | [
{
"content": "Question:\nYou are required to develop a function `rotate_matrix(matrix: List[List[int]]) -> None` which performs an in-place rotation of a given NxN matrix by 90 degrees in the clockwise direction.\n\nHere are the steps your function needs to perform:\n1. Transpose the matrix: Convert all rows to... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1939,
"level": 1,
"question": "You are required to develop a function `rotate_matrix(matrix: List[List[int]]) -> None` which performs an in-place rotation of a given NxN matrix by 90 degrees in the clockwise direction.\n\nHere are the steps your function needs to perform:\n1. Transp... |
def is_submatrix(matrix, submatrix):
# Handle the case where the submatrix is empty
if not submatrix or not submatrix[0]:
return True
rows_matrix = len(matrix)
if rows_matrix == 0:
return False # Main matrix is empty but submatrix is non-empty
cols_matrix = len(matrix[0])
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to determine if a given 2D array is a submatrix of another 2D array. The function should take two 2D arrays as input and return `True` if the second array is a submatrix of the first, and `False` otherwise.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1940,
"level": 1,
"question": "Write a function to determine if a given 2D array is a submatrix of another 2D array. The function should take two 2D arrays as input and return `True` if the second array is a submatrix of the first, and `False` otherwise.",
"split": "train"
} |
def longest_contiguous_subarray(arr):
if not arr:
return 0
max_deque = []
min_deque = []
left = 0
max_len = 0
for right in range(len(arr)):
# Update max_deque
while max_deque and arr[right] >= max_deque[-1][0]:
max_deque.pop()
max_deque.appen... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr`, find and return the length of the longest contiguous subarray where the absolute difference between any two elements of the subarray is less than or equal to `1`. Use a sliding window technique to optimize the search for the longest subarray satisfying ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1941,
"level": 1,
"question": "Given an array of integers `arr`, find and return the length of the longest contiguous subarray where the absolute difference between any two elements of the subarray is less than or equal to `1`. Use a sliding window technique to optimize the search f... |
from collections import defaultdict
def findWealthiestUser(transactions):
balances = defaultdict(int)
for sender, receiver, amount in transactions:
balances[sender] -= amount
balances[receiver] += amount
max_balance = float('-inf')
wealthiest_user = None
for user_id, balance in... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of transactions made by users in an online marketplace. Each transaction is represented as a tuple (sender_id, receiver_id, amount), where sender_id and receiver_id are unique user identifiers and amount is the transaction amount. Your task is to identify the user w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1942,
"level": 1,
"question": "You are given a list of transactions made by users in an online marketplace. Each transaction is represented as a tuple (sender_id, receiver_id, amount), where sender_id and receiver_id are unique user identifiers and amount is the transaction amount. ... |
import time
def simulate_drone_delivery(grid_size, speed_per_second, power_consumption, deliveries):
x, y = 0.0, 0.0
battery_level = 100.0
distance_traveled = 0.0
deliveries_made = 0
current_delivery_index = 0
total_deliveries = len(deliveries)
while current_delivery_index < total_deli... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with simulating a delivery drone making deliveries in a city grid. Each second, the program will update and display the current status of the delivery, such as the drone's position, remaining battery, number of deliveries made, and distance traveled. The simulation should... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1943,
"level": 1,
"question": "You are tasked with simulating a delivery drone making deliveries in a city grid. Each second, the program will update and display the current status of the delivery, such as the drone's position, remaining battery, number of deliveries made, and dista... |
import numpy as np
def min_max_normalize(input_vector: np.ndarray) -> np.ndarray:
"""
This function normalizes a 1-D numpy array to the range [0, 1] using Min-Max normalization.
Parameters:
input_vector (np.ndarray): A 1-D numpy array of real numbers.
Returns:
np.ndarray: The ... | simplelr_Algorithm | [
{
"content": "Question:\nData Normalization for Machine Learning\n\nData normalization is a crucial step in preparing data for machine learning models. One common method is Min-Max normalization, which scales the data to a specified range [0, 1]. Your task is to write a Python function that normalizes a given 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1944,
"level": 1,
"question": "Data Normalization for Machine Learning\n\nData normalization is a crucial step in preparing data for machine learning models. One common method is Min-Max normalization, which scales the data to a specified range [0, 1]. Your task is to write a Python... |
def is_one_edit(s: str, t: str) -> bool:
len_s, len_t = len(s), len(t)
if len_s == len_t:
# Check for substitution case
diff = 0
for a, b in zip(s, t):
if a != b:
diff += 1
if diff > 1:
return False
return diff ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Context\nYou are tasked with building a spell checker that suggests words which are a single edit distance apart from the input word. \n\n### Task\n\nWrite a Python function `is_one_edit` that takes two strings `s` and `t`, and returns `True` if they are one edit distance apart (one... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1945,
"level": 1,
"question": "### Context\nYou are tasked with building a spell checker that suggests words which are a single edit distance apart from the input word. \n\n### Task\n\nWrite a Python function `is_one_edit` that takes two strings `s` and `t`, and returns `True` if th... |
def decode_string(s: str) -> str:
stack = []
current_str = ''
current_num = 0
for char in s:
if char.isdigit():
current_num = current_num * 10 + int(char)
elif char == '[':
stack.append((current_str, current_num))
current_str = ''
curr... | simplelr_Data_Structure | [
{
"content": "Question:\n### Decoding Nested Strings\n\n#### Problem Description\nYou are given an encoded string containing nested formatting and your goal is to decode it. The encoding uses a structure where:\n- `k[encoded_string]` indicates the substring `encoded_string` is repeated `k` times.\n\nThe input s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1946,
"level": 1,
"question": "### Decoding Nested Strings\n\n#### Problem Description\nYou are given an encoded string containing nested formatting and your goal is to decode it. The encoding uses a structure where:\n- `k[encoded_string]` indicates the substring `encoded_string` is... |
def increment(n):
return n + 1 | simplelr_Filter | [
{
"content": "Question:\nI need to create a function in Python that increments an integer value by one. How can I do this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1947,
"level": 1,
"question": "I need to create a function in Python that increments an integer value by one. How can I do this?",
"split": "train"
} |
def digital_root(n):
if n == 0:
return 0
remainder = n % 9
return 9 if remainder == 0 else remainder | simplelr_Apps | [
{
"content": "Question:\n## Recursive Sum of Digits\n\nGiven a non-negative integer, you need to find the recursive sum of its digits until a single digit is obtained. The single-digit result is called the digital root.\n\n### Task\n\n* Write a function `digital_root(n)` that takes an integer `n` as input.\n* T... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1948,
"level": 1,
"question": "## Recursive Sum of Digits\n\nGiven a non-negative integer, you need to find the recursive sum of its digits until a single digit is obtained. The single-digit result is called the digital root.\n\n### Task\n\n* Write a function `digital_root(n)` that ... |
def caesar_cipher(text: str, shift: int) -> str:
"""
Shifts the characters in the input text by a specified shift value.
This function implements the Caesar cipher, a type of substitution cipher where
each letter in the plaintext is 'shifted' a certain number of places down the alphabet.
Args:
... | simplelr_Filter | [
{
"content": "Question:\nHere are the details of my problem:\nI am a computer science student and I'm trying to implement a simple Caesar cipher for educational purposes. \nHowever, I am currently stuck on the implementation details.\n\nHere's my current code:\n\n```python\ndef caesar_cipher(text: str, shift: i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1949,
"level": 1,
"question": "Here are the details of my problem:\nI am a computer science student and I'm trying to implement a simple Caesar cipher for educational purposes. \nHowever, I am currently stuck on the implementation details.\n\nHere's my current code:\n\n```python\nde... |
def bubble_sort(arr):
arr = arr.copy()
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to sort an array of integers in ascending order using a custom sorting algorithm. The function should use the Bubble Sort algorithm. Bubble Sort is a simple comparison-based algorithm that repeatedly steps through the list, compares adjacent elements in pairs and swaps ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1950,
"level": 1,
"question": "Write a function to sort an array of integers in ascending order using a custom sorting algorithm. The function should use the Bubble Sort algorithm. Bubble Sort is a simple comparison-based algorithm that repeatedly steps through the list, compares ad... |
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:\nGiven a错过ebity array nums = [-1, 0, 3, 5, 9, 12] and a target value 9, write a function to search the target in nums. If the target exists, return its index; otherwise, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1951,
"level": 1,
"question": "Given a错过ebity array nums = [-1, 0, 3, 5, 9, 12] and a target value 9, write a function to search the target in nums. If the target exists, return its index; otherwise, return -1.",
"split": "train"
} |
def is_palindrome(s):
return s == s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given word is a palindrome. A palindrome is a word that reads the same backward as forward, e.g., \"radar\". You should not ignore cases and spaces. For example, \"A man a plan a canal Panama\" is not a palindrome because of the spaces.\nAnswer:\nLet's thi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1952,
"level": 1,
"question": "Write a function to check if a given word is a palindrome. A palindrome is a word that reads the same backward as forward, e.g., \"radar\". You should not ignore cases and spaces. For example, \"A man a plan a canal Panama\" is not a palindrome because... |
def repeat_substring(s: str) -> bool:
n = len(s)
if n < 2:
return False
for d in range(1, n // 2 + 1):
if n % d != 0:
continue
k = n // d
substring = s[:d]
valid = True
for i in range(1, k):
current = s[i * d : (i + 1) * d]
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Repeated Substring Pattern Challenge\n\n**Objective**: Implement a function that determines if a given non-empty string can be constructed by repeating a substring multiple times.\n\n### Function Signature\n```python\ndef repeat_substring(s: str) -> bool:\n```\n\n#### Input\n* A sin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1953,
"level": 1,
"question": "### Repeated Substring Pattern Challenge\n\n**Objective**: Implement a function that determines if a given non-empty string can be constructed by repeating a substring multiple times.\n\n### Function Signature\n```python\ndef repeat_substring(s: str) -... |
from typing import List, Tuple
def final_position(commands: List[str]) -> Tuple[int, int]:
x, y = 0, 0
for cmd in commands:
if cmd == "UP":
y += 1
elif cmd == "DOWN":
y -= 1
elif cmd == "LEFT":
x -= 1
elif cmd == "RIGHT":
x += 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nDesign a function that calculates the final position of a robot after executing a series of movement commands. The robot starts at position `(0, 0)` on a 2D plane and can move up, down, left, or right based on the commands provided.\n\n### Requirements:\n\nImple... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1954,
"level": 1,
"question": "### Problem Statement\n\nDesign a function that calculates the final position of a robot after executing a series of movement commands. The robot starts at position `(0, 0)` on a 2D plane and can move up, down, left, or right based on the commands prov... |
def sum_of_squares(n):
if n <= 0:
return 0
return n * (n + 1) * (2 * n + 1) // 6
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `sum_of_squares(n)` that takes an integer `n` as input and returns the sum of the squares of all integers from 1 to `n`. For example, if `n = 3`, the function should return `1^2 + 2^2 + 3^2 = 14`. If `n = 0` or `n` is negative, the function should return 0.\n\n### Examp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1955,
"level": 1,
"question": "Write a function `sum_of_squares(n)` that takes an integer `n` as input and returns the sum of the squares of all integers from 1 to `n`. For example, if `n = 3`, the function should return `1^2 + 2^2 + 3^2 = 14`. If `n = 0` or `n` is negative, the fun... |
from typing import List
from collections import defaultdict
def top_k_hashtags(hashtags: List[str], k: int) -> List[str]:
if k < 0:
raise ValueError("Invalid input")
if k == 0:
return []
freq = defaultdict(int)
for hashtag in hashtags:
freq[hashtag] += 1
m = len(fr... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Question:\nYou are tasked with implementing a feature for tracking the popularity of a series of hashtags. Specifically, you need to keep track of the top `k` most frequently occurring hashtags within a given list. Each hashtag is represented as a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1956,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Question:\nYou are tasked with implementing a feature for tracking the popularity of a series of hashtags. Specifically, you need to keep track of the top `k` most frequently occurring hashtags within a given list... |
def max_min_swap(nums):
max_val = max(nums)
min_val = min(nums)
max_index = nums.index(max_val)
min_index = nums.index(min_val)
nums[max_index], nums[min_index] = nums[min_index], nums[max_index]
return nums | simplelr_Package | [
{
"content": "Question:\nIn this problem, you will work with lists and basic arithmetic operations in Python. The goal is to manipulate and perform operations on lists to solve a given problem. Below is a step-by-step explanation of the task and the function you need to write.\n\n**Task:**\n\nYou need to define... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1957,
"level": 1,
"question": "In this problem, you will work with lists and basic arithmetic operations in Python. The goal is to manipulate and perform operations on lists to solve a given problem. Below is a step-by-step explanation of the task and the function you need to write.... |
from typing import List
def ternary_search(arr: List[int], left: int, right: int, key: int) -> int:
while left <= right:
mid1 = left + (right - left) // 3
mid2 = right - (right - left) // 3
if mid1 == mid2:
if arr[mid1] == key:
return mid1
el... | simplelr_Data_Structure | [
{
"content": "Question:\n### Ternary Search Implementation Challenge\n\n#### Context\nYou have to implement a search algorithm for a software system that deals with sorted datasets. Given the constraints and to differentiate from the typical binary search, you opt to implement a Ternary Search algorithm. The im... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1958,
"level": 1,
"question": "### Ternary Search Implementation Challenge\n\n#### Context\nYou have to implement a search algorithm for a software system that deals with sorted datasets. Given the constraints and to differentiate from the typical binary search, you opt to implement... |
def unique_elements(lst):
# Create a frequency dictionary to count occurrences of each element
freq = {}
for num in lst:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
# Build the result list with elements that appear exactly once
result = []
for ... | simplelr_Evol | [
{
"content": "Question:\nCreate a function in Python that takes a list of integers and returns a new list containing only the elements that are unique in the original list (appear exactly once). Additionally, the function should maintain the original order of the elements from the input list. Write test cases t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1959,
"level": 1,
"question": "Create a function in Python that takes a list of integers and returns a new list containing only the elements that are unique in the original list (appear exactly once). Additionally, the function should maintain the original order of the elements from... |
def longest_distinct_substring(S: str) -> tuple[int, str]:
last_occurrence = {}
max_length = 0
start = 0
left = 0
for right in range(len(S)):
current_char = S[right]
if current_char in last_occurrence and last_occurrence[current_char] >= left:
left = last_occurrence[curre... | simplelr_Code_Contests | [
{
"content": "Question:\nGiven a string $S$ consisting of lowercase alphabetic characters, determine the length of the longest substring of $S$ with all distinct characters. If there are multiple such substrings with the same length, return the one that appears first.\n\nFunction Signature: `def longest_distinc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1960,
"level": 1,
"question": "Given a string $S$ consisting of lowercase alphabetic characters, determine the length of the longest substring of $S$ with all distinct characters. If there are multiple such substrings with the same length, return the one that appears first.\n\nFunct... |
def remove_duplicates(s):
seen = set()
result = []
for char in s:
if char not in seen:
result.append(char)
seen.add(char)
return ''.join(result) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove all duplicate characters from a string while maintaining the original order of the characters. Also, ensure your solution is efficient.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1961,
"level": 1,
"question": "Write a python function to remove all duplicate characters from a string while maintaining the original order of the characters. Also, ensure your solution is efficient.",
"split": "train"
} |
def findMaxLength(nums):
balance_map = {0: -1}
max_len = 0
current_balance = 0
for index, num in enumerate(nums):
current_balance += 1 if num == 1 else -1
if current_balance in balance_map:
length = index - balance_map[current_balance]
if length > max_len:
... | simplelr_Filter | [
{
"content": "Question:\nPlease provide the Python code to solve the problem of finding the longest contiguous subarray with an equal number of 0s and 1s.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1962,
"level": 1,
"question": "Please provide the Python code to solve the problem of finding the longest contiguous subarray with an equal number of 0s and 1s.",
"split": "train"
} |
def containsNearbyDuplicate(nums, k):
last_occurrence = {}
for i, num in enumerate(nums):
if num in last_occurrence:
if i - last_occurrence[num] <= k:
return True
last_occurrence[num] = i
return False | simplelr_Code_Contests | [
{
"content": "Question:\nGiven an integer array nums and an integer k, your task is to determine if there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.\n\nWrite a function `containsNearbyDuplicate` that takes in the following ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1963,
"level": 1,
"question": "Given an integer array nums and an integer k, your task is to determine if there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.\n\nWrite a function `containsNearbyDupl... |
def product_except_self(arr):
total_product = 1
for num in arr:
total_product *= num
result = []
for num in arr:
result.append(total_product // num)
return result
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers, return an array where each element at index `i` is the product of all the numbers in the original array except the one at `i`.\n\nExample 1:\nInput:\narr = [1, 2, 3, 4]\nOutput: [24, 12, 8, 6]\n\nExample 2:\nInput:\narr = [5, 3, 4, 2]\nOutput: [24, 40, 30, 60... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1964,
"level": 1,
"question": "Given an array of integers, return an array where each element at index `i` is the product of all the numbers in the original array except the one at `i`.\n\nExample 1:\nInput:\narr = [1, 2, 3, 4]\nOutput: [24, 12, 8, 6]\n\nExample 2:\nInput:\narr = [5... |
import datetime
def day_of_week(day, month, year):
date_obj = datetime.date(year, month, day)
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
return days[date_obj.weekday()] | simplelr_Code_Contests | [
{
"content": "Question:\nYou are working on a calendar application that needs to determine the day of the week for any given date in the past, present, or future. The day of the week is required to help users plan their schedules more efficiently.\n\nWrite a function that takes three integers: `day`, `month`, a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1965,
"level": 1,
"question": "You are working on a calendar application that needs to determine the day of the week for any given date in the past, present, or future. The day of the week is required to help users plan their schedules more efficiently.\n\nWrite a function that take... |
from typing import List
def binary_search(sorted_list: List[int], target: int) -> bool:
low = 0
high = len(sorted_list) - 1
while low <= high:
mid = (low + high) // 2
if sorted_list[mid] == target:
return True
elif target < sorted_list[mid]:
high = mid - 1
... | simplelr_Taco | [
{
"content": "Question:\nIn Python, a binary search algorithm is an efficient way to find an item from a sorted list of items. Assume we have a sorted list of unique integers and we want to find out if a target integer exists in the list.\n\nImplement a function `binary_search(sorted_list, target)` that perform... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1966,
"level": 1,
"question": "In Python, a binary search algorithm is an efficient way to find an item from a sorted list of items. Assume we have a sorted list of unique integers and we want to find out if a target integer exists in the list.\n\nImplement a function `binary_search... |
def words_with_both_vowels_and_consonants(sentence):
vowels = {'a', 'e', 'i', 'o', 'u'}
words = sentence.split()
result = []
for word in words:
has_vowel = False
has_consonant = False
for c in word:
if c.isalpha():
lower_c = c.lower()
i... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find all words in a sentence that contain both vowels and consonants. The function should return these words in a list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1967,
"level": 1,
"question": "Write a python function to find all words in a sentence that contain both vowels and consonants. The function should return these words in a list.",
"split": "train"
} |
def second_largest(numbers):
unique = list(set(numbers))
if len(unique) < 2:
return None
unique.sort(reverse=True)
return unique[1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers as input and returns the second largest number in the list. If the list has duplicates, the function should only consider unique elements. If the list has less than 2 unique elements, the function should return `None`.\nAnswer:\nLet's thin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1968,
"level": 1,
"question": "Create a function that takes a list of integers as input and returns the second largest number in the list. If the list has duplicates, the function should only consider unique elements. If the list has less than 2 unique elements, the function should ... |
from typing import List
def product_except_self(nums: List[int]) -> List[int]:
n = len(nums)
if n == 0:
return []
prefix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]
suffix = [1] * n
for i in range(n-2, -1, -1):
suffix[i] = suffix[i+1] * ... | simplelr_Evol | [
{
"content": "Question:\nCreate a function in programming language syntax that receives a list of integers as input and returns a new list where each element is the product of all other elements except itself in the original list, without using division.\n\ndef product_except_self(nums: List[int]) -> List[int]:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1969,
"level": 1,
"question": "Create a function in programming language syntax that receives a list of integers as input and returns a new list where each element is the product of all other elements except itself in the original list, without using division.\n\ndef product_except_... |
import torch
def nested_sequence_sums(sequences: list) -> torch.Tensor:
sums = [seq.sum() for seq in sequences]
return torch.stack(sums)
| simplelr_Docs | [
{
"content": "Question:\n### **Nested Tensors and Sequence Summation in PyTorch**\n\n#### Problem Statement\n\nYou are provided with multiple sequences of varying lengths, and you need to process these sequences using PyTorch's nested tensors. Your task is to write a function that computes the sum of elements i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1970,
"level": 1,
"question": "### **Nested Tensors and Sequence Summation in PyTorch**\n\n#### Problem Statement\n\nYou are provided with multiple sequences of varying lengths, and you need to process these sequences using PyTorch's nested tensors. Your task is to write a function ... |
def min_edit_distance(source: str, target: str) -> int:
m = len(source)
n = len(target)
# Initialize a 2D array with (m+1) rows and (n+1) columns
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Base case: transforming an empty string to target
for j in range(n + 1):
dp[0][j] = j
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are tasked with developing a function that determines the minimum number of operations required to convert one string into another through a series of allowed operations. Given two strings, `source` and `target`, only the following operations are permitted:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1971,
"level": 1,
"question": "### Problem Statement\n\nYou are tasked with developing a function that determines the minimum number of operations required to convert one string into another through a series of allowed operations. Given two strings, `source` and `target`, only the f... |
def reverse_first_fifteen_letters():
result = ''
for i in range(15, 0, -1):
result += chr(64 + i)
return result | simplelr_Filter | [
{
"content": "Question:\nCompose a Python function that outputs a string consisting of the first fifteen letters of the English alphabet in reverse order. However, you must use a loop and not use any built-in reverse or slicing methods to generate your string.\nAnswer:\nLet's think step by step.\n",
"role":... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1972,
"level": 1,
"question": "Compose a Python function that outputs a string consisting of the first fifteen letters of the English alphabet in reverse order. However, you must use a loop and not use any built-in reverse or slicing methods to generate your string.",
"split": "tr... |
from collections import Counter
def can_form_palindrome(s):
counts = Counter(s)
odd_count = 0
for count in counts.values():
if count % 2 != 0:
odd_count += 1
return odd_count <= 1 | simplelr_Apps | [
{
"content": "Question:\nDetermine if the given string can be rearranged to form a palindrome. The input will be a string of lowercase letters with no spaces or special characters.\n\n### Examples\n```\n\"civic\" --> True\n\"ivicc\" --> True\n\"hello\" --> False\n\"racecar\" --> True\n\"aabbcc\" --> True\n``` \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1973,
"level": 1,
"question": "Determine if the given string can be rearranged to form a palindrome. The input will be a string of lowercase letters with no spaces or special characters.\n\n### Examples\n```\n\"civic\" --> True\n\"ivicc\" --> True\n\"hello\" --> False\n\"racecar\" -... |
def trap(height):
left = 0
right = len(height) - 1
left_max = right_max = 0
res = 0
while left < right:
if height[left] < height[right]:
if height[left] > left_max:
left_max = height[left]
else:
res += left_max - height[left]
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers representing the height of buildings in a city, where each building's width is the same. The goal is to find the maximum amount of water that can be trapped between the buildings after it rains. Write a function that takes the list of building heights an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1974,
"level": 1,
"question": "You are given a list of integers representing the height of buildings in a city, where each building's width is the same. The goal is to find the maximum amount of water that can be trapped between the buildings after it rains. Write a function that ta... |
def visible_buildings_from_left(height):
result = []
max_height = -float('inf')
for i, h in enumerate(height):
if h > max_height:
result.append(i)
max_height = h
return result | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `n` unique integers `height` where `height[i]` represents the height of the `i-th` building. A building is **visible** if no building to its left has a greater or equal height. Write a function to return a list of indices representing buildings that are visible f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1975,
"level": 1,
"question": "You are given a list of `n` unique integers `height` where `height[i]` represents the height of the `i-th` building. A building is **visible** if no building to its left has a greater or equal height. Write a function to return a list of indices repres... |
def longest_unique_substring(s):
char_index = {}
max_length = 0
left = 0
for right in range(len(s)):
char = s[right]
if char in char_index:
left = max(left, char_index[char] + 1)
char_index[char] = right
current_length = right - left + 1
if current_len... | simplelr_Filter | [
{
"content": "Question:\nGiven the following code, create a function to find the length of the longest substring that does not have any repeating characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1976,
"level": 1,
"question": "Given the following code, create a function to find the length of the longest substring that does not have any repeating characters.",
"split": "train"
} |
def mirror_reverse(s):
reversed1 = s[::-1]
swapped = []
for c in reversed1:
if c.isupper():
swapped.append(c.lower())
else:
swapped.append(c.upper())
swapped_str = ''.join(swapped)
return swapped_str[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string and returns its mirror reverse. The mirror reverse means you should reverse the string twice, essentially putting it back in its original order. However, for the second reverse, change all characters to lowercase that were originally uppercase, and ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1977,
"level": 1,
"question": "Create a function that takes a string and returns its mirror reverse. The mirror reverse means you should reverse the string twice, essentially putting it back in its original order. However, for the second reverse, change all characters to lowercase t... |
def remove_duplicates(nums):
seen = set()
unique_list = []
for num in nums:
if num not in seen:
seen.add(num)
unique_list.append(num)
return unique_list | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a new list with all duplicates removed. Write the function in Python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1978,
"level": 1,
"question": "Create a function that takes a list of integers and returns a new list with all duplicates removed. Write the function in Python.",
"split": "train"
} |
def maxPower(artifacts):
n = len(artifacts)
if n == 1:
return artifacts[0]
prev_prev = artifacts[0]
prev = max(artifacts[0], artifacts[1])
for i in range(2, n):
current = max(prev, prev_prev + artifacts[i])
prev_prev, prev = prev, current
return prev | simplelr_Apps | [
{
"content": "Question:\nIn a game, players collect artifacts identified by distinct IDs, which are positive integers. Each artifact has a specific power value, and the total power of a player is the sum of power values of collected artifacts. The power values of artifacts are given in an array such that the i-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1979,
"level": 1,
"question": "In a game, players collect artifacts identified by distinct IDs, which are positive integers. Each artifact has a specific power value, and the total power of a player is the sum of power values of collected artifacts. The power values of artifacts are... |
def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if two strings are anagrams, meaning they contain the same characters in any order. For example, \"listen\" and \"silent\" are anagrams.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1980,
"level": 1,
"question": "Write a function to check if two strings are anagrams, meaning they contain the same characters in any order. For example, \"listen\" and \"silent\" are anagrams.",
"split": "train"
} |
def find_pairs(lst, target):
result = []
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] + lst[j] == target:
result.append((i, j))
return result | simplelr_Evol | [
{
"content": "Question:\nWrite a function in Python that takes a list of integers and a target integer as inputs. The function should return a list of tuples, where each tuple contains a pair of indices whose corresponding values in the list add up to the target integer. Ensure that the pairs are listed in asce... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1981,
"level": 1,
"question": "Write a function in Python that takes a list of integers and a target integer as inputs. The function should return a list of tuples, where each tuple contains a pair of indices whose corresponding values in the list add up to the target integer. Ensur... |
def is_perfect_cube(n):
if n == 0:
return True
if n > 0:
low = 0
high = n
else:
low = -abs(n)
high = 0
while low <= high:
mid = (low + high) // 2
cube = mid ** 3
if cube == n:
return True
elif cube < n:
low =... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given number is a perfect cube. A number is a perfect cube if there exists an integer such that the integer raised to the power of three equals the number.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1982,
"level": 1,
"question": "Write a function to check if a given number is a perfect cube. A number is a perfect cube if there exists an integer such that the integer raised to the power of three equals the number.",
"split": "train"
} |
def find_duplicate(nums):
n = len(nums)
sum1n = n * (n + 1) // 2
sum_array = sum(nums)
s = sum_array - sum1n # s = d - m
sum_sq_1n = n * (n + 1) * (2 * n + 1) // 6
sum_sq_array = sum(x * x for x in nums)
numerator = (sum_sq_array - sum_sq_1n) // s
m = (numerator - s) // 2
d = m + ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array `nums` of size `n`, where each element is between `1` and `n` inclusive, with no duplicates, except one repeated number, find the repeated number. You must solve this problem without modifying the input array and using only `O(1)` extra space.\nAnswer:\nLet's think step b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1983,
"level": 1,
"question": "Given an array `nums` of size `n`, where each element is between `1` and `n` inclusive, with no duplicates, except one repeated number, find the repeated number. You must solve this problem without modifying the input array and using only `O(1)` extra ... |
def calculate_score(cards):
if not cards:
return 0
total = 0
prev = None
for card in cards:
if prev is None:
total += card
prev = card
else:
if card != prev:
total += card
prev = card
return total
| simplelr_Taco | [
{
"content": "Question:\nIn a certain card game, each player receives a list of cards represented by positive integers. The value of each card represents the points it adds to the player's total score. However, there is also a special rule: if a player has more than one consecutive card with the same value (e.g... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1984,
"level": 1,
"question": "In a certain card game, each player receives a list of cards represented by positive integers. The value of each card represents the points it adds to the player's total score. However, there is also a special rule: if a player has more than one consec... |
def validate_parentheses(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Apps | [
{
"content": "Question:\n#Task\n\nWrite a function to validate a string that contains only parentheses. The function should return a boolean indicating whether the string is valid. A string containing only parentheses is considered valid if:\n1. Every opening parenthesis has a corresponding closing parenthesis.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1985,
"level": 1,
"question": "#Task\n\nWrite a function to validate a string that contains only parentheses. The function should return a boolean indicating whether the string is valid. A string containing only parentheses is considered valid if:\n1. Every opening parenthesis has a... |
def word_lengths(s):
if not s:
return {}
words = s.split()
result = {}
for word in words:
result[word] = len(word)
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string and returns a dictionary mapping each unique word in the string to its length. Words are considered as any sequence of characters separated by spaces. If the input string is empty, the function should return an empty dictionary.\nAnswer:\nLet'... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1986,
"level": 1,
"question": "Write a Python function that takes a string and returns a dictionary mapping each unique word in the string to its length. Words are considered as any sequence of characters separated by spaces. If the input string is empty, the function should return ... |
def max_subarray_sum(arr):
if not arr:
return 0 # Assuming the function should return 0 for an empty array
max_current = max_global = arr[0]
for num in arr[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the maximum sum of a subarray in an integer array. This is known as Kadane's Algorithm. Can you provide a Python implementation?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1987,
"level": 1,
"question": "Write a function to find the maximum sum of a subarray in an integer array. This is known as Kadane's Algorithm. Can you provide a Python implementation?",
"split": "train"
} |
def product_except_self(nums):
n = len(nums)
prefix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]
suffix = [1] * n
for i in range(n-2, -1, -1):
suffix[i] = suffix[i+1] * nums[i+1]
result = [prefix[i] * suffix[i] for i in range(n)]
return result | simplelr_Evol | [
{
"content": "Question:\nYou are asked to design a function that takes a list of integers and returns a new list such that each element at index `i` of the new list is the product of all the numbers in the original list except the one at `i`. Your solution should not use division.\n\nFor instance, consider the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1988,
"level": 1,
"question": "You are asked to design a function that takes a list of integers and returns a new list such that each element at index `i` of the new list is the product of all the numbers in the original list except the one at `i`. Your solution should not use divis... |
def generate_primes(limit):
if limit < 2:
return []
sieve_list = [True] * (limit + 1)
sieve_list[0], sieve_list[1] = False, False
sqrt_limit = int(limit ** 0.5)
for p in range(2, sqrt_limit + 1):
if sieve_list[p]:
for multiple in range(p * p, limit + 1, p):
... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that generates and returns a list of prime numbers up to a given upper limit. The function should be optimized to handle large values efficiently.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1989,
"level": 1,
"question": "Create a function that generates and returns a list of prime numbers up to a given upper limit. The function should be optimized to handle large values efficiently.",
"split": "train"
} |
def trapezoidal_rule(f, a, b, n):
h = (b - a) / n
total = f(a) + f(b)
for k in range(1, n):
x = a + k * h
total += 2 * f(x)
return (h / 2) * total | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to integrate a given function using the composite trapezoidal rule.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1990,
"level": 1,
"question": "Write a function to integrate a given function using the composite trapezoidal rule.",
"split": "train"
} |
from typing import List
def comb_sort(arr: List[int]) -> List[int]:
arr = arr.copy() # Create a copy to avoid modifying the input list
n = len(arr)
if n <= 1:
return arr
shrink = 1.3
gap = n - 1
while gap >= 1:
swapped = False
for i in range(n - gap):
if a... | simplelr_Data_Structure | [
{
"content": "Question:\n### Comb Sort Implementation\n\n#### Background\nComb Sort is a relatively simple sorting algorithm that improves upon Bubble Sort by introducing a gap sequence. The algorithm iteratively reduces the gap between elements to be compared and sorted, starting with a large gap and shrinking... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1991,
"level": 1,
"question": "### Comb Sort Implementation\n\n#### Background\nComb Sort is a relatively simple sorting algorithm that improves upon Bubble Sort by introducing a gap sequence. The algorithm iteratively reduces the gap between elements to be compared and sorted, star... |
def sort_people(people):
return sorted(people, key=lambda x: (x['age'], x['name'])) | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes a list of dictionaries representing people with their names and ages, and returns a new list of dictionaries sorted by age in ascending order. If two people have the same age, sort them by their name in alphabetical order. Each dictionary in the lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1992,
"level": 1,
"question": "Write a function in Python that takes a list of dictionaries representing people with their names and ages, and returns a new list of dictionaries sorted by age in ascending order. If two people have the same age, sort them by their name in alphabetica... |
def longest_word(sentence):
words = sentence.split()
longest = ''
max_length = 0
for word in words:
if len(word) > max_length:
max_length = len(word)
longest = word
return (longest, max_length) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that finds the longest word in a sentence. The function should return the longest word along with its length. If there are multiple words with the same maximum length, return the first one encountered.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1993,
"level": 1,
"question": "Create a function that finds the longest word in a sentence. The function should return the longest word along with its length. If there are multiple words with the same maximum length, return the first one encountered.",
"split": "train"
} |
from typing import List, Tuple
def optimal_task_order(n: int, tasks: List[Tuple[int, int]]) -> List[int]:
sorted_tasks = []
for idx in range(n):
t_i, d_i = tasks[idx]
sum_key = t_i + d_i
sorted_tasks.append((sum_key, t_i, idx))
sorted_tasks.sort(key=lambda x: (x[0], x[1]))
resul... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a list of tasks to be executed by a single-threaded CPU. Each task has a start time `t` when it becomes available for execution and a duration `d` indicating how long it takes to complete. The CPU can only execute one task at a time and must completely finish the current t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1994,
"level": 1,
"question": "You are given a list of tasks to be executed by a single-threaded CPU. Each task has a start time `t` when it becomes available for execution and a duration `d` indicating how long it takes to complete. The CPU can only execute one task at a time and m... |
def add_two_to_each_element(lst):
return [x + 2 for x in lst]
# Example usage:
numbers = [1, 2, 3, 4, 5]
result = add_two_to_each_element(numbers)
print(result) # Outputs: [3, 4, 5, 6, 7] | simplelr_Filter | [
{
"content": "Question:\nI have a list and I want to generate a new list that adds 2 to each element. How can I do that using a function in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1995,
"level": 1,
"question": "I have a list and I want to generate a new list that adds 2 to each element. How can I do that using a function in Python?",
"split": "train"
} |
def reverse_tuples(tuples_list):
return [(t[1], t[0]) for t in tuples_list] | simplelr_Filter | [
{
"content": "Question:\nWrite a python function that takes a list as input. This list contains tuples, each of which consists of two different strings. The function should reverse the elements of each tuple and return the reversed list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1996,
"level": 1,
"question": "Write a python function that takes a list as input. This list contains tuples, each of which consists of two different strings. The function should reverse the elements of each tuple and return the reversed list.",
"split": "train"
} |
def print_reverse(a, b, c):
print(c, b, a) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in three arguments then print the arguments in reverse order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1997,
"level": 1,
"question": "Create a function that takes in three arguments then print the arguments in reverse order.",
"split": "train"
} |
def max_consecutive_ones(binary_array: list) -> int:
max_count = 0
current = 0
for num in binary_array:
if num == 1:
current += 1
else:
if current > max_count:
max_count = current
current = 0
# Check after loop ends in case the array en... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question: Maximum Consecutive Ones in Binary Array\n\n**Context**:\nWorking with binary arrays (arrays composed of 0s and 1s) is a common task in many coding and technical assessments. One significant operation on such an array is determining the longest sequence o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1998,
"level": 1,
"question": "### Coding Assessment Question: Maximum Consecutive Ones in Binary Array\n\n**Context**:\nWorking with binary arrays (arrays composed of 0s and 1s) is a common task in many coding and technical assessments. One significant operation on such an array is... |
from collections import deque
def min_steps_to_reach_end(grid):
if not grid or not grid[0]:
return -1
n = len(grid)
m = len(grid[0])
if n == 1 and m == 1:
return 0
visited = [[False for _ in range(m)] for _ in range(n)]
queue = deque()
queue.append((0, 0, 0))
visited[0][... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a 2D matrix `grid` of integers where each cell represents the elevation at that point, find the minimum number of steps required to reach from the top-left corner of the matrix to the bottom-right corner. You can move up, down, left, or right from a cell, and you can only move to ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1999,
"level": 1,
"question": "Given a 2D matrix `grid` of integers where each cell represents the elevation at that point, find the minimum number of steps required to reach from the top-left corner of the matrix to the bottom-right corner. You can move up, down, left, or right fro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.