target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
from typing import List
def increment_number(digits: List[int]) -> List[int]:
copied_digits = digits.copy()
carry = 1
n = len(copied_digits)
for i in range(n-1, -1, -1):
total = copied_digits[i] + carry
if total < 10:
copied_digits[i] = total
carry = 0
... | simplelr_Data_Structure | [
{
"content": "Question:\n**Problem Statement:**\n\nYou are given a list of non-negative integers where each integer represents a digit of a non-negative number. The list is arranged such that the most significant digit is at the head of the list. Your task is to write a function that increments the number repre... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8700,
"level": 1,
"question": "**Problem Statement:**\n\nYou are given a list of non-negative integers where each integer represents a digit of a non-negative number. The list is arranged such that the most significant digit is at the head of the list. Your task is to write a functi... |
import numpy as np
def custom_kernel(X, Y, gamma=1.0, alpha=1.0, c0=0.0, degree=3):
"""
Custom kernel combining RBF and Polynomial kernels.
Parameters:
- X: np.ndarray of shape (n_samples_X, n_features)
- Y: np.ndarray of shape (n_samples_Y, n_features)
- gamma: float, parameter for the RBF ke... | simplelr_Docs | [
{
"content": "Question:\n### Custom Kernel Function Implementation and Utilization\n\n#### Problem Statement\n\nYou are tasked with implementing a custom kernel function and utilizing it to compute a pairwise kernel matrix using `sklearn` utilities. The custom kernel function will be a combination of the RBF (R... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8701,
"level": 1,
"question": "### Custom Kernel Function Implementation and Utilization\n\n#### Problem Statement\n\nYou are tasked with implementing a custom kernel function and utilizing it to compute a pairwise kernel matrix using `sklearn` utilities. The custom kernel function ... |
def get_sum_of_squares(numbers):
return sum(num ** 2 for num in numbers) | simplelr_Filter | [
{
"content": "Question:\nLet's define a function called *get_sum_of_squares* \n\nIt should take a list of numbers as input and return the sum of the squares of those numbers.\n\n\n```python\ndef get_sum_of_squares(numbers):\n \"\"\"\n This function takes a list of numbers and returns the \n sum of the square... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8702,
"level": 1,
"question": "Let's define a function called *get_sum_of_squares* \n\nIt should take a list of numbers as input and return the sum of the squares of those numbers.\n\n\n```python\ndef get_sum_of_squares(numbers):\n \"\"\"\n This function takes a list of numbers an... |
from typing import List
def move_zeros_to_end(nums: List[int]) -> List[int]:
write_pos = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[write_pos], nums[i] = nums[i], nums[write_pos]
write_pos += 1
return nums | simplelr_Algorithm | [
{
"content": "Question:\n## Problem Statement\nGiven an integer array `nums`, write a function `move_zeros_to_end` that moves all zeros present in the array to the end while maintaining the relative order of non-zero elements.\n\n### Function Signature\n```python\ndef move_zeros_to_end(nums: List[int]) -> List[... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8703,
"level": 1,
"question": "## Problem Statement\nGiven an integer array `nums`, write a function `move_zeros_to_end` that moves all zeros present in the array to the end while maintaining the relative order of non-zero elements.\n\n### Function Signature\n```python\ndef move_zer... |
def multiply(a, b):
"""
Returns the product of two numbers.
Parameters:
a (int): The first number
b (int): The second number
Returns:
int: The product of a and b
"""
return a * b
result = multiply(5, 7)
print("The product is: ", result) | simplelr_Filter | [
{
"content": "Question:\n### Introduction to Functions\n#### Introduction to Functions\nFunctions are reusable blocks of code that perform a specific task. They are essential in programming as they:\n* Reduce code duplication\n* Improve code readability\n* Make code more maintainable\n* Enable modular programmi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8704,
"level": 1,
"question": "### Introduction to Functions\n#### Introduction to Functions\nFunctions are reusable blocks of code that perform a specific task. They are essential in programming as they:\n* Reduce code duplication\n* Improve code readability\n* Make code more maint... |
def island_perimeter(grid):
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
perimeter = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
count = 0
if i > 0 and grid[i-1][j] == 1:
count += 1
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a grid of `m x n` `0s` and `1s`. A `0` represents water, and a `1` represents land. An island is a group of `1`s connected horizontally or vertically. The grid is surrounded by water, and there will be exactly one island (i.e., one or more connected `1`s). \n\nDetermine th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8705,
"level": 1,
"question": "You are given a grid of `m x n` `0s` and `1s`. A `0` represents water, and a `1` represents land. An island is a group of `1`s connected horizontally or vertically. The grid is surrounded by water, and there will be exactly one island (i.e., one or mor... |
def UpdateInventory(inventory: dict, transactions: list) -> dict:
new_inv = inventory.copy()
for trans in transactions:
product_id, t_type, qty = trans
if t_type == 'add':
if product_id in new_inv:
new_inv[product_id] += qty
else:
new_inv[p... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function that simulates a simple inventory management system for a warehouse. The warehouse inventory is represented as a dictionary where the keys are product IDs (integers) and the values are the quantities of each product (integers). \n\nYou need to imp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8706,
"level": 1,
"question": "You are tasked with creating a function that simulates a simple inventory management system for a warehouse. The warehouse inventory is represented as a dictionary where the keys are product IDs (integers) and the values are the quantities of each prod... |
import heapq
from typing import List
def find_top_three(nums: List[int]) -> List[int]:
unique_nums = list(set(nums))
top_three = heapq.nlargest(3, unique_nums)
result = top_three.copy()
while len(result) < 3:
result.append(None)
return result | simplelr_Evol | [
{
"content": "Question:\nGiven a list of numbers, create a function that finds the three largest numbers and returns them in a new list sorted in descending order. \n\nFunction Signature: \n```python\ndef find_top_three(nums: List[int]) -> List[int]:\n```\n\nInput:\n- nums: A list of integers.\n\nOutput:\n- A l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8707,
"level": 1,
"question": "Given a list of numbers, create a function that finds the three largest numbers and returns them in a new list sorted in descending order. \n\nFunction Signature: \n```python\ndef find_top_three(nums: List[int]) -> List[int]:\n```\n\nInput:\n- nums: A ... |
from collections import Counter
def first_non_repeating_char(s):
if not s:
return "No unique characters found"
freq = Counter(s)
for char in s:
if freq[char] == 1:
return char
return "No unique characters found"
# Test cases
print(first_non_repeating_char("aabbccd")) # Ex... | simplelr_Evol | [
{
"content": "Question:\nConstruct a function that processes an input string and finds the first non-repeating character. If the string contains no unique characters, the function should return a specific message indicating this. Optimize the solution for efficiency both in terms of time and space complexity, a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8708,
"level": 1,
"question": "Construct a function that processes an input string and finds the first non-repeating character. If the string contains no unique characters, the function should return a specific message indicating this. Optimize the solution for efficiency both in te... |
from typing import List
def validate_booking_codes(codes: List[str]) -> List[str]:
result = []
for code in codes:
has_letter = False
has_digit = False
for char in code:
if char.isupper():
has_letter = True
elif char.isdigit():
has_... | simplelr_Code_Contests | [
{
"content": "Question:\nA flight booking system keeps a record of reservations using booking codes that follow a specific pattern. Each booking code consists of uppercase English letters and digits, and has a minimum length of 5 and a maximum length of 10. However, to meet business standards, the system impose... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8709,
"level": 1,
"question": "A flight booking system keeps a record of reservations using booking codes that follow a specific pattern. Each booking code consists of uppercase English letters and digits, and has a minimum length of 5 and a maximum length of 10. However, to meet bu... |
def longest_arith_seq_length(arr):
n = len(arr)
if n == 0:
return 0
if n == 1:
return 1
max_len = 2 # Minimum possible is 2
dp = [{} for _ in range(n)]
for i in range(1, n):
for j in range(i):
d = arr[i] - arr[j]
current_length = 2 # At... | simplelr_Apps | [
{
"content": "Question:\nWrite a function `longest_arith_seq_length` that receives a list of integers and returns the length of the longest arithmetic subsequence in the list. An arithmetic subsequence is a subsequence that follows the property where the difference between consecutive elements is always the sam... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8710,
"level": 1,
"question": "Write a function `longest_arith_seq_length` that receives a list of integers and returns the length of the longest arithmetic subsequence in the list. An arithmetic subsequence is a subsequence that follows the property where the difference between con... |
def length_of_longest_unique_substring(s):
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 - left + 1... | simplelr_Codeforces | [
{
"content": "Question:\nYou're given a string `s` consisting of lowercase alphabets. A substring is defined as a contiguous sequence of characters within the string. A unique substring is defined as a substring that has no repeated characters. \n\nWrite a function that returns the length of the longest unique ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8711,
"level": 1,
"question": "You're given a string `s` consisting of lowercase alphabets. A substring is defined as a contiguous sequence of characters within the string. A unique substring is defined as a substring that has no repeated characters. \n\nWrite a function that return... |
def spiral_order(matrix):
if not matrix:
return []
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
# Traverse from left to right on top row
for i in range(left, right + 1):
result.append(matri... | simplelr_Filter | [
{
"content": "Question:\nGiven the following 2d array. Create a function that prints the array in a clockwise spiral order. The function should also be able to handle arrays of different sizes.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8712,
"level": 1,
"question": "Given the following 2d array. Create a function that prints the array in a clockwise spiral order. The function should also be able to handle arrays of different sizes.",
"split": "train"
} |
def is_semi_palindrome(s):
length = len(s)
if length % 2 != 0:
return False
mid = length // 2
first_half = s[:mid]
second_half = s[mid:]
return first_half[::-1] == second_half | simplelr_Filter | [
{
"content": "Question:\nI am trying to verify if a string is a semi-palindrome using Python. A semi-palindrome is defined as a string that can be split into two equal parts, where the first part is the reverse of the second part. For example, \"abccba\" is not a semi-palindrome, but \"abba\" or \"noon\" are. H... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8713,
"level": 1,
"question": "I am trying to verify if a string is a semi-palindrome using Python. A semi-palindrome is defined as a string that can be split into two equal parts, where the first part is the reverse of the second part. For example, \"abccba\" is not a semi-palindro... |
def sort_strings_by_length(string_list):
return sorted(string_list, key=len) | simplelr_Filter | [
{
"content": "Question:\nGiven a list of strings, write a function in Python to sort the strings based on the length of the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8714,
"level": 1,
"question": "Given a list of strings, write a function in Python to sort the strings based on the length of the string.",
"split": "train"
} |
def longestPalindrome(s: str) -> str:
n = len(s)
if n < 2:
return s
# Initialize DP table
dp = [[False] * n for _ in range(n)]
for i in range(n):
dp[i][i] = True
max_len = 1
start = 0
for j in range(1, n):
for i in range(j):
if s[i] == s[j]:
... | simplelr_Filter | [
{
"content": "Question:\nThis is the prompt:\n\nGiven a string, find the longest palindrome substring within that string.\n\nFor example:\n\nInput: \"babad\"\nOutput: \"bab\"\n\nInput: \"cbbd\"\nOutput: \"bb\"\n\n**Constraints:**\n\n* 1 <= s.length <= 1000\n* s consist of only digits and English letters.\n\n**C... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8715,
"level": 1,
"question": "This is the prompt:\n\nGiven a string, find the longest palindrome substring within that string.\n\nFor example:\n\nInput: \"babad\"\nOutput: \"bab\"\n\nInput: \"cbbd\"\nOutput: \"bb\"\n\n**Constraints:**\n\n* 1 <= s.length <= 1000\n* s consist of only... |
import xml.etree.ElementTree as ET
from datetime import datetime
from xml.dom import minidom
def modify_xml(xml_str: str) -> str:
root = ET.fromstring(xml_str)
current_year = datetime.now().year
for book in root.findall('book'):
# Update the year to current year if it's earlier than 2010
y... | simplelr_Docs | [
{
"content": "Question:\n### XML Document Manipulation with `xml.etree.ElementTree`\n\n**Objective**: \nWrite a Python function that parses a given XML string, modifies certain elements based on specified criteria, and returns the modified XML as a string.\n\n**Function Signature**:\n```python\ndef modify_xml(... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8716,
"level": 1,
"question": "### XML Document Manipulation with `xml.etree.ElementTree`\n\n**Objective**: \nWrite a Python function that parses a given XML string, modifies certain elements based on specified criteria, and returns the modified XML as a string.\n\n**Function Signa... |
def duplicate_characters(s: str) -> dict:
char_count = {}
for char in s.lower():
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
result = {k: v for k, v in char_count.items() if v > 1}
return result | simplelr_Package | [
{
"content": "Question:\n### Objective:\nDevelop a function named `duplicate_characters` that receives a string and returns a dictionary with each character that appears more than once in the string and the number of times it appears. The function should be case-insensitive.\n\n### Input:\nA single string `s` w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8717,
"level": 1,
"question": "### Objective:\nDevelop a function named `duplicate_characters` that receives a string and returns a dictionary with each character that appears more than once in the string and the number of times it appears. The function should be case-insensitive.\n... |
import pandas as pd
def task_func(df):
"""
Given a pandas DataFrame with numerical columns, normalize each column to have mean 0 and variance 1.
Args:
df (DataFrame): A pandas DataFrame with numerical columns.
Returns:
DataFrame: A DataFrame with the normalized columns.
"""
no... | simplelr_Package | [
{
"content": "Question:\n```python\nimport pandas as pd\n\ndef task_func(df):\n \"\"\"\n Given a pandas DataFrame with numerical columns, normalize each column to have mean 0 and variance 1.\n \n Args:\n df (DataFrame): A pandas DataFrame with numerical columns.\n \n Returns:\n DataFrame... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8718,
"level": 1,
"question": "```python\nimport pandas as pd\n\ndef task_func(df):\n \"\"\"\n Given a pandas DataFrame with numerical columns, normalize each column to have mean 0 and variance 1.\n \n Args:\n df (DataFrame): A pandas DataFrame with numerical columns.... |
def min_possible_value(arr):
return sum(arr) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array `arr` of `n` integers. You can perform the following operation on the array as many times as you want: \n\n* Choose any two adjacent elements `arr[i]` and `arr[i+1]` (0 <= i < n-1) and replace them with a single element that is their sum.\n\nYour task is to determ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8719,
"level": 1,
"question": "You are given an array `arr` of `n` integers. You can perform the following operation on the array as many times as you want: \n\n* Choose any two adjacent elements `arr[i]` and `arr[i+1]` (0 <= i < n-1) and replace them with a single element that is t... |
def longest_common_substring(s1, s2):
m = len(s1)
n = len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
max_length = 0
end = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
if dp[i][j] ... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code to find the longest common substring between two strings.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8720,
"level": 1,
"question": "Write a Python code to find the longest common substring between two strings.",
"split": "train"
} |
from typing import List
def max_books_subset(heights: List[int], k: int) -> int:
heights.sort()
n = len(heights)
max_size = 0
right = 0
for left in range(n):
while right < n and heights[right] - heights[left] <= k:
right += 1
current_size = right - left
if curren... | simplelr_Code_Contests | [
{
"content": "Question:\nOne day, you come across a peculiar bookshelf in a library. This bookshelf has books arranged in such a way that every book has its unique height. You wish to pick a subset of these books such that the height difference between the tallest and shortest book in the subset does not exceed... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8721,
"level": 1,
"question": "One day, you come across a peculiar bookshelf in a library. This bookshelf has books arranged in such a way that every book has its unique height. You wish to pick a subset of these books such that the height difference between the tallest and shortest... |
def transform_string(s):
digit_to_word = {
'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three',
'4': 'four',
'5': 'five',
'6': 'six',
'7': 'seven',
'8': 'eight',
'9': 'nine'
}
result = []
for c in s:
if c in digit_to_w... | simplelr_Taco | [
{
"content": "Question:\nGiven a string consisting of digits and lowercase letters, return the original string transformed as follows:\n\n1. Replace each digit by its corresponding English word in lowercase.\n2. Replace each lowercase letter by its position in the alphabet (e.g., 'a' -> 1, 'b' -> 2 ... 'z' -> 2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8722,
"level": 1,
"question": "Given a string consisting of digits and lowercase letters, return the original string transformed as follows:\n\n1. Replace each digit by its corresponding English word in lowercase.\n2. Replace each lowercase letter by its position in the alphabet (e.... |
def sum_of_digits(n: int) -> int:
"""
This function calculates the sum of the digits of an integer.
Args:
n (int): The integer whose digits will be summed.
Returns:
int: The sum of the digits of the input integer.
"""
return sum(int(digit) for digit in str(abs(n))) | simplelr_Filter | [
{
"content": "Question:\nHello! I have a question about Python programming. How can I create a function that takes an integer as input and returns the sum of its digits?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8723,
"level": 1,
"question": "Hello! I have a question about Python programming. How can I create a function that takes an integer as input and returns the sum of its digits?",
"split": "train"
} |
def remove_duplicates(species):
result = []
seen = set()
for s in species:
if s not in seen:
result.append(s)
seen.add(s)
return result
| simplelr_Taco | [
{
"content": "Question:\nA research organization maintains a database of species observations from various expeditions. Recently, they noticed that some of their entries have duplicate species names due to a data entry error. They need a way to filter out these duplicates but preserve the first occurrence of ea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8724,
"level": 1,
"question": "A research organization maintains a database of species observations from various expeditions. Recently, they noticed that some of their entries have duplicate species names due to a data entry error. They need a way to filter out these duplicates but ... |
def modify_list(lst):
return [x * 2 if i % 2 == 0 else x for i, x in enumerate(lst)] | simplelr_Filter | [
{
"content": "Question:\nCreate a function in Python that takes a list of integers and multiplies each even indexed element by 2. The function should return the modified list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8725,
"level": 1,
"question": "Create a function in Python that takes a list of integers and multiplies each even indexed element by 2. The function should return the modified list.",
"split": "train"
} |
import csv
def read_csv_to_dicts(filename):
with open(filename, 'r') as csvfile:
csv_reader = csv.DictReader(csvfile)
rows = list(csv_reader)
return rows | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python function that reads a CSV file and returns a list of dictionaries, where each dictionary represents a row in the CSV file? Each key in the dictionary should correspond to a column header in the CSV file.\nAnswer:\nLet's think step by step.\n",
"role": "... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8726,
"level": 1,
"question": "Can you help me with a Python function that reads a CSV file and returns a list of dictionaries, where each dictionary represents a row in the CSV file? Each key in the dictionary should correspond to a column header in the CSV file.",
"split": "trai... |
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1) | simplelr_Filter | [
{
"content": "Question:\nHello, I'm a student learning about recursion in programming. Could you explain recursion with an example in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8727,
"level": 1,
"question": "Hello, I'm a student learning about recursion in programming. Could you explain recursion with an example in Python?",
"split": "train"
} |
def sum_of_multiples(numbers):
total = 0
for num in numbers:
if num % 3 == 0 or num % 5 == 0:
total += num
return total | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns the sum of all integers that are multiples of either 3 or 5.\n\nFor example:\n```\nsum_of_multiples([1, 2, 3, 4, 5, 6]) = 14 \n-- because 3, 5, and 6 are multiples of 3 or 5, and 3 + 5 + 6 = 14\n\nsum_of_multiples([10, 11, 12, 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8728,
"level": 1,
"question": "Write a function that takes a list of integers and returns the sum of all integers that are multiples of either 3 or 5.\n\nFor example:\n```\nsum_of_multiples([1, 2, 3, 4, 5, 6]) = 14 \n-- because 3, 5, and 6 are multiples of 3 or 5, and 3 + 5 + 6 = 14... |
def find_substring_indices(s: str, t: str) -> list[int]:
indices = []
start = 0
t_len = len(t)
s_len = len(s)
if t_len == 0:
return indices
if t_len > s_len:
return indices
while start <= s_len - t_len:
pos = s.find(t, start)
if pos == -1:
... | simplelr_Filter | [
{
"content": "Question:\nGiven a string `s` and a target substring `t`, find all starting indices of `s` where `t` is a substring. Return the list of indices in ascending order. The function should be efficient and handle large strings.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8729,
"level": 1,
"question": "Given a string `s` and a target substring `t`, find all starting indices of `s` where `t` is a substring. Return the list of indices in ascending order. The function should be efficient and handle large strings.",
"split": "train"
} |
def reverse_string(s):
return ''.join([s[i] for i in range(-1, -len(s)-1, -1)]) | simplelr_Filter | [
{
"content": "Question:\nGenerate a Python code to find the reverse of a given string, but you are not allowed to use any built-in string reversal methods or functions. Additionally, you should implement the reversal algorithm in a single line of code using list comprehension.\nAnswer:\nLet's think step by step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8730,
"level": 1,
"question": "Generate a Python code to find the reverse of a given string, but you are not allowed to use any built-in string reversal methods or functions. Additionally, you should implement the reversal algorithm in a single line of code using list comprehension.... |
def prime_factors(n):
if n < 1:
return []
factors = []
# Handle the case for 2 separately
while n % 2 == 0:
factors.append(2)
n = n // 2
# Now check for odd factors
i = 3
while i * i <= n:
while n % i == 0:
factors.append(i)
n = n // i
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function called `prime_factors` which takes an integer as an argument and returns a list of its prime factors in the decreasing order. Make sure that large integers are handled efficiently. Additionally, debug the provided erroneous code example that aims to solve the tas... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8731,
"level": 1,
"question": "Write a Python function called `prime_factors` which takes an integer as an argument and returns a list of its prime factors in the decreasing order. Make sure that large integers are handled efficiently. Additionally, debug the provided erroneous code... |
def max_product(nums):
nums.sort()
product1 = nums[-1] * nums[-2]
product2 = nums[0] * nums[1]
return max(product1, product2) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list of integers and returns the maximum product that can be obtained by multiplying any two numbers from the list. The list is guaranteed to have at least two integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8732,
"level": 1,
"question": "Create a function that takes in a list of integers and returns the maximum product that can be obtained by multiplying any two numbers from the list. The list is guaranteed to have at least two integers.",
"split": "train"
} |
def find_winners(arr):
n = len(arr)
winners = []
for i in range(1, n - 1):
if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
winners.append(arr[i])
return winners | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** array `arr` consisting of `n` distinct integers. A **winner** is an element that is greater than the previous and the next element in the array (if they exist). * Formally, an element `arr[i]` is a winner if `arr[i] > arr[i - 1]` and `arr[i] > arr[i + 1]... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8733,
"level": 1,
"question": "You are given a **0-indexed** array `arr` consisting of `n` distinct integers. A **winner** is an element that is greater than the previous and the next element in the array (if they exist). * Formally, an element `arr[i]` is a winner if `arr[i] > a... |
def two_sum(numbers, target):
seen = set()
for num in numbers:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Filter | [
{
"content": "Question:\nThis challenge requires you to write a function that takes two arguments:\n\n `numbers`: A list of integers.\n `target`: An integer representing the target sum.\n\nThe function should return `True` if there are two numbers in the list that add up to the target sum, and `False` other... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8734,
"level": 1,
"question": "This challenge requires you to write a function that takes two arguments:\n\n `numbers`: A list of integers.\n `target`: An integer representing the target sum.\n\nThe function should return `True` if there are two numbers in the list that add up t... |
def length_of_longest_good_substring(s):
char_index = {} # Dictionary to keep track of the last index of each character
max_length = 0 # Variable to store the maximum length found
left = 0 # Left pointer of the sliding window
for right in range(len(s)):
char = s[right]
#... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase Latin letters. A \"good\" substring is defined as a substring that contains no repeated characters. Your task is to find the length of the longest \"good\" substring in `s`. A substring is defined as a contiguous sequence of characters ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8735,
"level": 1,
"question": "You are given a string `s` consisting of lowercase Latin letters. A \"good\" substring is defined as a substring that contains no repeated characters. Your task is to find the length of the longest \"good\" substring in `s`. A substring is defined as a... |
def reverse_words(sentence):
words = sentence.split()
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function to reverse the words in a given sentence while keeping the words in their original positions. For example:\n\n```\n\"Hello from the other side\" --> \"olleH morf eht rehto edis\"\n\"Test case for reverse\" --> \"tseT esac rof esrever\"\n```\nAnswer:\nLet's think... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8736,
"level": 1,
"question": "Write a function to reverse the words in a given sentence while keeping the words in their original positions. For example:\n\n```\n\"Hello from the other side\" --> \"olleH morf eht rehto edis\"\n\"Test case for reverse\" --> \"tseT esac rof e... |
def shift_digits(n, k):
if n == 0:
return 0
sign = 1 if n > 0 else -1
s = str(abs(n))
len_s = len(s)
if k >= len_s:
return 0
shifted = s[k:] + s[:k]
return sign * int(shifted) | simplelr_Apps | [
{
"content": "Question:\nCreate a function to shift the digits of an integer to the left by a given number of positions. If the number is positive, the shifted digits should remain positive, and if the number is negative, the shifted digits should remain negative. The function should handle both positive and ne... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8737,
"level": 1,
"question": "Create a function to shift the digits of an integer to the left by a given number of positions. If the number is positive, the shifted digits should remain positive, and if the number is negative, the shifted digits should remain negative. The function... |
def format_mixed_list(data_list: list, float_precision: int) -> str:
if not isinstance(data_list, list):
return "<error>"
elements = []
for element in data_list:
if isinstance(element, str):
elements.append(element)
elif isinstance(element, int):
elements... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nCreate a function that takes a list of mixed data types (integers, floats, and strings) and converts it to a formatted string. The function should:\n1. Convert numbers to strings with a specified number of decimal places for floats.\n2. Handle and format each element ap... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8738,
"level": 1,
"question": "#### Objective:\nCreate a function that takes a list of mixed data types (integers, floats, and strings) and converts it to a formatted string. The function should:\n1. Convert numbers to strings with a specified number of decimal places for floats.\n2... |
from typing import List
def counting_sort(arr: List[int]) -> List[int]:
if not arr:
return []
min_val = min(arr)
max_val = max(arr)
count_size = max_val - min_val + 1
count = [0] * count_size
for num in arr:
idx = num - min_val
count[idx] += 1
result =... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a list of integers that may include negative values. Your task is to implement the Counting Sort algorithm to sort the array in non-decreasing order. \n\n### Function Signature\n```python\ndef counting_sort(arr: List[int]) -> List[int]:\n```\n\n### Input\n* `arr`: List of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8739,
"level": 1,
"question": "You are given a list of integers that may include negative values. Your task is to implement the Counting Sort algorithm to sort the array in non-decreasing order. \n\n### Function Signature\n```python\ndef counting_sort(arr: List[int]) -> List[int]:\n... |
import re
def is_valid_number(s):
pattern = r'^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$'
return re.fullmatch(pattern, s) is not None | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to determine if a string is a valid number. A valid number can be a integer, a float, or a number in scientific notation. The function should return `True` if the string is a valid number, and `False` otherwise.\nAnswer:\nLet's think step by step.\n",
"role": "user"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8740,
"level": 1,
"question": "Write a function to determine if a string is a valid number. A valid number can be a integer, a float, or a number in scientific notation. The function should return `True` if the string is a valid number, and `False` otherwise.",
"split": "train"
} |
def cutRod(L, price):
dp = [0] * (L + 1)
for i in range(1, L + 1):
max_val = 0
for j in range(1, i + 1):
current = price[j-1] + dp[i-j]
if current > max_val:
max_val = current
dp[i] = max_val
return dp[L]
| simplelr_Taco | [
{
"content": "Question:\nYou are given a rod of length L inches. You need to cut the rod into one or more pieces such that the total value obtained by selling the pieces is maximized. The value of each piece of length i inches is given by a price array price[] where price[i] is the value of a piece of length i.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8741,
"level": 1,
"question": "You are given a rod of length L inches. You need to cut the rod into one or more pieces such that the total value obtained by selling the pieces is maximized. The value of each piece of length i inches is given by a price array price[] where price[i] i... |
import heapq
def find_k_smallest_pairs(nums1, nums2, k):
if not nums1 or not nums2 or k == 0:
return []
heap = []
visited = set()
# Initialize with the first pair
heapq.heappush(heap, (nums1[0] + nums2[0], nums1[0], nums2[0], 0, 0))
visited.add((0, 0))
result = []
... | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a Python function called `find_k_smallest_pairs` that takes two input lists of integers and an integer k and returns a list of k smallest sum pairs (us.pi, vj). Each pair should be represented as a tuple (us.pi, vj) where us.pi belongs to the first list and vj to the second list. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8742,
"level": 1,
"question": "Write a Python function called `find_k_smallest_pairs` that takes two input lists of integers and an integer k and returns a list of k smallest sum pairs (us.pi, vj). Each pair should be represented as a tuple (us.pi, vj) where us.pi belongs to the fir... |
def read_file(filename):
with open(filename, 'r', encoding='utf-8') as file:
content = file.read()
return content | simplelr_Filter | [
{
"content": "Question:\nCan you explain how to implement a `read_file` function in Python that reads the contents of a file and returns it as a string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8743,
"level": 1,
"question": "Can you explain how to implement a `read_file` function in Python that reads the contents of a file and returns it as a string?",
"split": "train"
} |
def is_strictly_increasing(lst: list) -> bool:
if len(lst) <= 1:
return True
for i in range(1, len(lst)):
if lst[i] <= lst[i-1]:
return False
return True | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Context\nIn many scenarios within computer science, it is crucial to assess whether a given sequence of numbers satisfies specific properties. One common task is to determine if a sequence follows a strictly increasing pattern, where each subsequent number is greater than th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8744,
"level": 1,
"question": "### Problem Context\nIn many scenarios within computer science, it is crucial to assess whether a given sequence of numbers satisfies specific properties. One common task is to determine if a sequence follows a strictly increasing pattern, where each s... |
def longest_substring_with_k_distinct(s: str, k: int) -> int:
if k == 0 or not s:
return 0
freq = {}
distinct = set()
max_len = 0
left = 0
for right in range(len(s)):
c = s[right]
if c in freq:
freq[c] += 1
else:
freq[c] = 1
... | simplelr_Evol | [
{
"content": "Question:\nImplement a function `longest_substring_with_k_distinct` that takes two parameters: a string `s` and an integer `k`. The function should return the length of the longest substring of `s` that contains at most `k` distinct characters. If `k` is 0 or if the string is empty, return 0. Cons... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8745,
"level": 1,
"question": "Implement a function `longest_substring_with_k_distinct` that takes two parameters: a string `s` and an integer `k`. The function should return the length of the longest substring of `s` that contains at most `k` distinct characters. If `k` is 0 or if ... |
def reverse_binary_string(s):
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse a binary string. The function should take one binary string as input and return the reversed binary string. For example, if the input is \"10101\", the function should return \"10101\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8746,
"level": 1,
"question": "Write a function to reverse a binary string. The function should take one binary string as input and return the reversed binary string. For example, if the input is \"10101\", the function should return \"10101\".",
"split": "train"
} |
def max_subarray_sum(arr):
if not arr:
return 0
max_current = max_global = arr[0]
for num in arr[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global | simplelr_Filter | [
{
"content": "Question:\nThis is a coding challenge for Python:\n\n**Challenge:**\n\nYou are given a list of integers. Your task is to find the maximum sum of a contiguous subarray within the list.\n\n**Example:**\n\nInput: `[-2, 1, -3, 4, -1, 2, 1, -5, 4]`\n\nOutput: `6`\n\nExplanation: The contiguous subarray... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8747,
"level": 1,
"question": "This is a coding challenge for Python:\n\n**Challenge:**\n\nYou are given a list of integers. Your task is to find the maximum sum of a contiguous subarray within the list.\n\n**Example:**\n\nInput: `[-2, 1, -3, 4, -1, 2, 1, -5, 4]`\n\nOutput: `6`\n\nE... |
def rotate_matrix(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse() | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function `rotate_matrix(matrix)` that takes a 2D square matrix (list of lists) and rotates it by 90 degrees clockwise. The function should modify the matrix in-place and not return anything. Note: The input matrix is guaranteed to be square (NxN).\n\nExample:\n```\nInput:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8748,
"level": 1,
"question": "Write a Python function `rotate_matrix(matrix)` that takes a 2D square matrix (list of lists) and rotates it by 90 degrees clockwise. The function should modify the matrix in-place and not return anything. Note: The input matrix is guaranteed to be squ... |
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return [] | simplelr_Filter | [
{
"content": "Question:\ndef two_sum(nums, target):\n seen = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in seen:\n return [seen[complement], i]\n seen[num] = i\n return []\nAnswer:\nLet's think step by step.\n",
"role": "user"
}... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8749,
"level": 1,
"question": "def two_sum(nums, target):\n seen = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in seen:\n return [seen[complement], i]\n seen[num] = i\n return []",
"split": "train"
} |
def find_smallest_missing_positive(lst):
positives = {x for x in lst if x > 0}
if not positives:
return 1
max_p = max(positives)
for i in range(1, max_p + 1):
if i not in positives:
return i
return max_p + 1 | simplelr_Apps | [
{
"content": "Question:\nWrite a function called `find_smallest_missing_positive` that takes a list of integers and returns the smallest positive integer that is not present in the list. The list may contain duplicates and negative numbers, and the integers are not necessarily sorted.\nAnswer:\nLet's think step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8750,
"level": 1,
"question": "Write a function called `find_smallest_missing_positive` that takes a list of integers and returns the smallest positive integer that is not present in the list. The list may contain duplicates and negative numbers, and the integers are not necessarily... |
def rearrange_numbers(nums):
negatives = []
non_negatives = []
for num in nums:
if num < 0:
negatives.append(num)
else:
non_negatives.append(num)
return negatives + non_negatives | simplelr_Package | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns a new list with the elements rearranged such that all negative numbers appear before all positive numbers, while maintaining the relative order of the negative numbers and positive numbers within their respective groups.\n\n### ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8751,
"level": 1,
"question": "Write a function that takes a list of integers and returns a new list with the elements rearranged such that all negative numbers appear before all positive numbers, while maintaining the relative order of the negative numbers and positive numbers with... |
def add_numbers(a, b):
return a + b | simplelr_Filter | [
{
"content": "Question:\n### Create a Python function `add_numbers` that takes two arguments and returns their sum.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8752,
"level": 1,
"question": "### Create a Python function `add_numbers` that takes two arguments and returns their sum.",
"split": "train"
} |
def find_first_index(s, chars):
for index, char in enumerate(s):
if char in chars:
return index
return -1 | simplelr_Filter | [
{
"content": "Question:\nHow can I find the first index of any of the characters in a string using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8753,
"level": 1,
"question": "How can I find the first index of any of the characters in a string using Python?",
"split": "train"
} |
def are_lists_equal(a, b):
if len(a) != len(b):
return False
for i in range(len(a)):
if a[i] != b[i]:
return False
return True | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two lists and returns True if they have the same elements in the same order, otherwise False.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8754,
"level": 1,
"question": "Create a function that takes two lists and returns True if they have the same elements in the same order, otherwise False.",
"split": "train"
} |
def find_pair_with_sum(numbers, target):
"""Find two distinct numbers in a list that add up to a target sum.
Args:
numbers (list): A list of numbers.
target (int): The target sum.
Returns:
tuple: A tuple of two distinct numbers from the list that add up to the target sum,
... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a list of numbers and a target sum, and returns a tuple of two distinct numbers from the list that add up to the target sum. The function should return `None` if no such pair exists. The function should be efficient and concise. Consider using a set f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8755,
"level": 1,
"question": "Create a Python function that takes a list of numbers and a target sum, and returns a tuple of two distinct numbers from the list that add up to the target sum. The function should return `None` if no such pair exists. The function should be efficient ... |
def sum_even_numbers(data):
"""
This function takes a list of integers as input and returns the sum of all
the even numbers in the list.
"""
if not data:
return 0
else:
first = data[0]
if first % 2 == 0:
return first + sum_even_numbers(data[1:])
else:
... | simplelr_Filter | [
{
"content": "Question:\nThe purpose of this assignment is to demonstrate your ability to:\n* Understand and apply the concept of recursion.\n* Implement a recursive algorithm to solve a problem.\n\nProblem:\n\nWrite a recursive function in Python that takes a list of integers as input and returns the sum of al... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8756,
"level": 1,
"question": "The purpose of this assignment is to demonstrate your ability to:\n* Understand and apply the concept of recursion.\n* Implement a recursive algorithm to solve a problem.\n\nProblem:\n\nWrite a recursive function in Python that takes a list of integers... |
def length_of_longest_good_substring(s, k):
if k == 0:
return -1 # Assuming k is at least 1 as per problem constraints
char_count = {}
left = 0
max_length = 0
distinct_count = 0
for right in range(len(s)):
char = s[right]
if char in char_count:
if c... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of only lowercase English letters. A **substring** is any contiguous sequence of characters within the string. A **good substring** is defined as a substring which contains exactly `k` distinct characters. Return _the **length** of the longest good ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8757,
"level": 1,
"question": "You are given a string `s` consisting of only lowercase English letters. A **substring** is any contiguous sequence of characters within the string. A **good substring** is defined as a substring which contains exactly `k` distinct characters. Return _... |
def repeat_string(A: str, B: str) -> int:
# Check if all characters in B are present in A
if not set(B).issubset(set(A)):
return -1
len_A = len(A)
len_B = len(B)
# Case 1: Length of B is less than or equal to A
if len_B <= len_A:
if B in A:
return 1
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Repeated String Match\n\n#### Problem Context\nGiven two strings `A` and `B`, you need to determine the minimum number of times you must repeat string `A` such that string `B` becomes a substring of this repeated string. If it's not possible for `B` to be a substring of repeated `A`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8758,
"level": 1,
"question": "### Repeated String Match\n\n#### Problem Context\nGiven two strings `A` and `B`, you need to determine the minimum number of times you must repeat string `A` such that string `B` becomes a substring of this repeated string. If it's not possible for `B... |
def rearrange_line(nums):
n = len(nums)
result = [0] * n
for i in range(n):
result[nums[i]] = i
return result | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `n` distinct integers, `nums`, representing the positions of `n` people standing in a line. Each person in the line will be rearranged according to their position in the input list such that `nums[i]` denotes the new position of the person originally standing at ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8759,
"level": 1,
"question": "You are given a list of `n` distinct integers, `nums`, representing the positions of `n` people standing in a line. Each person in the line will be rearranged according to their position in the input list such that `nums[i]` denotes the new position of... |
def generate_fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
fib_sequence = [0, 1]
for i in range(2, n):
next_term = fib_sequence[i-1] + fib_sequence[i-2]
fib_sequence.append(next_term)
return fib_sequence | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to generate the first n terms of the Fibonacci sequence in Python. The Fibonacci sequence is defined by the recurrence relation F(n) = F(n-1) + F(n-2), with initial conditions F(0) = 0 and F(1) = 1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8760,
"level": 1,
"question": "Write a function to generate the first n terms of the Fibonacci sequence in Python. The Fibonacci sequence is defined by the recurrence relation F(n) = F(n-1) + F(n-2), with initial conditions F(0) = 0 and F(1) = 1.",
"split": "train"
} |
def min_button_presses(n, start, path, rooms):
return len(path) - 1 | simplelr_Filter | [
{
"content": "Question:\nHere's a coding challenge problem I'm trying to solve and I'm not sure where to start:\n\n\"There is a Haunted House with `n` rooms. Each room has 4 binary buttons labeled `North`, `South`, `East`, and `West`. The initial state of all buttons is `OFF`. You can navigate from one room to ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8761,
"level": 1,
"question": "Here's a coding challenge problem I'm trying to solve and I'm not sure where to start:\n\n\"There is a Haunted House with `n` rooms. Each room has 4 binary buttons labeled `North`, `South`, `East`, and `West`. The initial state of all buttons is `OFF`.... |
def word_pattern(pattern: str, input_string: str) -> bool:
words = input_string.split()
if len(pattern) != len(words):
return False
p_to_word = {}
word_to_p = {}
for p_char, word in zip(pattern, words):
if p_char in p_to_word:
if p_to_word[p_char] != word:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\n\nYou are tasked with implementing a function that determines whether a given string follows a specific pattern. This scenario is common when ensuring that strings conform to template constraints, like validating formatted data input.\n\nWrite a function `word_pattern(patt... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8762,
"level": 1,
"question": "### Question\n\nYou are tasked with implementing a function that determines whether a given string follows a specific pattern. This scenario is common when ensuring that strings conform to template constraints, like validating formatted data input.\n\n... |
from typing import Tuple
def longest_common_substring(str1: str, str2: str) -> Tuple[int, str]:
m = len(str1)
n = len(str2)
max_len = 0
end_i = 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 str1[i-1] == str2[j-1]:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge\n\n### Problem Statement\n\nGiven two strings `str1` and `str2`, write a Python function called `longest_common_substring` that finds the longest common substring. A substring is a contiguous sequence of characters within a string. \n\nYou have to ensure that the fu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8763,
"level": 1,
"question": "### Coding Challenge\n\n### Problem Statement\n\nGiven two strings `str1` and `str2`, write a Python function called `longest_common_substring` that finds the longest common substring. A substring is a contiguous sequence of characters within a string.... |
def factorial(n):
"""
Calculate the factorial of a non-negative integer n.
Args:
n (int): A non-negative integer.
Returns:
int: The factorial of n.
Raises:
ValueError: If n is a negative integer or not an integer.
"""
if not isinstance(n, int) or n < 0:... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code snippet that calculates the factorial of a given number `n` using a custom function.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8764,
"level": 1,
"question": "Write a Python code snippet that calculates the factorial of a given number `n` using a custom function.",
"split": "train"
} |
def count_characters(s):
counts = {}
for char in s:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
return counts | simplelr_Filter | [
{
"content": "Question:\nWrite a python function that takes in a string and returns a dictionary where the keys are the unique characters in the string and the values are the counts of those characters in the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8765,
"level": 1,
"question": "Write a python function that takes in a string and returns a dictionary where the keys are the unique characters in the string and the values are the counts of those characters in the string.",
"split": "train"
} |
def calculate_expression(expression: str) -> int:
for i in range(1, len(expression)):
if expression[i] in '+-*/':
op = expression[i]
a = int(expression[:i])
b = int(expression[i+1:])
break
if op == '+':
return a + b
elif op == '-':
retu... | simplelr_Codeforces | [
{
"content": "Question:\nAn aspiring software developer is tasked to create a simple online calculator. This calculator can perform the following operations: addition (+), subtraction (-), multiplication (*), and division (/), between two given numbers A and B. The input is a string consisting of two integers s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8766,
"level": 1,
"question": "An aspiring software developer is tasked to create a simple online calculator. This calculator can perform the following operations: addition (+), subtraction (-), multiplication (*), and division (/), between two given numbers A and B. The input is a ... |
def caesar_cipher_encrypt(s, shift):
"""
Encrypts a given string using a Caesar cipher with the specified shift.
Args:
s (str): The string to be encrypted.
shift (int): The number of positions to shift each letter.
Returns:
str: The encrypted string.
"""
res... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to perform string encryption.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8767,
"level": 1,
"question": "Write a python function to perform string encryption.",
"split": "train"
} |
def length_of_longest_substring(s: str) -> int:
if not s:
return 0
max_len = 0
left = 0
last_occurrence = {}
for right in range(len(s)):
char = s[right]
if char in last_occurrence and last_occurrence[char] >= left:
left = last_occurrence[char] + 1
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters. You need to find the longest substring containing only unique characters and return its length. If the string is empty, return 0. Your task is to implement a function that executes this requirement efficiently.\nAnswer:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8768,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters. You need to find the longest substring containing only unique characters and return its length. If the string is empty, return 0. Your task is to implement a function that executes thi... |
def is_armstrong_number(n):
if n < 0:
return False
str_n = str(n)
number_of_digits = len(str_n)
sum_of_power = 0
for digit in str_n:
digit_int = int(digit)
sum_of_power += digit_int ** number_of_digits
return sum_of_power == n | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code snippet to check if a number is an Armstrong number? An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8769,
"level": 1,
"question": "Can you provide a Python code snippet to check if a number is an Armstrong number? An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits.",
"s... |
import json
def task_func(json_file, list_key):
with open(json_file, 'r') as f:
data = json.load(f)
list_data = data.get(list_key, [])
frequency_dict = {}
for item in list_data:
frequency_dict[item] = frequency_dict.get(item, 0) + 1
return frequency_dict | simplelr_Package | [
{
"content": "Question:\nLoad a JSON file using the `json` module, create a dictionary to map each unique element to the frequency of its occurrence in a specified list from the JSON data. The function should return this dictionary.\nYou should write self-contained code starting with:\n```\nimport json\ndef tas... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8770,
"level": 1,
"question": "Load a JSON file using the `json` module, create a dictionary to map each unique element to the frequency of its occurrence in a specified list from the JSON data. The function should return this dictionary.\nYou should write self-contained code starti... |
def fibonacci_cumulative_sum(n: int) -> int:
if n < 0:
return 0
m = n + 2
a, b = 0, 1
if m == 0:
fib_num = a
elif m == 1:
fib_num = b
else:
for i in range(2, m + 1):
a, b = b, a + b
fib_num = b
return fib_num - 1 | simplelr_Algorithm | [
{
"content": "Question:\n### Fibonacci Sequence Cumulative Sum\n\n#### Scenario:\nYou are given a problem related to the Fibonacci sequence, which is a series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. The cumulative sum of the Fibonacci series up to a gi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8771,
"level": 1,
"question": "### Fibonacci Sequence Cumulative Sum\n\n#### Scenario:\nYou are given a problem related to the Fibonacci sequence, which is a series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. The cumulative sum... |
def merge_sorted_lists(list1, list2):
# Handle edge cases where one or both lists are empty
if not list1:
return list2.copy()
if not list2:
return list1.copy()
# Initialize the result list and pointers for both input lists
result = []
i = j = 0
# Merge smaller eleme... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a Python function named `merge_sorted_lists` that merges two sorted lists into one sorted list. The function should:\n\n1. Accept two arguments which are the lists to be merged.\n2. Merge the lists while maintaining the sorted order without using built-in sorti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8772,
"level": 1,
"question": "You are required to write a Python function named `merge_sorted_lists` that merges two sorted lists into one sorted list. The function should:\n\n1. Accept two arguments which are the lists to be merged.\n2. Merge the lists while maintaining the sorted... |
def find_longest_substring(s: str) -> str:
char_map = {}
start = 0
max_len = 0
max_start = 0
for i, char in enumerate(s):
if char in char_map and char_map[char] >= start:
start = char_map[char] + 1
char_map[char] = i
current_len = i - start + 1
if current... | simplelr_Package | [
{
"content": "Question:\nImplement a function `find_longest_substring` that takes a string `s` as input and returns the longest substring without repeating characters. If there are multiple substrings of the same maximum length, return the one that appears first.\n\nThe goal of this function is to identify the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8773,
"level": 1,
"question": "Implement a function `find_longest_substring` that takes a string `s` as input and returns the longest substring without repeating characters. If there are multiple substrings of the same maximum length, return the one that appears first.\n\nThe goal o... |
def average_temperature(temperatures, ranges):
n = len(temperatures)
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + temperatures[i]
results = []
for left, right in ranges:
total = prefix[right + 1] - prefix[left]
count = right - left + 1
av... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `temperatures` of length `n`, where `temperatures[i]` represents the temperature on the `i-th` day. You are also given a **0-indexed** integer array `ranges` of length `m`, where `ranges[j] = [leftj, rightj]`. Each `ranges[j]` represents a que... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8774,
"level": 1,
"question": "You are given a **0-indexed** integer array `temperatures` of length `n`, where `temperatures[i]` represents the temperature on the `i-th` day. You are also given a **0-indexed** integer array `ranges` of length `m`, where `ranges[j] = [leftj, rightj]`... |
def make_change(amount: int, denominations: list) -> int:
if amount == 0:
return 0
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for d in denominations:
if d <= i:
dp[i] = min(dp[i], dp[i - d] + 1)
return dp[amount] if dp[amou... | simplelr_Taco | [
{
"content": "Question:\nA popular company that sells electronic gadgets wants to design a new prototype for a vending machine. The machine will only accept coins of certain denominations and will provide change in a minimal number of coins. You are required to help design the part of the software that calculat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8775,
"level": 1,
"question": "A popular company that sells electronic gadgets wants to design a new prototype for a vending machine. The machine will only accept coins of certain denominations and will provide change in a minimal number of coins. You are required to help design the... |
def power(n, m):
if m == 0:
return 1
elif m < 0:
return 1 / power(n, -m)
else:
return n * power(n, m - 1) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to compute the value of n to the power m, using recursion, handling the base case of exponent zero and negative bases and exponents.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8776,
"level": 1,
"question": "Write a function to compute the value of n to the power m, using recursion, handling the base case of exponent zero and negative bases and exponents.",
"split": "train"
} |
def rotate_matrix(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse()
return matrix | simplelr_Leetcode | [
{
"content": "Question:\nGiven a square matrix `matrix`, rotate the matrix 90 degrees clockwise in place. Return the rotated matrix. The rotation should be performed with a constant amount of extra space. \nFor example, given the matrix:\n```\n[\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\n```\nThe rotated matrix ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8777,
"level": 1,
"question": "Given a square matrix `matrix`, rotate the matrix 90 degrees clockwise in place. Return the rotated matrix. The rotation should be performed with a constant amount of extra space. \nFor example, given the matrix:\n```\n[\n [1, 2, 3],\n [4, 5, 6],\n [7,... |
def find_unique_elements(lst):
seen = set()
unique_list = []
for item in lst:
if item not in seen:
unique_list.append(item)
seen.add(item)
return unique_list | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the unique elements in a given list and return them in the order they first appear. If there are multiple occurrences of an element, it should only appear once in the output list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8778,
"level": 1,
"question": "Write a python function to find the unique elements in a given list and return them in the order they first appear. If there are multiple occurrences of an element, it should only appear once in the output list.",
"split": "train"
} |
import heapq
def lastStoneWeight(stones):
if not stones:
return 0
heap = []
for stone in stones:
heapq.heappush(heap, -stone)
while len(heap) > 1:
a = -heapq.heappop(heap)
b = -heapq.heappop(heap)
if a == b:
continue
else:
hea... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `stones` of length `n` where `stones[i]` represents the weight of the `i`-th stone. The **heaviest** two stones are taken and their weights compared. If their weights are equal, both stones are destroyed. Otherwise, the stone weighing less is destroyed, an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8779,
"level": 1,
"question": "You are given an integer array `stones` of length `n` where `stones[i]` represents the weight of the `i`-th stone. The **heaviest** two stones are taken and their weights compared. If their weights are equal, both stones are destroyed. Otherwise, the s... |
def is_well_formed(parentheses: str) -> bool:
stack = []
n = len(parentheses)
# If the length is odd, it's impossible to be well-formed
if n % 2 != 0:
return False
for char in parentheses:
if char == '(':
stack.append(char)
else:
# Check if t... | simplelr_Apps | [
{
"content": "Question:\n#### Summary\nYour challenge is to determine if the provided string (representing a sequence of parentheses) is well-formed, such that every opening parenthesis has a corresponding closing parenthesis.\n\n#### Details\nA well-formed sequence of parentheses follows these rules:\n1. An em... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8780,
"level": 1,
"question": "#### Summary\nYour challenge is to determine if the provided string (representing a sequence of parentheses) is well-formed, such that every opening parenthesis has a corresponding closing parenthesis.\n\n#### Details\nA well-formed sequence of parenth... |
def smallestWindow(s):
sum_indices = {0: -1}
current_sum = 0
min_length = float('inf')
for j in range(len(s)):
if s[j] == 'X':
current_sum += 1
else:
current_sum -= 1
if current_sum in sum_indices:
window_length = j - sum_indices[current_sum]
... | simplelr_Taco | [
{
"content": "Question:\nGiven a string containing only the characters 'X' and 'Y', you need to determine the smallest window that contains an equal number of 'X' and 'Y'. A window is defined as any contiguous subarray of the string. If no such window exists, return -1.\n\nExample 1:\nInput: s = \"XXXYXYX\"\nOu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8781,
"level": 1,
"question": "Given a string containing only the characters 'X' and 'Y', you need to determine the smallest window that contains an equal number of 'X' and 'Y'. A window is defined as any contiguous subarray of the string. If no such window exists, return -1.\n\nExa... |
def sort_products(products: list[tuple[str, float]]) -> list[tuple[str, float]]:
return sorted(products, key=lambda x: x[1], reverse=True) | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Optimize Product Listings\n\n### Context:\nE-commerce platforms often need to showcase products in a way that maximizes user engagement and sales. One such strategy is to sort products based on a specific criterion, such as price, customer rating, or relevance. Given a lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8782,
"level": 1,
"question": "### Question: Optimize Product Listings\n\n### Context:\nE-commerce platforms often need to showcase products in a way that maximizes user engagement and sales. One such strategy is to sort products based on a specific criterion, such as price, custome... |
def encode_string(s: str) -> str:
if not s:
return s
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
if count > 1:
result.append(current_char + str(count))
else:
... | simplelr_Taco | [
{
"content": "Question:\nString manipulation plays an essential role in various programming tasks. One common use case is formatting and transforming strings based on specific requirements. In this challenge, you'll write a function to encode a given string using a simple variant of the run-length encoding (RLE... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8783,
"level": 1,
"question": "String manipulation plays an essential role in various programming tasks. One common use case is formatting and transforming strings based on specific requirements. In this challenge, you'll write a function to encode a given string using a simple vari... |
def matrixBlockSum(mat, k):
if not mat or not mat[0]:
return []
m = len(mat)
n = len(mat[0])
# Compute the prefix sum matrix
pre = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
pre[i][j] = mat[i-1][j-1] + pre[i-1][... | simplelr_Leetcode | [
{
"content": "Question:\nImplement a function that takes a matrix `mat` of size `m x n` and an integer `k`, and returns a matrix of the same size where each element in the returning matrix is the sum of all elements within a `k`-radius square of that element in the original matrix. The `k`-radius square of an e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8784,
"level": 1,
"question": "Implement a function that takes a matrix `mat` of size `m x n` and an integer `k`, and returns a matrix of the same size where each element in the returning matrix is the sum of all elements within a `k`-radius square of that element in the original ma... |
from collections import deque
def min_steps_to_reach_end(grid):
m = len(grid)
if m == 0:
return -1
n = len(grid[0])
if grid[0][0] == -1 or grid[m-1][n-1] == -1:
return -1
if m == 1 and n == 1:
return 0
visited = [[False for _ in range(n)] for _ in range(m)]
queue = ... | simplelr_Leetcode | [
{
"content": "Question:\nYou need to traverse a 2D array of integers, `grid`, representing a field of land mines and empty spaces. Some cells contain land mines (indicated by a `-1`) and others are empty (indicated by a `0`). You are to move from the top-left corner of the grid to the bottom-right corner. You c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8785,
"level": 1,
"question": "You need to traverse a 2D array of integers, `grid`, representing a field of land mines and empty spaces. Some cells contain land mines (indicated by a `-1`) and others are empty (indicated by a `0`). You are to move from the top-left corner of the gri... |
def birdWatch(entries):
counts = {}
for entry in entries:
time_part, bird = entry.split(',')
counts[bird] = counts.get(bird, 0) + 1
max_count = max(counts.values())
max_birds = [bird for bird, count in counts.items() if count == max_count]
max_birds_sorted = sorted(max_birds)
... | simplelr_Taco | [
{
"content": "Question:\nDr. Bird is a keen ornithologist, and every weekend, he goes bird watching. He keeps meticulous records of the birds he spots each day, noting down the time and type of each bird he sees in a simple journal. Dr. Bird wants to find out which species he sees the most frequently to plan hi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8786,
"level": 1,
"question": "Dr. Bird is a keen ornithologist, and every weekend, he goes bird watching. He keeps meticulous records of the birds he spots each day, noting down the time and type of each bird he sees in a simple journal. Dr. Bird wants to find out which species he ... |
def maxProfit(prices):
if not prices:
return 0
min_price = prices[0]
max_profit = 0
for price in prices[1:]:
current_profit = price - min_price
if current_profit > max_profit:
max_profit = current_profit
if price < min_price:
min_price = price
... | simplelr_Apps | [
{
"content": "Question:\nYou are given a list of stock prices for a company in chronological order. You want to find out the maximum profit you could have made by buying a stock once and then selling that stock later.\n\nWrite a function that takes a list of integers representing the stock prices on different d... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8787,
"level": 1,
"question": "You are given a list of stock prices for a company in chronological order. You want to find out the maximum profit you could have made by buying a stock once and then selling that stock later.\n\nWrite a function that takes a list of integers represent... |
def minPathSum(grid):
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
# Initialize previous row with the first row's cumulative sums
prev_row = [0] * n
prev_row[0] = grid[0][0]
for j in range(1, n):
prev_row[j] = prev_row[j-1] + grid[0][j]
# ... | simplelr_Taco | [
{
"content": "Question:\nA warehouse has shelves arranged in rows and columns forming a grid. Each cell in the grid contains a certain number of boxes. You need to determine the minimum path sum from the top-left corner to the bottom-right corner of the grid. You can only move either right or down at any point ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8788,
"level": 1,
"question": "A warehouse has shelves arranged in rows and columns forming a grid. Each cell in the grid contains a certain number of boxes. You need to determine the minimum path sum from the top-left corner to the bottom-right corner of the grid. You can only move... |
def first_non_repeating_char(s):
char_counts = {}
for c in s:
if c in char_counts:
char_counts[c] += 1
else:
char_counts[c] = 1
for c in s:
if char_counts[c] == 1:
return c
return "_" | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the first character that appears only once in a given string. If there is no such character, return \"_\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8789,
"level": 1,
"question": "Write a python function to find the first character that appears only once in a given string. If there is no such character, return \"_\".",
"split": "train"
} |
def group_books_by_author(books):
grouped_books = {}
for book in books:
author = book['author']
if author not in grouped_books:
grouped_books[author] = []
grouped_books[author].append(book['title'])
return grouped_books | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of dictionaries, where each dictionary represents a book with keys 'title' and 'author'. The function should group these books by author and return a dictionary where the keys are authors and the values are lists of book titles. If the input lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8790,
"level": 1,
"question": "Write a Python function that takes a list of dictionaries, where each dictionary represents a book with keys 'title' and 'author'. The function should group these books by author and return a dictionary where the keys are authors and the values are lis... |
import seaborn as sns
import matplotlib.pyplot as plt
def analyze_residuals():
# Load the dataset
mpg = sns.load_dataset('mpg')
# Create and display the residual plot for weight vs displacement
plt.figure()
res = sns.residplot(x='displacement', y='weight', data=mpg)
plt.title('Residual Plo... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\n\nEvaluate the student's ability to use seaborn to create and customize residual plots, test for linearity, and apply advanced configurations.\n\n#### Question\n\nWrite a function `analyze_residuals` that:\n\n1. Loads the `mpg` dataset using seaborn.\n2. Generates a resi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8791,
"level": 1,
"question": "#### Objective\n\nEvaluate the student's ability to use seaborn to create and customize residual plots, test for linearity, and apply advanced configurations.\n\n#### Question\n\nWrite a function `analyze_residuals` that:\n\n1. Loads the `mpg` dataset ... |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def custom_heatmap(df: pd.DataFrame, annot: bool = True, fmt: str = ".2f", cmap: str = "viridis",
line_width: float = 0.5, color_min: float = None, color_max: float = None,
annot_df: pd.DataFrame = None) -... | simplelr_Docs | [
{
"content": "Question:\n### Objective\n\nWrite a function `custom_heatmap` that takes a DataFrame with numeric values and visualizes it as a heatmap with various customizations.\n\n### Function Signature\n\n```python\ndef custom_heatmap(df: pd.DataFrame, annot: bool = True, fmt: str = \".2f\", cmap: str = \"vi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8792,
"level": 1,
"question": "### Objective\n\nWrite a function `custom_heatmap` that takes a DataFrame with numeric values and visualizes it as a heatmap with various customizations.\n\n### Function Signature\n\n```python\ndef custom_heatmap(df: pd.DataFrame, annot: bool = True, f... |
def longest_common_subsequence(X, Y):
m = len(X)
n = len(Y)
# Create a table to store lengths of longest common subsequence of substrings.
# table[i][j] will store LCS length of X[0..i-1] and Y[0..j-1]
table = [[0] * (n+1) for _ in range(m+1)]
# Fill the table in bottom-up manner
f... | simplelr_Filter | [
{
"content": "Question:\nI am trying to solve the problem of finding the longest common subsequence (LCS) of two strings using dynamic programming. The strings are given as inputs, and I need to write a function that returns the length of the LCS. Can you guide me through the process and provide a code snippet ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8793,
"level": 1,
"question": "I am trying to solve the problem of finding the longest common subsequence (LCS) of two strings using dynamic programming. The strings are given as inputs, and I need to write a function that returns the length of the LCS. Can you guide me through the ... |
def find_first_duplicate(arr):
"""Returns the first duplicate in an array of integers, or -1 if none found."""
seen = set()
for num in arr:
if num in seen:
return num
seen.add(num)
return -1
print(find_first_duplicate([2, 1, 3, 5, 3, 2])) # Output: 3
print(find_first_duplic... | simplelr_Filter | [
{
"content": "Question:\nI am working on a project that requires me to find the first duplicate in an array of integers. \nThe function should return the first duplicate number it encounters in the array, and if it doesn't find any duplicates, it should return -1.\n\nFor example:\nInput: [2, 1, 3, 5, 3, 2]\nOut... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8794,
"level": 1,
"question": "I am working on a project that requires me to find the first duplicate in an array of integers. \nThe function should return the first duplicate number it encounters in the array, and if it doesn't find any duplicates, it should return -1.\n\nFor examp... |
def reversedMerge(a, b):
if not isinstance(a, list) or not isinstance(b, list):
raise TypeError("Both parameters must be lists.")
merged = a + b
merged.reverse()
return merged | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function called 'reversedMerge' that accepts two parameters, both are list objects, and merges these two lists into one. After merging, reverse the order of the list. If the parameters are not list objects, the function should raise a TypeError. Additionally, optimize yo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8795,
"level": 1,
"question": "Create a Python function called 'reversedMerge' that accepts two parameters, both are list objects, and merges these two lists into one. After merging, reverse the order of the list. If the parameters are not list objects, the function should raise a T... |
def is_valid_ipv4(ip: str) -> bool:
parts = ip.split('.')
if len(parts) != 4:
return False
for part in parts:
if not part.isdigit():
return False
num = int(part)
if num < 0 or num > 255:
return False
if len(part) > 1 and part[0] == '0':
... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with writing a function that determines if a given string is a valid IPv4 address. The function named `is_valid_ipv4` should take a string input `ip`, representing the potential IPv4 address.\n\nAn IPv4 address belongs to the format `x.x.x.x` where `x` is a number between... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8796,
"level": 1,
"question": "You are tasked with writing a function that determines if a given string is a valid IPv4 address. The function named `is_valid_ipv4` should take a string input `ip`, representing the potential IPv4 address.\n\nAn IPv4 address belongs to the format `x.x... |
def subarray_sum(nums, target):
prefix_counts = {0: 1}
current_sum = 0
count = 0
for num in nums:
current_sum += num
if (current_sum - target) in prefix_counts:
count += prefix_counts[current_sum - target]
if current_sum in prefix_counts:
prefix_counts[cur... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of integers `nums` and an integer `target`, return the number of subarrays that add up to the target. A subarray is a contiguous non-empty sequence of elements within the array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8797,
"level": 1,
"question": "Given a list of integers `nums` and an integer `target`, return the number of subarrays that add up to the target. A subarray is a contiguous non-empty sequence of elements within the array.",
"split": "train"
} |
import bisect
def find_nth_smallest(matrix, n):
m = len(matrix)
if m == 0:
return None # As per problem statement, m >= 1, so this is just a safeguard
low = matrix[0][0]
high = matrix[-1][-1]
while low < high:
mid = (low + high) // 2
count = 0
for row in m... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\nYou are tasked with finding the Nth smallest element in a sorted matrix.\n\n### Problem Statement\nWrite a function `find_nth_smallest(matrix: List[List[int]], n: int) -> int` that returns the Nth smallest element in a sorted matrix. The matrix is sorte... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8798,
"level": 1,
"question": "### Coding Assessment Question\n\nYou are tasked with finding the Nth smallest element in a sorted matrix.\n\n### Problem Statement\nWrite a function `find_nth_smallest(matrix: List[List[int]], n: int) -> int` that returns the Nth smallest element in a... |
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_Evol | [
{
"content": "Question:\nWrite a function that takes a string as input and returns a new string where all of the unique characters in the input string appear in the order they first appeared. Ignore duplicate characters beyond their first appearances.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8799,
"level": 1,
"question": "Write a function that takes a string as input and returns a new string where all of the unique characters in the input string appear in the order they first appeared. Ignore duplicate characters beyond their first appearances.",
"split": "train"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.