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 next_bigger(num: int) -> int:
digits = list(map(int, str(num)))
idx = len(digits) - 1
# Step 1: Find the pivot point
while idx > 0 and digits[idx - 1] >= digits[idx]:
idx -= 1
if idx == 0:
return -1 # No such number exists
# Step 2: Find the successor to swap
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Next Bigger Number with Same Digits\n\nGiven an integer, find the next higher number that contains the same digits. If no such number exists, return -1. Your solution should be efficient and handle large inputs gracefully. Implement the function `next_bigger(num: int) -> i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3000,
"level": 1,
"question": "### Question: Next Bigger Number with Same Digits\n\nGiven an integer, find the next higher number that contains the same digits. If no such number exists, return -1. Your solution should be efficient and handle large inputs gracefully. Implement the f... |
def is_palindrome(s):
left = 0
right = len(s) - 1
while left < right:
# Move left pointer to the next alphanumeric character
while left < right and not s[left].isalnum():
left += 1
# Move right pointer to the next alphanumeric character
while left < right and not... | simplelr_Filter | [
{
"content": "Question:\nGiven a string `s`, return true if it is a palindrome, or false otherwise.\n\n**Explanation:**\n\nA palindrome is a word or phrase that reads the same backward as forward.\n\n\n\n**Example 1:**\n\n```\nInput: s = \"racecar\"\nOutput: true\n```\n\n**Example 2:**\n\n```\nInput: s = \"not ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3001,
"level": 1,
"question": "Given a string `s`, return true if it is a palindrome, or false otherwise.\n\n**Explanation:**\n\nA palindrome is a word or phrase that reads the same backward as forward.\n\n\n\n**Example 1:**\n\n```\nInput: s = \"racecar\"\nOutput: true\n```\n\n**Exa... |
def calculate_total_cost(num_units, price_per_unit):
"""
Calculate the total cost of a product.
Args:
num_units (int or float): The number of units to purchase.
price_per_unit (int or float): The price per unit of the product.
Returns:
int or float: The total cost of th... | simplelr_Filter | [
{
"content": "Question:\nHow do I create a Python function to calculate the total cost of a product, given the number of units and the price per unit?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3002,
"level": 1,
"question": "How do I create a Python function to calculate the total cost of a product, given the number of units and the price per unit?",
"split": "train"
} |
def largest_product_of_three(nums):
if len(nums) < 3:
return None # Assuming the input array has at least three elements
nums.sort()
n = len(nums)
candidate1 = nums[-1] * nums[-2] * nums[-3]
candidate2 = nums[0] * nums[1] * nums[-1]
return max(candidate1, candidate2) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the largest product of three numbers in an array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3003,
"level": 1,
"question": "Write a python function to find the largest product of three numbers in an array.",
"split": "train"
} |
def first_occurrence(arr, target):
low = 0
high = len(arr) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
result = mid
high = mid - 1
elif arr[mid] < target:
low = mid + 1
else:
high = mid ... | simplelr_Filter | [
{
"content": "Question:\nYou are given a sorted array of integers. Write a function that returns the index of the first occurrence of a given target integer in the array. If the target is not present in the array, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3004,
"level": 1,
"question": "You are given a sorted array of integers. Write a function that returns the index of the first occurrence of a given target integer in the array. If the target is not present in the array, return -1.",
"split": "train"
} |
def factorial(n):
if n < 0:
raise ValueError("Factorial is not defined for negative numbers")
elif n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Example usage:
print(factorial(5)) # Output: 120
print(factorial(0)) # Output: 1
print(factorial(1)) # Output: 1 | simplelr_Filter | [
{
"content": "Question:\nCan I get an example of a recursive function in Python, along with an explanation of how it works?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3005,
"level": 1,
"question": "Can I get an example of a recursive function in Python, along with an explanation of how it works?",
"split": "train"
} |
def is_divisible_by_3(n):
if n % 3 == 0:
print("The number is divisible by 3.")
return True
else:
print("The number is not divisible by 3.")
return False | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as an input, then prints out whether it is divisible by 3 or not. If the number is divisible by 3, the function should return `True`, otherwise, it should return `False`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3006,
"level": 1,
"question": "Create a function that takes an integer as an input, then prints out whether it is divisible by 3 or not. If the number is divisible by 3, the function should return `True`, otherwise, it should return `False`.",
"split": "train"
} |
def longest_substring_length(s):
char_index = {}
max_length = 0
start = 0
for end in range(len(s)):
char = s[end]
if char in char_index:
# Move the start pointer to the right of the last occurrence of the current character
start = max(start, char_index[char] + 1)
... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that identifies the longest substring in a given string that does not contain any repeating characters. For instance, longest_substring_length(\"abcabcbb\") should return 3, because the longest substring without repeating characters is \"abc\". The function should be o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3007,
"level": 1,
"question": "Create a function that identifies the longest substring in a given string that does not contain any repeating characters. For instance, longest_substring_length(\"abcabcbb\") should return 3, because the longest substring without repeating characters i... |
def is_isomorphic_emails(local1, local2):
if len(local1) != len(local2):
return False
map1 = {}
map2 = {}
for c1, c2 in zip(local1, local2):
if c1 in map1:
if map1[c1] != c2:
return False
else:
map1[c1] = c2
if c2... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with designing a software feature that validates the structure of emails. Specifically, your task is to determine if the local parts (the section before the '@' symbol) of two emails are isomorphic. Two local parts are considered isomorphic if characters in the first loca... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3008,
"level": 1,
"question": "You are tasked with designing a software feature that validates the structure of emails. Specifically, your task is to determine if the local parts (the section before the '@' symbol) of two emails are isomorphic. Two local parts are considered isomorp... |
def uppercase_all_names(names):
return [name.upper() for name in names] | simplelr_Filter | [
{
"content": "Question:\n### Objective\nThe objective of this lesson is to show how to apply a function to each element of a list. \n\n### Example Use Case\nSuppose that we have a list of names and we want to convert each name to uppercase. \n\n```python\nnames = [\"john\", \"peter\", \"sarah\"]\n```\n\n### Sol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3009,
"level": 1,
"question": "### Objective\nThe objective of this lesson is to show how to apply a function to each element of a list. \n\n### Example Use Case\nSuppose that we have a list of names and we want to convert each name to uppercase. \n\n```python\nnames = [\"john\", \"... |
def compress_string(s: str) -> str:
if not s:
return s
compressed = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
compressed.append(f"{current_char}{count}")
current_char = char
... | simplelr_Taco | [
{
"content": "Question:\nJason is working on a project that requires compressing a string while preserving its information. He decided to use a special encoding technique where he replaces consecutive identical characters with a single character followed by the count of repetitions.\n\nFor example, the string \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3010,
"level": 1,
"question": "Jason is working on a project that requires compressing a string while preserving its information. He decided to use a special encoding technique where he replaces consecutive identical characters with a single character followed by the count of repeti... |
def most_frequent_string(str1, str2, lst):
count1 = lst.count(str1)
count2 = lst.count(str2)
if count1 > count2:
return str1
elif count2 > count1:
return str2
else:
for item in lst:
if item == str1 or item == str2:
return item
return s... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two strings as input and returns the string that is the most frequent in a given list of strings. If both strings are equally frequent, return the first string that appears in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3011,
"level": 1,
"question": "Create a function that takes two strings as input and returns the string that is the most frequent in a given list of strings. If both strings are equally frequent, return the first string that appears in the list.",
"split": "train"
} |
def count_paths(m, n):
# Create a DP table with m rows and n columns
dp = [[0 for _ in range(n)] for _ in range(m)]
# Initialize the first row
for j in range(n):
dp[0][j] = 1
# Initialize the first column
for i in range(m):
dp[i][0] = 1
# Fill the DP table
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Counting Unique Paths in a Matrix\n\nYou are given an \\(m \\times n\\) grid. Your task is to calculate the number of unique paths from the top-left corner (0, 0) to the bottom-right corner (m-1, n-1). You can only move either right or down from a cell.\n\nWrite a function `count_pa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3012,
"level": 1,
"question": "### Counting Unique Paths in a Matrix\n\nYou are given an \\(m \\times n\\) grid. Your task is to calculate the number of unique paths from the top-left corner (0, 0) to the bottom-right corner (m-1, n-1). You can only move either right or down from a ... |
def replace_lowercase_with_uppercase(s):
result = []
for c in s:
if 'a' <= c <= 'y':
result.append(c.upper())
else:
result.append(c)
return ''.join(result) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to replace all the lower case letters 'a' to 'y' in a string with corresponding upper case letters, and maintain other characters unchanged.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3013,
"level": 1,
"question": "Write a python function to replace all the lower case letters 'a' to 'y' in a string with corresponding upper case letters, and maintain other characters unchanged.",
"split": "train"
} |
def find_closest_number(numbers, target):
if not numbers:
return None # or raise ValueError("List is empty")
closest_num = numbers[0]
closest_diff = abs(closest_num - target)
for num in numbers[1:]:
current_diff = abs(num - target)
if current_diff < closest_diff:
... | simplelr_Filter | [
{
"content": "Question:\nCan you write a Python function that finds the number in a list that is closest to a specific target number? For example, if you have a list of numbers and a target, the function should return the number from the list that is nearest to the target. If two numbers are equally close, the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3014,
"level": 1,
"question": "Can you write a Python function that finds the number in a list that is closest to a specific target number? For example, if you have a list of numbers and a target, the function should return the number from the list that is nearest to the target. If ... |
def is_palindrome(s):
cleaned = [c.lower() for c in s if c.isalnum()]
cleaned_str = ''.join(cleaned)
return cleaned_str == cleaned_str[::-1]
| simplelr_Taco | [
{
"content": "Question:\n## Palindrome Checker\n\nWrite a function that takes a string as input and determines whether it is a palindrome, ignoring non-alphanumeric characters and case. The function should return `True` if the string is a palindrome and `False` otherwise.\n\nA palindrome is a word, phrase, numb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3015,
"level": 1,
"question": "## Palindrome Checker\n\nWrite a function that takes a string as input and determines whether it is a palindrome, ignoring non-alphanumeric characters and case. The function should return `True` if the string is a palindrome and `False` otherwise.\n\nA... |
from collections import defaultdict
def electLeader(ballots):
vote_counts = defaultdict(int)
for name in ballots:
vote_counts[name] += 1
max_votes = max(vote_counts.values())
candidates = [name for name in vote_counts if vote_counts[name] == max_votes]
candidates.sort()
return candidate... | simplelr_Taco | [
{
"content": "Question:\nA company organizes a voting campaign where employees cast their votes to elect a leader. Each employee votes by submitting a ballot with the name of their chosen candidate. The person who receives the most votes wins the election. In the event of a tie, the candidate whose name comes f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3016,
"level": 1,
"question": "A company organizes a voting campaign where employees cast their votes to elect a leader. Each employee votes by submitting a ballot with the name of their chosen candidate. The person who receives the most votes wins the election. In the event of a ti... |
def reverse_words(s):
words = s.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse the order of words in a string. For example, given the string \"I am a programmer\", the function should return \"programmer a am I\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3017,
"level": 1,
"question": "Write a function to reverse the order of words in a string. For example, given the string \"I am a programmer\", the function should return \"programmer a am I\".",
"split": "train"
} |
def highest_score(scores):
if not scores:
return None
return max(scores) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the highest score in a list of scores. If the list is empty, return `None`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3018,
"level": 1,
"question": "Write a python function to find the highest score in a list of scores. If the list is empty, return `None`.",
"split": "train"
} |
from typing import List, Dict
def map_sum(list1: List[int], list2: List[int]) -> Dict[int, int]:
result = {}
for i in range(len(list1)):
key = list1[i]
value = list2[i]
if key in result:
result[key] += value
else:
result[key] = value
return result | simplelr_Apps | [
{
"content": "Question:\nYou are given two lists: `list1` and `list2`, containing integers. Both lists are of the same length. Develop a function that returns a dictionary where each key is an element from `list1` and the corresponding value is the sum of elements in `list2` at positions in indexes where `list1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3019,
"level": 1,
"question": "You are given two lists: `list1` and `list2`, containing integers. Both lists are of the same length. Develop a function that returns a dictionary where each key is an element from `list1` and the corresponding value is the sum of elements in `list2` a... |
def are_anagrams(s1, s2):
count1 = [0] * 26
count2 = [0] * 26
for c in s1:
if c.isalpha():
index = ord(c.lower()) - ord('a')
count1[index] += 1
for c in s2:
if c.isalpha():
index = ord(c.lower()) - ord('a')
count2[index] += 1
... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes two strings as inputs and checks if they are anagrams. The function should be case insensitive and ignore any spaces or special characters. Additionally, the function should only use O(1) extra space and have a time complexity of O(n log n), where n i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3020,
"level": 1,
"question": "Create a Python function that takes two strings as inputs and checks if they are anagrams. The function should be case insensitive and ignore any spaces or special characters. Additionally, the function should only use O(1) extra space and have a time ... |
def longest_substring_with_two_distinct_characters(s: str) -> int:
char_counts = {}
left = 0
max_len = 0
for right in range(len(s)):
current_char = s[right]
if current_char in char_counts:
char_counts[current_char] += 1
else:
char_counts[current_char] = 1
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a string, s, consisting of lowercase Latin letters (a-z). Your task is to find the longest substring that contains at most two distinct characters. \n\nImplement a function that takes a string as input and returns the length of the longest substring that contains at most t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3021,
"level": 1,
"question": "You are given a string, s, consisting of lowercase Latin letters (a-z). Your task is to find the longest substring that contains at most two distinct characters. \n\nImplement a function that takes a string as input and returns the length of the longes... |
import torch
def custom_tensor_transform(input_tensor: torch.Tensor, n: int) -> float:
added = torch.add(input_tensor, n)
squared = torch.pow(added, 2)
mean = torch.mean(squared)
return float(mean)
| simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nDemonstrate your understanding of PyTorch's Core Aten IR by implementing a function that performs tensor operations using Core Aten IR operators.\n\n#### Task:\nImplement a function called `custom_tensor_transform` that:\n1. Accepts a 2D PyTorch tensor `input_tensor` an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3022,
"level": 1,
"question": "#### Objective:\nDemonstrate your understanding of PyTorch's Core Aten IR by implementing a function that performs tensor operations using Core Aten IR operators.\n\n#### Task:\nImplement a function called `custom_tensor_transform` that:\n1. Accepts a ... |
from collections import deque
def find_path(maze):
# Handle the case where the maze is 1x1
if len(maze) == 1 and len(maze[0]) == 1:
return [(0, 0)] if maze[0][0] == 0 else []
rows = len(maze)
cols = len(maze[0])
# Check if start or end is blocked
if maze[0][0] == 1 or maze[row... | simplelr_Taco | [
{
"content": "Question:\nYou are given a maze represented by a 2D grid of integers where `0` indicates an open cell and `1` indicates a wall. A rat can move up, down, left, or right from an open cell. The goal is to find a way for the rat to reach the bottom-right corner of the maze starting from the top-left c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3023,
"level": 1,
"question": "You are given a maze represented by a 2D grid of integers where `0` indicates an open cell and `1` indicates a wall. A rat can move up, down, left, or right from an open cell. The goal is to find a way for the rat to reach the bottom-right corner of th... |
from typing import List
def custom_sum(numbers: List[int]) -> int:
total = 0
for number in numbers:
total += number
return total | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nIn numerical computations and data analysis, summing up large datasets is a common operation. Sometimes, to ensure the performance and accuracy of your program, you might need to implement summing algorithms without using built-in functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3024,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario\nIn numerical computations and data analysis, summing up large datasets is a common operation. Sometimes, to ensure the performance and accuracy of your program, you might need to implement summing algori... |
def digit_sum(n):
if n == 0:
return 0
remainder = n % 9
return 9 if remainder == 0 else remainder | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the sum of a given number's steps until it reduced to a single digit. This process is known as digit sum or digital root. For example, for the number 39, the function should return 3 (3 + 9 = 12, 1 + 2 = 3).\nAnswer:\nLet's think step by step.\n",
"ro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3025,
"level": 1,
"question": "Write a python function to find the sum of a given number's steps until it reduced to a single digit. This process is known as digit sum or digital root. For example, for the number 39, the function should return 3 (3 + 9 = 12, 1 + 2 = 3).",
"split":... |
def max_competitions(work_hours, total_hours):
if total_hours <= 0 or not work_hours:
return 0
work_hours.sort()
current_sum = 0
count = 0
for hours in work_hours:
if current_sum + hours > total_hours:
break
current_sum += hours
count += 1
return count | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are responsible for organizing coding challenge competitions at your organization. Each competition requires a certain amount of preparatory work, and you have a limited number of work hours to allocate each day. You want to distribute the work such that the m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3026,
"level": 1,
"question": "### Problem Statement\nYou are responsible for organizing coding challenge competitions at your organization. Each competition requires a certain amount of preparatory work, and you have a limited number of work hours to allocate each day. You want to ... |
def generate_sequence(start, limit, step):
sequence = []
if step == 0:
if start <= limit:
sequence.append(start)
return sequence
if step > 0:
if start > limit:
return sequence
current = start
while current <= limit:
sequence.ap... | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that generates a sequence of numbers starting from a given number, up to a specified limit, and increments by a specified step. The function should take three parameters: the starting number, the limit, and the step. It should return a list of the generated se... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3027,
"level": 1,
"question": "Write a function in Python that generates a sequence of numbers starting from a given number, up to a specified limit, and increments by a specified step. The function should take three parameters: the starting number, the limit, and the step. It shoul... |
def can_form_string(s1, s2):
if not s1:
return True
i = j = 0
while i < len(s1) and j < len(s2):
if s1[i] == s2[j]:
i += 1
j += 1
return i == len(s1) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in two strings and decide if a new string can be formed by taking characters from the second string in the same order that they appear in the first string. For example, if `s1=\"abc\"` and `s2=\"abcatgda\"`, the function should return `true` because `s2` con... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3028,
"level": 1,
"question": "Create a function that takes in two strings and decide if a new string can be formed by taking characters from the second string in the same order that they appear in the first string. For example, if `s1=\"abc\"` and `s2=\"abcatgda\"`, the function sh... |
from typing import List
def filter_packets(packets: List[int]) -> List[int]:
seen = set()
result = []
for packet in packets:
if packet not in seen:
seen.add(packet)
result.append(packet)
return result | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nA communications company needs to analyze and stabilize the data transmission over their network. Data packets transmitted over the network may occasionally be delayed or duplicated. They want to clean the data by identifying original packets and detecting duplicates.\n\n##... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3029,
"level": 1,
"question": "### Context\nA communications company needs to analyze and stabilize the data transmission over their network. Data packets transmitted over the network may occasionally be delayed or duplicated. They want to clean the data by identifying original pack... |
def number_matrix(n):
# Create a matrix of size n x n initialized to 0
matrix = [[0 for _ in range(n)] for _ in range(n)]
current_num = 1
start_row, end_row = 0, n - 1
start_col, end_col = 0, n - 1
while start_row <= end_row and start_col <= end_col:
# Top row: left to right
... | simplelr_Taco | [
{
"content": "Question:\n## Task:\nWrite a function `number_matrix` that generates a matrix of numbers in a spiral order, given an integer `n`. The function should return the matrix as a list of lists.\n\n#### Input:\n- An integer `n` (1 <= n <= 20)\n\n#### Output:\n- A 2D list representing the matrix of number... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3030,
"level": 1,
"question": "## Task:\nWrite a function `number_matrix` that generates a matrix of numbers in a spiral order, given an integer `n`. The function should return the matrix as a list of lists.\n\n#### Input:\n- An integer `n` (1 <= n <= 20)\n\n#### Output:\n- A 2D lis... |
def remove_whitespace(s):
return ''.join(c for c in s if not c.isspace()) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string and returns a new string with all whitespace removed.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3031,
"level": 1,
"question": "Create a function that takes a string and returns a new string with all whitespace removed.",
"split": "train"
} |
def minimum_bricks_to_remove(heights, k):
if not heights:
return 0
current_height = heights[0]
current_count = 1
total = 0
for h in heights[1:]:
if h == current_height:
current_count += 1
else:
if current_count > k:
total += (current_co... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `heights` representing the heights of buildings and an integer `k`, return the minimum number of bricks you need to remove so that there are no more than `k` buildings of the same height standing in a row.\n\nFor example, if the input is `heights = [3,3,3,3,4,4,4,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3032,
"level": 1,
"question": "Given an integer array `heights` representing the heights of buildings and an integer `k`, return the minimum number of bricks you need to remove so that there are no more than `k` buildings of the same height standing in a row.\n\nFor example, if the ... |
def sum_of_digits(num):
total = 0
n = num
while n > 0:
total += n % 10
n = n // 10
return total | simplelr_Filter | [
{
"content": "Question:\nCould you explain how to write a Python function that returns the sum of the digits of a positive integer?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3033,
"level": 1,
"question": "Could you explain how to write a Python function that returns the sum of the digits of a positive integer?",
"split": "train"
} |
def max_word_length(s):
words = s.split()
return max(len(word) for word in words) if words else 0 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and outputs the maximum length of the string present in any word within the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3034,
"level": 1,
"question": "Create a function that takes a string as input and outputs the maximum length of the string present in any word within the string.",
"split": "train"
} |
def roman_to_int(s):
roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
for i in range(len(s) - 1):
current = roman_map[s[i]]
next_val = roman_map[s[i + 1]]
if current < next_val:
total -= current
else:
total += cur... | simplelr_Leetcode | [
{
"content": "Question:\nWrite a function that takes a string `s` representing a Roman numeral and returns the integer value of the numeral. Roman numerals are represented by seven different symbols: `I, V, X, L, C, D, and M`. The value of Roman numerals is determined by summing or subtracting values based on s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3035,
"level": 1,
"question": "Write a function that takes a string `s` representing a Roman numeral and returns the integer value of the numeral. Roman numerals are represented by seven different symbols: `I, V, X, L, C, D, and M`. The value of Roman numerals is determined by summi... |
def are_anagrams(str1, str2):
# Check if lengths are different
if len(str1) != len(str2):
return False
# Convert both strings to lowercase and sort
return sorted(str1.lower()) == sorted(str2.lower())
# Example usage:
print(are_anagrams('listen', 'silent')) # Output: True
print(are_anagrams('he... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code example that demonstrates how to check if a string is an anagram of another string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3036,
"level": 1,
"question": "Can you provide a Python code example that demonstrates how to check if a string is an anagram of another string?",
"split": "train"
} |
from typing import List
def can_return_books(borrowed: List[str], permissible: List[str]) -> bool:
pos_map = {book: idx for idx, book in enumerate(permissible)}
current_pos = -1
for book in borrowed:
idx = pos_map[book]
if idx <= current_pos:
return False
current_pos = i... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\n#### Scenario:\nYou are developing a library management system where users can borrow and return books. A feature needs to be added to check if all borrowed books can be returned in a particular order, given that users might return books in any order they choose... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3037,
"level": 1,
"question": "### Problem Statement\n\n#### Scenario:\nYou are developing a library management system where users can borrow and return books. A feature needs to be added to check if all borrowed books can be returned in a particular order, given that users might re... |
def sort_letters_digits(s):
letters = []
digits = []
for c in s:
if c.isalpha():
letters.append(c)
else:
digits.append(c)
letters.sort()
digits.sort()
result = []
l = d = 0
for c in s:
if c.isalpha():
result.append(letters[l])
... | simplelr_Evol | [
{
"content": "Question:\nDevise a function that, given a string containing letters and digits, generates a new string where the letters are sorted in alphabetical order and the digits are sorted in ascending order. The positions of letters and digits in the new string should remain the same respective to each o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3038,
"level": 1,
"question": "Devise a function that, given a string containing letters and digits, generates a new string where the letters are sorted in alphabetical order and the digits are sorted in ascending order. The positions of letters and digits in the new string should r... |
def roman_to_int(s):
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
prev_value = 0
for char in s:
current_value = roman_dict[char]
if current_value > prev_value:
total = total - 2 * prev_value + current_value
else:
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert a Roman numeral to an integer. Could you provide a solution using Python, specifically a code snippet that implements the conversion algorithm? Here's an example of a Roman numeral: \"MCMXCIV\".\nAnswer:\nLet's think step by step.\n",
"role": "user... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3039,
"level": 1,
"question": "Write a python function to convert a Roman numeral to an integer. Could you provide a solution using Python, specifically a code snippet that implements the conversion algorithm? Here's an example of a Roman numeral: \"MCMXCIV\".",
"split": "train"
} |
def is_palindrome(s):
"""
Checks if a string is a palindrome recursively.
Args:
s: The input string.
Returns:
True if s is a palindrome, False otherwise.
"""
s = s.lower()
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrom... | simplelr_Filter | [
{
"content": "Question:\nThe following problems are about **recursion**:\n\n**Problem 1:**\n\nWrite a recursive function `is_palindrome(s)` that takes a string `s` and returns `True` if `s` is a palindrome, `False` otherwise.\n\n**Problem 2:**\n\nWrite a recursive function `factorial(n)` that takes a non-negati... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3040,
"level": 1,
"question": "The following problems are about **recursion**:\n\n**Problem 1:**\n\nWrite a recursive function `is_palindrome(s)` that takes a string `s` and returns `True` if `s` is a palindrome, `False` otherwise.\n\n**Problem 2:**\n\nWrite a recursive function `fa... |
def is_palindrome(text):
text = text.lower() # Ensure case-insensitive comparison
left = 0
right = len(text) - 1
if len(text) <= 1:
return True
while left < right:
if text[left] != text[right]:
return False
left += 1
right -= 1
retu... | simplelr_Filter | [
{
"content": "Question:\nYou are given a string, \"abccba\". Determine if it is a palindrome.\n\n Solution Approach:\n 1. Two-Pointer Technique:\n Initialize left and right pointers at the beginning and end of the string, respectively.\n Iterate through the string:\n While the left poi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3041,
"level": 1,
"question": "You are given a string, \"abccba\". Determine if it is a palindrome.\n\n Solution Approach:\n 1. Two-Pointer Technique:\n Initialize left and right pointers at the beginning and end of the string, respectively.\n Iterate through the str... |
def count_unique_words(s):
words = s.split()
unique_words = set(words)
return len(unique_words) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to count the number of unique words in a given string. You can assume that words are separated by space.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3042,
"level": 1,
"question": "Write a python function to count the number of unique words in a given string. You can assume that words are separated by space.",
"split": "train"
} |
def min_substrings(s, words):
if not s:
return 0
word_set = set(words)
max_length = max(len(word) for word in words) if words else 0
n = len(s)
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
for l in range(1, max_length + 1):
if i - l >= 0:... | simplelr_Apps | [
{
"content": "Question:\nGiven a string `s` and an array of strings `words`, find the minimum number of substrings of `s` required such that each substring is one of the words in the array. If it is not possible to form the string `s` using the words in the array, return -1.\n\nFor example:\n```\ns = \"leetcode... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3043,
"level": 1,
"question": "Given a string `s` and an array of strings `words`, find the minimum number of substrings of `s` required such that each substring is one of the words in the array. If it is not possible to form the string `s` using the words in the array, return -1.\n... |
def reverse_characters_in_words(s: str) -> str:
if not s:
return s
runs = []
current_run = s[0]
current_is_space = current_run.isspace()
for c in s[1:]:
if c.isspace() == current_is_space:
current_run += c
else:
runs.append(current_run)
c... | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem Description\nYou are tasked with implementing a function that takes a string, and returns a new string where the order of the characters in each individual word is reversed, but the words are in the original order. \n\n### Input and Output\n\n* **Input**: A single string `s`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3044,
"level": 1,
"question": "### Problem Description\nYou are tasked with implementing a function that takes a string, and returns a new string where the order of the characters in each individual word is reversed, but the words are in the original order. \n\n### Input and Output\... |
def max_subarray_sum(array: list[int]) -> int:
if not array:
return 0
max_current = max_global = array[0]
for num in array[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global | simplelr_Algorithm | [
{
"content": "Question:\n### Context:\nYou are working on a data processing pipeline that involves manipulating lists of integers. You need to implement a function that finds the maximum sum of a contiguous subarray within a one-dimensional array of integers, which is a crucial part of performance analytics in ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3045,
"level": 1,
"question": "### Context:\nYou are working on a data processing pipeline that involves manipulating lists of integers. You need to implement a function that finds the maximum sum of a contiguous subarray within a one-dimensional array of integers, which is a crucia... |
def reverse_string(s):
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that reverses a string passed as an argument and returns the reversed string. The function should handle both uppercase and lowercase letters, and ignore any non-alphabetic characters. For example, reversing the string \"Hello, World!\" should return \"!dlroW ,olleH\".... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3046,
"level": 1,
"question": "Create a function that reverses a string passed as an argument and returns the reversed string. The function should handle both uppercase and lowercase letters, and ignore any non-alphabetic characters. For example, reversing the string \"Hello, World!... |
def group_tasks(tasks):
priority_groups = {}
for task, prio in tasks:
if prio not in priority_groups:
priority_groups[prio] = []
priority_groups[prio].append((task, prio))
sorted_priorities = sorted(priority_groups.keys(), reverse=True)
result = []
for p in sorted_priorit... | simplelr_Taco | [
{
"content": "Question:\nYou are helping your friend to manage their to-do list with a very specific task setup. They categorize their tasks based on priority levels, which are represented with numbers: the higher the number, the higher the priority.\n\nYou are given a list of tasks with their priorities. You n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3047,
"level": 1,
"question": "You are helping your friend to manage their to-do list with a very specific task setup. They categorize their tasks based on priority levels, which are represented with numbers: the higher the number, the higher the priority.\n\nYou are given a list of... |
def length_of_longest_substring(s: str) -> int:
last_seen = {}
max_length = 0
left = 0
for right in range(len(s)):
char = s[right]
if char in last_seen and last_seen[char] >= left:
left = last_seen[char] + 1
last_seen[char] = right
current_length = right - lef... | simplelr_Filter | [
{
"content": "Question:\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n if not s:\n return 0\n\n char_set = set()\n left = 0\n max_length = 0\n\n for right in range(len(s)):\n while s[right] in char_set:\n char_se... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3048,
"level": 1,
"question": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n if not s:\n return 0\n\n char_set = set()\n left = 0\n max_length = 0\n\n for right in range(len(s)):\n while s[right] in... |
def count_characters(input_string):
char_count = {}
for c in input_string:
char_count[c] = char_count.get(c, 0) + 1
return char_count
| simplelr_Taco | [
{
"content": "Question:\nComplete the function that takes a string as an input and returns a dictionary with the count of each unique character in the string.\n\n## Examples\n\n```python\ninput_string = \"hello\" ==> {'h': 1, 'e': 1, 'l': 2, 'o': 1}\ninput_string = \"world\" ==> {'w': 1, 'o': 1, 'r': 1, 'l': ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3049,
"level": 1,
"question": "Complete the function that takes a string as an input and returns a dictionary with the count of each unique character in the string.\n\n## Examples\n\n```python\ninput_string = \"hello\" ==> {'h': 1, 'e': 1, 'l': 2, 'o': 1}\ninput_string = \"world\" ... |
def longest_common_substring(s1, s2):
len1, len2 = len(s1), len(s2)
dp = [0] * len2
max_len = 0
for i in range(len1):
# Iterate j in reverse to prevent overwriting issues
for j in range(len2 - 1, -1, -1):
if s1[i] == s2[j]:
if i == 0 or j == 0:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven two strings `s1` and `s2`, find the length of the longest substring that appears in both `s1` and `s2`. The substring is defined as a contiguous sequence of characters that appear in the same order in both strings. If there are multiple longest substrings with the same length, out... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3050,
"level": 1,
"question": "Given two strings `s1` and `s2`, find the length of the longest substring that appears in both `s1` and `s2`. The substring is defined as a contiguous sequence of characters that appear in the same order in both strings. If there are multiple longest s... |
def count_derangements(n: int) -> int:
if n == 1:
return 0
elif n == 2:
return 1
else:
a, b = 0, 1 # a is D(1), b is D(2)
for i in range(3, n + 1):
current = (i - 1) * (b + a)
a, b = b, current
return b
| simplelr_Taco | [
{
"content": "Question:\nA group of friends has a peculiar way of exchanging gifts. Each person in the group has exactly one gift, and they want to exchange them in such a way that everyone ends up with a different gift than the one they initially had. The group leader wants to know how many possible ways there... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3051,
"level": 1,
"question": "A group of friends has a peculiar way of exchanging gifts. Each person in the group has exactly one gift, and they want to exchange them in such a way that everyone ends up with a different gift than the one they initially had. The group leader wants t... |
def filter_and_sort(data: list[dict], key: str) -> list[dict]:
filtered_data = [d for d in data if key in d]
sorted_data = sorted(filtered_data, key=lambda x: x[key])
return sorted_data | simplelr_Package | [
{
"content": "Question:\nIn this problem, you are to create a function that filters and sorts a list of dictionaries. Your task is to create a function named `filter_and_sort` that accepts a list of dictionaries and a string key. The function will filter out dictionaries that do not contain the specified key an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3052,
"level": 1,
"question": "In this problem, you are to create a function that filters and sorts a list of dictionaries. Your task is to create a function named `filter_and_sort` that accepts a list of dictionaries and a string key. The function will filter out dictionaries that ... |
def final_position(start, commands):
x, y = start
for command in commands:
direction, steps = command
if direction == "up":
y += steps
elif direction == "down":
y -= steps
elif direction == "left":
x -= steps
elif direction == "right":
... | simplelr_Package | [
{
"content": "Question:\n### Background\nIn this problem, you will write a function that simulates a robot moving around on a grid. The robot starts at a given position on a 2D grid and will move according to a set of commands. Each command tells the robot to move one step in a specified direction (up, down, le... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3053,
"level": 1,
"question": "### Background\nIn this problem, you will write a function that simulates a robot moving around on a grid. The robot starts at a given position on a 2D grid and will move according to a set of commands. Each command tells the robot to move one step in ... |
def largest_rectangle(heights: list) -> int:
stack = [-1] # Initialize stack with -1 to handle the base case
max_area = 0
n = len(heights)
for i in range(n):
# Pop elements from the stack while the top of the stack is taller than current height
while len(stack) > 1 and heights[i] <... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given a list of integers representing the heights of buildings in a row, and your task is to calculate the largest rectangular area that can be formed from consecutive buildings in the row.\n\n### Function Signature\n\n```python\ndef largest_rectangle(he... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3054,
"level": 1,
"question": "### Problem Statement\n\nYou are given a list of integers representing the heights of buildings in a row, and your task is to calculate the largest rectangular area that can be formed from consecutive buildings in the row.\n\n### Function Signature\n\n... |
def two_sum(nums, target):
numToIndex = {}
for i, num in enumerate(nums):
complement = target - num
if complement in numToIndex:
return [numToIndex[complement], i]
numToIndex[num] = i
return None # In case no such pair exists (though problem assumes a solution) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers and returns the indices of two numbers such that they add up to a specific target.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3055,
"level": 1,
"question": "Create a function that takes an array of integers and returns the indices of two numbers such that they add up to a specific target.",
"split": "train"
} |
def three_sum(nums, S):
n = len(nums)
for i in range(n - 2):
# Skip duplicates for the first element
if i > 0 and nums[i] == nums[i-1]:
continue
left = i + 1
right = n - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` sorted in non-decreasing order. Determine if there exist three elements in `nums` such that they sum up to a given target value `S`. Return `true` if such a triplet exists in the array; otherwise, return `false`.\nAnswer:\nLet's think step by step.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3056,
"level": 1,
"question": "You are given an integer array `nums` sorted in non-decreasing order. Determine if there exist three elements in `nums` such that they sum up to a given target value `S`. Return `true` if such a triplet exists in the array; otherwise, return `false`.",... |
from typing import List
def daily_temperatures(temperatures: List[int]) -> List[int]:
stack = []
result = [0] * len(temperatures)
for i in range(len(temperatures)-1, -1, -1):
while stack and stack[-1][0] <= temperatures[i]:
stack.pop()
if stack:
result[i] = stack[-1]... | simplelr_Taco | [
{
"content": "Question:\nIn this challenge, you are given an array of integers representing daily temperatures. You need to create a method that returns an array such that, for each day in the input, it tells you how many days you would have to wait until a warmer temperature. If there is no future day that pro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3057,
"level": 1,
"question": "In this challenge, you are given an array of integers representing daily temperatures. You need to create a method that returns an array such that, for each day in the input, it tells you how many days you would have to wait until a warmer temperature.... |
def filter_long_strings(strings_list):
return [s for s in strings_list if len(s) > 4] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of strings and returns a new list that contains only strings that are longer than 4 characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3058,
"level": 1,
"question": "Write a Python function that takes a list of strings and returns a new list that contains only strings that are longer than 4 characters.",
"split": "train"
} |
def longest_arithmetic_sequence(nums):
n = len(nums)
if n == 0:
return 0
dp = [{} for _ in range(n)]
max_len = 1 # At least one element is present
for i in range(1, n):
for j in range(i):
d = nums[i] - nums[j]
prev = dp[j].get(d, 1)
current = prev... | simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, find the length of the longest arithmetic subsequence (LAS) in the array.\n\nFor this problem, a subsequence is defined as a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. An ari... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3059,
"level": 1,
"question": "Given a list of integers, find the length of the longest arithmetic subsequence (LAS) in the array.\n\nFor this problem, a subsequence is defined as a sequence that can be derived from the array by deleting some or no elements without changing the orde... |
def merge_sorted_lists(list1, list2):
result = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
result.append(list1[i])
i += 1
else:
result.append(list2[j])
j += 1
# Add any remaining elements from list1
re... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that merges two sorted lists into a single sorted list without using any built-in sort functions. The function should traverse both lists and merge them into the resultant list in non-decreasing order.\n\nYour task is to implement this function and test it with a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3060,
"level": 1,
"question": "Write a Python function that merges two sorted lists into a single sorted list without using any built-in sort functions. The function should traverse both lists and merge them into the resultant list in non-decreasing order.\n\nYour task is to impleme... |
import bisect
def findLongestIncreasingSubsequence(arr):
tails = []
for num in arr:
idx = bisect.bisect_left(tails, num)
if idx == len(tails):
tails.append(num)
else:
tails[idx] = num
return len(tails) | simplelr_Data_Structure | [
{
"content": "Question:\nGiven an unsorted array of integers, write a function `findLongestIncreasingSubsequence(arr: List[int]) -> int` to find the length of the longest increasing subsequence.\n\n#### Implementation Requirements\n\n- Implement the function using an approach that has a time complexity of at mo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3061,
"level": 1,
"question": "Given an unsorted array of integers, write a function `findLongestIncreasingSubsequence(arr: List[int]) -> int` to find the length of the longest increasing subsequence.\n\n#### Implementation Requirements\n\n- Implement the function using an approach ... |
def extract_digits(s):
digits = ''
for char in s:
if char.isdigit():
digits += char
return int(digits) if digits else 0
| simplelr_Taco | [
{
"content": "Question:\nYou have been given a string containing a mix of alphabets and digits. Write a function that extracts the digits from the string and returns them as an integer. If no digits are found in the string, return `0`.\n\nExample:\n```python\nextract_digits(\"a1b2c3\")\n> 123\n\nextract_digits(... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3062,
"level": 1,
"question": "You have been given a string containing a mix of alphabets and digits. Write a function that extracts the digits from the string and returns them as an integer. If no digits are found in the string, return `0`.\n\nExample:\n```python\nextract_digits(\"... |
import math
from collections import Counter
def compute_statistics(data: list[int]) -> dict:
data_sorted = sorted(data)
n = len(data)
mean_val = sum(data) / n
if n % 2 == 1:
mediancompute = data_sorted[n // 2]
else:
a = data_sorted[n // 2 - 1]
b = data_sorted[n // 2]
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are required to write a function `compute_statistics` that processes numerical data and computes a set of statistical values. The function should take a list of integers and return a dictionary with the following statistics:\n1. Mean (average) of the data.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3063,
"level": 1,
"question": "### Problem Statement\n\nYou are required to write a function `compute_statistics` that processes numerical data and computes a set of statistical values. The function should take a list of integers and return a dictionary with the following statistics... |
def trapWater(arr, n):
if n < 3:
return 0
left_max = [0] * n
for i in range(1, n):
left_max[i] = max(left_max[i-1], arr[i-1])
right_max = [0] * n
for i in range(n-2, -1, -1):
right_max[i] = max(right_max[i+1], arr[i+1])
total_water = 0
for i in range(n):
... | simplelr_Taco | [
{
"content": "Question:\nImagine you are given an array of integers where each integer represents the height of a building. You need to find the maximum amount of water that can be trapped after raining between the buildings. The structure is such that no water can be trapped at the ends of the array, as these ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3064,
"level": 1,
"question": "Imagine you are given an array of integers where each integer represents the height of a building. You need to find the maximum amount of water that can be trapped after raining between the buildings. The structure is such that no water can be trapped ... |
def remove_duplicates(text: str) -> str:
seen = set()
result = []
for char in text:
if char not in seen:
result.append(char)
seen.add(char)
return ''.join(result) | simplelr_Algorithm | [
{
"content": "Question:\n### Introduction\nIn modern text-processing workflows, it's quite common to clean up and format text input in various ways. One common task is to remove all duplicate characters from a string while preserving the order of their first occurrences.\n\n### Problem\nWrite a function `remove... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3065,
"level": 1,
"question": "### Introduction\nIn modern text-processing workflows, it's quite common to clean up and format text input in various ways. One common task is to remove all duplicate characters from a string while preserving the order of their first occurrences.\n\n##... |
def longest_word(words):
words_set = set(words)
# Sort by descending length, then lex order
sorted_words = sorted(words, key=lambda x: (-len(x), x))
for word in sorted_words:
valid = True
for i in range(1, len(word)):
prefix = word[:i]
if prefix not in words_set:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of strings `words` representing a list of words. You need to find and return the longest word in `words` that can be constructed one character at a time by other words in `words`. If there are multiple possible results, return the one that is lexicographically sma... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3066,
"level": 1,
"question": "You are given an array of strings `words` representing a list of words. You need to find and return the longest word in `words` that can be constructed one character at a time by other words in `words`. If there are multiple possible results, return th... |
def watch(duration, timeSlots):
if duration == 0:
return True
if not timeSlots:
return False
possible_sums = {0}
for num in timeSlots:
to_add = set()
for s in possible_sums:
new_sum = s + num
if new_sum == duration:
return True
... | simplelr_Leetcode | [
{
"content": "Question:\nImagine you have a function `watch(duration, timeSlots)` where `duration` is an integer representing the total duration you want to fill by choosing some, none, or all of the integers in the `timeSlots` list. The function should return a boolean value indicating whether it is possible t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3067,
"level": 1,
"question": "Imagine you have a function `watch(duration, timeSlots)` where `duration` is an integer representing the total duration you want to fill by choosing some, none, or all of the integers in the `timeSlots` list. The function should return a boolean value ... |
def min_completion_time(times):
total = sum(times)
target = total // 2
dp = [False] * (target + 1)
dp[0] = True
for time in times:
for i in range(target, time - 1, -1):
if dp[i - time]:
dp[i] = True
best = 0
for i in range(target, -1, -1):
if dp[i]... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `times` where `times[i]` represents the time needed to complete the `i-th` task. There are two workers and each worker can only work on one task at a time. Your goal is to find the minimum possible time needed to complete all tasks using both workers. Retu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3068,
"level": 1,
"question": "You are given an integer array `times` where `times[i]` represents the time needed to complete the `i-th` task. There are two workers and each worker can only work on one task at a time. Your goal is to find the minimum possible time needed to complete... |
def can_split_into_pairs(arr, m):
from collections import defaultdict
freq = defaultdict(int)
for num in arr:
freq[num] += 1
for num in arr:
if freq[num] == 0:
continue
complement = m - num
if complement not in freq:
return False
if complem... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `arr` of even length `n` and an integer `m`. Your task is to split the array into `n/2` pairs such that the sum of every pair equals `m`. \n\nReturn `true` if the array can be split into the desired pairs, otherwise return `false`.\n\nNote: Ea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3069,
"level": 1,
"question": "You are given a **0-indexed** integer array `arr` of even length `n` and an integer `m`. Your task is to split the array into `n/2` pairs such that the sum of every pair equals `m`. \n\nReturn `true` if the array can be split into the desired pairs, ot... |
from collections import Counter
def count_unique_elements(arr):
counts = Counter(arr)
return sum(1 for num in arr if counts[num] == 1) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to count the number of elements with a unique value in an array of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3070,
"level": 1,
"question": "Write a python function to count the number of elements with a unique value in an array of integers.",
"split": "train"
} |
import re
def reverse_words_preserve_positions(s):
tokens = re.findall(r'\S+|\s+', s)
reversed_tokens = []
for token in tokens:
if token.strip() == '':
reversed_tokens.append(token)
else:
reversed_tokens.append(token[::-1])
return ''.join(reversed_tokens) | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a string as input and returns the string with all its characters in reverse order, but with each word's original position in the string preserved. For instance, given the input `\"hello world\"`, the function should return `\"olleh dlrow\"`. Consider punctuat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3071,
"level": 1,
"question": "Write a function that takes a string as input and returns the string with all its characters in reverse order, but with each word's original position in the string preserved. For instance, given the input `\"hello world\"`, the function should return `... |
from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr | simplelr_Algorithm | [
{
"content": "Question:\n### Context:\nSorting algorithms are fundamental to computer science, enabling the organization of data in an efficient manner. One of the straightforward and easy-to-understand sorting algorithms is the insertion sort. This algorithm is often used for its simplicity and for small datas... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3072,
"level": 1,
"question": "### Context:\nSorting algorithms are fundamental to computer science, enabling the organization of data in an efficient manner. One of the straightforward and easy-to-understand sorting algorithms is the insertion sort. This algorithm is often used for... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def generate_strip_plots(data: pd.DataFrame, strip_params: dict, catplot_params: dict):
"""
Generates a strip plot and a faceted plot from the given dataset and parameters.
Args:
data (pd.DataFrame): The dataset to be visual... | simplelr_Docs | [
{
"content": "Question:\nYou are required to implement a function that generates a customized strip plot from a given dataset. The function should also create a multi-faceted plot to visualize the data on different subsets.\n\n#### Function Signature\n```python\nimport pandas as pd\nimport matplotlib.pyplot as ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3073,
"level": 1,
"question": "You are required to implement a function that generates a customized strip plot from a given dataset. The function should also create a multi-faceted plot to visualize the data on different subsets.\n\n#### Function Signature\n```python\nimport pandas ... |
import os
def list_files_in_directory(directory):
try:
with os.scandir(directory) as entries:
file_names = [entry.name for entry in entries if entry.is_file()]
return file_names
except FileNotFoundError:
print(f"Directory '{directory}' not found.")
return []
exce... | simplelr_Filter | [
{
"content": "Question:\nI need to create a Python function that retrieves a list of all the files in a given directory and returns their names. How can I achieve this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3074,
"level": 1,
"question": "I need to create a Python function that retrieves a list of all the files in a given directory and returns their names. How can I achieve this?",
"split": "train"
} |
from typing import List
def max_profit(prices: List[int]) -> int:
buy1 = buy2 = float('-inf')
sell1 = sell2 = 0
for price in prices:
new_buy1 = max(buy1, -price)
new_sell1 = max(sell1, buy1 + price)
new_buy2 = max(buy2, sell1 - price)
new_sell2 = max(sell2, buy2 + price)
... | simplelr_Apps | [
{
"content": "Question:\nYou are given a list of stock prices in chronological order representing the price of a single stock on different days. Your task is to write a function that finds the maximum profit that can be achieved by buying and selling the stock at most twice. \n\nThe function should accept a lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3075,
"level": 1,
"question": "You are given a list of stock prices in chronological order representing the price of a single stock on different days. Your task is to write a function that finds the maximum profit that can be achieved by buying and selling the stock at most twice. \... |
import bisect
def longest_increasing_subsequence_length(arr):
tails = []
for x in arr:
index = bisect.bisect_left(tails, x)
if index == len(tails):
tails.append(x)
else:
tails[index] = x
return len(tails)
| simplelr_Taco | [
{
"content": "Question:\nA **strictly increasing subsequence** is a sequence that can be derived by deleting some or no elements from another sequence without changing the order of the remaining elements, and where each element is strictly greater than the preceding one.\n\nComplete the function/method that det... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3076,
"level": 1,
"question": "A **strictly increasing subsequence** is a sequence that can be derived by deleting some or no elements from another sequence without changing the order of the remaining elements, and where each element is strictly greater than the preceding one.\n\nCo... |
from collections import Counter
def most_frequent_element(nums):
if not nums:
return None
count = Counter(nums)
current_max_freq = -1
result = None
for num, freq in count.items():
if freq > current_max_freq:
current_max_freq = freq
result = num
elif f... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list of integers and returns the most frequent element. If there are multiple elements with the same highest frequency, return the smallest one among them.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3077,
"level": 1,
"question": "Create a function that takes in a list of integers and returns the most frequent element. If there are multiple elements with the same highest frequency, return the smallest one among them.",
"split": "train"
} |
from typing import List
def snake_matrix(rows: int, columns: int) -> List[List[int]]:
matrix = []
for i in range(rows):
start = 1 + i * columns
elements = list(range(start, start + columns))
if i % 2 == 1:
elements = elements[::-1]
matrix.append(elements)
return ... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Snake Matrix Generation\n\nYou are working on a project that involves generating a matrix with an interesting pattern. Specifically, you need to create a \"snake\" matrix, where the numbers start from 1 and increase continuously in a snake-like pat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3078,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Snake Matrix Generation\n\nYou are working on a project that involves generating a matrix with an interesting pattern. Specifically, you need to create a \"snake\" matrix, where the numbers start from 1 and increa... |
def ipv4_to_ipv6(ip):
octets = ip.split('.')
if len(octets) != 4:
raise ValueError("Invalid IPv4 address")
hex_octets = [format(int(octet), '02x') for octet in octets]
part1 = hex_octets[0] + hex_octets[1]
part2 = hex_octets[2] + hex_octets[3]
return f'::ffff:{part1}:{part2}' | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to convert an IP address from IPv4 to IPv6 format because it is needed for network migration from IPv4 to IPv6. The function should take an IPv4 address as a string and return a corresponding IPv6 address as a string.\nAnswer:\nLet's think step by step.\n",
"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3079,
"level": 1,
"question": "Write a Python function to convert an IP address from IPv4 to IPv6 format because it is needed for network migration from IPv4 to IPv6. The function should take an IPv4 address as a string and return a corresponding IPv6 address as a string.",
"split... |
def sort_list(lst):
return sorted(lst) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to sort a list of integers in ascending order. The function should be named `sort_list` and take a single argument, a list of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3080,
"level": 1,
"question": "Write a python function to sort a list of integers in ascending order. The function should be named `sort_list` and take a single argument, a list of integers.",
"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:\nHow can I create a Python function that checks if a given number is a prime number? Also, how can I use this function to check if the number 29 is a prime number?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3081,
"level": 1,
"question": "How can I create a Python function that checks if a given number is a prime number? Also, how can I use this function to check if the number 29 is a prime number?",
"split": "train"
} |
def min_trips(weights, limit):
weights.sort()
left = 0
right = len(weights) - 1
trips = 0
while left <= right:
if left == right:
trips += 1
break
if (weights[right] + weights[left] + weights[left + 1] <= limit) and (left + 1 <= right):
trips +... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers `weights` representing the weights of parcels you need to deliver. Each parcel can be delivered individually or combined with one or two other parcels in a single trip, provided the total weight of the trip does not exceed the weight limit `limit`. Retur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3082,
"level": 1,
"question": "You are given a list of integers `weights` representing the weights of parcels you need to deliver. Each parcel can be delivered individually or combined with one or two other parcels in a single trip, provided the total weight of the trip does not exc... |
def third_max(nums):
unique_nums = list(set(nums))
unique_nums.sort(reverse=True)
if len(unique_nums) < 3:
return unique_nums[0]
else:
return unique_nums[2] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that finds the third maximum number in a list of integers. If the third maximum number does not exist, return the maximum number.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3083,
"level": 1,
"question": "Create a function that finds the third maximum number in a list of integers. If the third maximum number does not exist, return the maximum number.",
"split": "train"
} |
def maximum_product_of_triplet(arr):
if len(arr) < 3:
return None # or raise ValueError("Array must have at least three elements")
arr.sort()
n = len(arr)
product1 = arr[-1] * arr[-2] * arr[-3]
product2 = arr[0] * arr[1] * arr[-1]
return max(product1, product2) | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function to find the maximum product of any triplet in an array of integers? The function should handle cases with negative numbers and zeros, and should have a time complexity of O(n log n) or better.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3084,
"level": 1,
"question": "Can you provide a Python function to find the maximum product of any triplet in an array of integers? The function should handle cases with negative numbers and zeros, and should have a time complexity of O(n log n) or better.",
"split": "train"
} |
import re
def condense_whitespace(s):
return re.sub(r'\s+', ' ', s).strip()
# Example usage:
# print(condense_whitespace("hello world")) # Output: "hello world"
# print(condense_whitespace(" this\tis a\n test ")) # Output: "this is a test" | simplelr_Evol | [
{
"content": "Question:\nImplement a function called `condense_whitespace` that takes a string containing multiple words separated by varying amounts of whitespace (spaces, tabs, newlines) and returns a single string where all consecutive whitespace characters are reduced to a single space, with no leading or t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3085,
"level": 1,
"question": "Implement a function called `condense_whitespace` that takes a string containing multiple words separated by varying amounts of whitespace (spaces, tabs, newlines) and returns a single string where all consecutive whitespace characters are reduced to a... |
def int_to_hex(n):
if n < 0:
return '-' + hex(abs(n))[2:]
else:
return hex(n)[2:] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes an integer as input and converts it to its hexadecimal representation as a string. The function should handle both positive and negative integers. For negative numbers, the function should return the hexadecimal representation starting with a minus sig... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3086,
"level": 1,
"question": "Write a Python function that takes an integer as input and converts it to its hexadecimal representation as a string. The function should handle both positive and negative integers. For negative numbers, the function should return the hexadecimal repre... |
def smallest_lexicographical_permutation(strings):
return [''.join(sorted(s)) if s else '' for s in strings] | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of strings and returns a new list where each string is replaced by the smallest lexicographical permutation of itself. Make sure the function handles edge cases, such as empty strings or strings with all identical characters. For example, given the lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3087,
"level": 1,
"question": "Write a function that takes a list of strings and returns a new list where each string is replaced by the smallest lexicographical permutation of itself. Make sure the function handles edge cases, such as empty strings or strings with all identical cha... |
def binary_search(arr, x):
low = 0
high = len(arr) - 1
while low <= high:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1 | simplelr_Filter | [
{
"content": "Question:\nThe problem I have is I can't seem to understand how to\n\nimplement a binary search in Python:\n\n```python\ndef binary_search(arr, x):\n low = 0\n high = len(arr) - 1\n mid = 0\n\n while low <= high:\n\n mid = (high + low) // 2\n\n # Check if x is present at ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3088,
"level": 1,
"question": "The problem I have is I can't seem to understand how to\n\nimplement a binary search in Python:\n\n```python\ndef binary_search(arr, x):\n low = 0\n high = len(arr) - 1\n mid = 0\n\n while low <= high:\n\n mid = (high + low) // 2\n\n... |
def find_second_largest(nums: list) -> int:
if len(nums) < 2:
return None
max_num = max(nums)
less_than_max = [num for num in nums if num < max_num]
if not less_than_max:
return None
return max(less_than_max) | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function named `find_second_largest` that will find and return the second largest number in a list of integers. \n\n**Function Signature:**\n\n```python\ndef find_second_largest(nums: list) -> int:\n```\n\n**Parameters:**\n- `nums` (list): A list of intege... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3089,
"level": 1,
"question": "You are tasked with creating a function named `find_second_largest` that will find and return the second largest number in a list of integers. \n\n**Function Signature:**\n\n```python\ndef find_second_largest(nums: list) -> int:\n```\n\n**Parameters:**... |
from typing import List
def has_pair_with_sum(arr: List[int], target: int) -> bool:
seen = set()
for num in arr:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Apps | [
{
"content": "Question:\n## Objective\n\nImplement a function that takes an integer array and a target integer. The goal is to determine if there are two distinct elements in the array whose sum equals the target integer. Return `True` if such a pair exists, otherwise return `False`.\n\n### Constraints\n- The a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3090,
"level": 1,
"question": "## Objective\n\nImplement a function that takes an integer array and a target integer. The goal is to determine if there are two distinct elements in the array whose sum equals the target integer. Return `True` if such a pair exists, otherwise return `... |
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
# Swap elements
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
# Print the state after e... | simplelr_Filter | [
{
"content": "Question:\nGiven a list of numbers, your task is to implement a method to sort this list in ascending order using the bubble sort algorithm. Additionally, for every swap that occurs during the sorting process, the current state of the list should be printed. Your implementation should be done in P... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3091,
"level": 1,
"question": "Given a list of numbers, your task is to implement a method to sort this list in ascending order using the bubble sort algorithm. Additionally, for every swap that occurs during the sorting process, the current state of the list should be printed. Your... |
def is_palindrome(n):
if n < 0:
return False
original = n
reversed_num = 0
while n > 0:
rem = n % 10
reversed_num = reversed_num * 10 + rem
n = n // 10
return reversed_num == original | simplelr_Filter | [
{
"content": "Question:\nI need to write a Python function that checks if a given number is a palindrome. The catch is that I can't use any string operations or the `re` module. How can I do this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3092,
"level": 1,
"question": "I need to write a Python function that checks if a given number is a palindrome. The catch is that I can't use any string operations or the `re` module. How can I do this?",
"split": "train"
} |
import math
def sieve_of_eratosthenes(limit):
if limit < 2:
return []
sieve = [True] * (limit + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(math.sqrt(limit)) + 1):
if sieve[i]:
sieve[i*i : limit+1 : i] = [False] * len(sieve[i*i : limit+1 : i])
primes = [i for i,... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to generate all prime numbers up to a given limit using the Sieve of Eratosthenes algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3093,
"level": 1,
"question": "Write a function to generate all prime numbers up to a given limit using the Sieve of Eratosthenes algorithm.",
"split": "train"
} |
def bin_to_int(bin_str):
"""Converts a binary string to an integer."""
return int(bin_str, 2) | simplelr_Filter | [
{
"content": "Question:\nThere’s no need to reinvent the wheel. Here's one of the popular methods used for converting a binary string to an integer in Python:\n\n\n\ndef bin_to_int(bin_str):\n \"\"\"Converts a binary string to an integer.\"\"\"\n return int(bin_str, 2)\n```\n\nIn this function, `int(bin_str, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3094,
"level": 1,
"question": "There’s no need to reinvent the wheel. Here's one of the popular methods used for converting a binary string to an integer in Python:\n\n\n\ndef bin_to_int(bin_str):\n \"\"\"Converts a binary string to an integer.\"\"\"\n return int(bin_str, 2)\n```\... |
def enhanced_selection_sort(arr):
arr_copy = arr.copy()
comparisons = 0
steps = []
n = len(arr_copy)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
comparisons += 1
if arr_copy[j] < arr_copy[min_idx]:
min_idx = j
if min_id... | simplelr_Data_Structure | [
{
"content": "Question:\n### Selection Sort with Detailed Analysis\n\nYou are given an implementation of the **Selection Sort** algorithm. Your task is to enhance this implementation to handle detailed analysis and validation of the sorting process.\n\n### Requirements\n\n1. **Function Signature:** \n ```pyth... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3095,
"level": 1,
"question": "### Selection Sort with Detailed Analysis\n\nYou are given an implementation of the **Selection Sort** algorithm. Your task is to enhance this implementation to handle detailed analysis and validation of the sorting process.\n\n### Requirements\n\n1. *... |
def check_odd_length(arr):
count = 0
for _ in arr:
count += 1
return 'yes' if count % 2 else 'no' | simplelr_Filter | [
{
"content": "Question:\nVerify the correctness of the following Python program. It should return 'yes' if an array contains an odd number of elements and 'no' if it does not. For an empty array, it should return 'no'. Implement a function `check_odd_length` that takes an array as input without using built-in P... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3096,
"level": 1,
"question": "Verify the correctness of the following Python program. It should return 'yes' if an array contains an odd number of elements and 'no' if it does not. For an empty array, it should return 'no'. Implement a function `check_odd_length` that takes an arra... |
def is_perfect_square(n: int) -> bool:
"""
Check if a given integer is a perfect square.
Parameters:
n (int): The integer to check.
Returns:
bool: True if the integer is a perfect square, False otherwise
Examples:
>>> is_perfect_square(16)
True
>>> is_perfect_square(15)
Fa... | simplelr_Algorithm | [
{
"content": "Question:\n### Task\n\nWrite a function that checks if a given integer is a perfect square using bit manipulation techniques and mathematical insights without using any built-in library functions or floating-point arithmetic.\n\n### Requirements\nCreate a function `is_perfect_square` that takes an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3097,
"level": 1,
"question": "### Task\n\nWrite a function that checks if a given integer is a perfect square using bit manipulation techniques and mathematical insights without using any built-in library functions or floating-point arithmetic.\n\n### Requirements\nCreate a functio... |
def has_duplicate_characters(s):
return len(s) != len(set(s)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find whether the string `s` contains any duplicate characters. If it does, return `True` else `False`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3098,
"level": 1,
"question": "Write a python function to find whether the string `s` contains any duplicate characters. If it does, return `True` else `False`.",
"split": "train"
} |
def longest_common_subsequence(word1, word2):
m = len(word1)
n = len(word2)
# Create a DP table of (m+1) rows and (n+1) columns initialized to 0
dp = [[0] * (n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if word1[i-1] == word2[j-1]:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings `word1` and `word2`. You want to construct the longest string `s` such that `s` is a subsequence of both `word1` and `word2`. A subsequence of a string is obtained by deleting some (possibly none) characters from the string without changing the order of the rem... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3099,
"level": 1,
"question": "You are given two strings `word1` and `word2`. You want to construct the longest string `s` such that `s` is a subsequence of both `word1` and `word2`. A subsequence of a string is obtained by deleting some (possibly none) characters from the string wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.