target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
def find_pattern(pattern: str, text: str) -> int:
m = len(pattern)
n = len(text)
if m == 0 or n < m:
return -1
base = 256
mod = 10**9 + 7
pow_base = pow(base, m - 1, mod)
# Compute pattern hash
p_hash = 0
for c in pattern:
p_hash = (p_hash * base + ord(c)) % mod
... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Context\nYou are given a task to search for the presence of a specific word within a large body of text using the Rabin-Karp algorithm. Implementing the algorithm efficiently will save time compared to direct string matching, especially when dealing with large texts and multiple pa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2400,
"level": 1,
"question": "#### Context\nYou are given a task to search for the presence of a specific word within a large body of text using the Rabin-Karp algorithm. Implementing the algorithm efficiently will save time compared to direct string matching, especially when deali... |
def reverse_words_order(s):
return ' '.join(reversed(s.split())) | simplelr_Filter | [
{
"content": "Question:\nI need to develop a Python function that reverses the order of words in a given string but keeps the order of the characters within each word the same. How can I write this function?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2401,
"level": 1,
"question": "I need to develop a Python function that reverses the order of words in a given string but keeps the order of the characters within each word the same. How can I write this function?",
"split": "train"
} |
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]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr
# Example usage... | simplelr_Filter | [
{
"content": "Question:\nCan you assist me in creating a basic algorithm to sort an array of numbers in ascending order? I'm a beginner in programming and would like to understand the core concepts.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2402,
"level": 1,
"question": "Can you assist me in creating a basic algorithm to sort an array of numbers in ascending order? I'm a beginner in programming and would like to understand the core concepts.",
"split": "train"
} |
def reverse_concatenate(lst):
result = 0
for digit in reversed(lst):
result = result * 10 + digit
return result | simplelr_Filter | [
{
"content": "Question:\nYou are tasked with writing a Python function that takes a list of single-digit integers (where each integer is between 0 to 9, inclusive) and combines them into one number. The integers in the list should be concatenated in reverse order to form the final number. For example, the list ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2403,
"level": 1,
"question": "You are tasked with writing a Python function that takes a list of single-digit integers (where each integer is between 0 to 9, inclusive) and combines them into one number. The integers in the list should be concatenated in reverse order to form the f... |
def two_sum(arr, target):
seen = set()
for num in arr:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` and an integer `target`. Determine if there exist two integers in the array whose sum is equal to `target`. Return `true` if such a pair exists, and `false` otherwise. The array may contain both positive and negative integers, and each integer in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2404,
"level": 1,
"question": "You are given an array of integers `arr` and an integer `target`. Determine if there exist two integers in the array whose sum is equal to `target`. Return `true` if such a pair exists, and `false` otherwise. The array may contain both positive and neg... |
def filter_log_data(log_data: list[str], keyword: str) -> tuple[list[str], int]:
"""
Filters log data to find lines containing the specified keyword and returns the filtered lines along with their count.
Args:
log_data (list[str]): A list of log lines.
keyword (str): The keyword to search f... | simplelr_Filter | [
{
"content": "Question:\nI'm trying to write some code to analyze and filter log data. The log data is stored in a list of strings, where each string represents a line of the log. \nI'd like to be able to iterate over the lines, count the number of lines that contain a certain keyword, and also keep track of th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2405,
"level": 1,
"question": "I'm trying to write some code to analyze and filter log data. The log data is stored in a list of strings, where each string represents a line of the log. \nI'd like to be able to iterate over the lines, count the number of lines that contain a certain... |
def calculate_total_price(cart):
total = 0
for item in cart:
total += item['price'] * item['quantity']
return total
# Example input: a list of dictionaries
cart = [
{'price': 15.99, 'quantity': 2}, # 2 books at $15.99 each
{'price': 5.00, 'quantity': 3}, # 3 notebooks at $5.00 each
... | simplelr_Filter | [
{
"content": "Question:\nHello, I am using the `calculate_total_price` function in a Python script to compute the total price of items in a shopping cart. The function takes a list of dictionaries, where each dictionary represents an item with its price and quantity. Can you show me how to use this function and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2406,
"level": 1,
"question": "Hello, I am using the `calculate_total_price` function in a Python script to compute the total price of items in a shopping cart. The function takes a list of dictionaries, where each dictionary represents an item with its price and quantity. Can you s... |
def sum_of_evens_and_product_of_odds(lst):
sum_even = 0
product_odd = 1
for num in lst:
if num % 2 == 0:
sum_even += num
else:
product_odd *= num
return (sum_even, product_odd) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a tuple containing the sum of all the even numbers and the product of all the odd numbers in the list. If there are no even numbers, the sum of even numbers should be 0. If there are no odd numbers, the product of odd numbers s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2407,
"level": 1,
"question": "Create a function that takes a list of integers and returns a tuple containing the sum of all the even numbers and the product of all the odd numbers in the list. If there are no even numbers, the sum of even numbers should be 0. If there are no odd nu... |
def is_sorted(lst):
if len(lst) <= 1:
return True # An empty list or single-element list is considered sorted
is_ascending = True
is_descending = True
for i in range(len(lst) - 1):
if lst[i] < lst[i + 1]:
is_descending = False
elif lst[i] > lst[i + 1]:
is... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers, and returns a boolean indicating whether the list is sorted in ascending order, descending order, or neither.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2408,
"level": 1,
"question": "Create a function that takes a list of integers, and returns a boolean indicating whether the list is sorted in ascending order, descending order, or neither.",
"split": "train"
} |
def remove_odd_numbers(numbers):
return [num for num in numbers if num % 2 == 0] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove all odd numbers from the list and return the modified list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2409,
"level": 1,
"question": "Write a python function to remove all odd numbers from the list and return the modified list.",
"split": "train"
} |
def solve(arr, target):
arr.sort()
n = len(arr)
for i in range(n - 2):
j = i + 1
k = n - 1
while j < k:
current = arr[i] + arr[j] + arr[k]
if current == target:
return (arr[i], arr[j], arr[k])
elif current < target:
... | simplelr_Apps | [
{
"content": "Question:\nYou are given an array of integers and a target integer. Your task is to determine if there are three distinct elements in the array that sum up to the target integer. If such a combination exists, return the combination as a tuple of three integers in non-decreasing order. If there are... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2410,
"level": 1,
"question": "You are given an array of integers and a target integer. Your task is to determine if there are three distinct elements in the array that sum up to the target integer. If such a combination exists, return the combination as a tuple of three integers in... |
import heapq
def efficient_dijkstra(graph, start_node):
"""
Implement Dijkstra's algorithm using a priority queue for performance optimization.
Args:
graph (dict): A dictionary of nodes and their neighbors with edge weights.
start_node (any): The starting node identifier.
Returns:
dict: A... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge: Implement Efficient Dijkstra Algorithm\n\n**Context**:\nYou have been provided with a basic graph structure and your task is to implement an efficient version of Dijkstra's shortest path algorithm. This algorithm should be optimized to efficiently handle larger dat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2411,
"level": 1,
"question": "### Coding Challenge: Implement Efficient Dijkstra Algorithm\n\n**Context**:\nYou have been provided with a basic graph structure and your task is to implement an efficient version of Dijkstra's shortest path algorithm. This algorithm should be optimiz... |
def gcd(a, b):
a = abs(a)
b = abs(b)
while b != 0:
a, b = b, a % b
return a | simplelr_Filter | [
{
"content": "Question:\nI was on a job interview and they asked me to solve this problem in an online coding environment. They presented me with a list of numbers and asked me to write a function to find the largest common divisor of two numbers. I have an idea of how to do this using the Euclidean algorithm ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2412,
"level": 1,
"question": "I was on a job interview and they asked me to solve this problem in an online coding environment. They presented me with a list of numbers and asked me to write a function to find the largest common divisor of two numbers. I have an idea of how to do ... |
def reverse_alphabetical_order(input_dict):
return {key: input_dict[key] for key in sorted(input_dict.keys(), reverse=True)} | simplelr_Filter | [
{
"content": "Question:\nGive me a Python function that takes a dictionary as input and returns a new dictionary with keys in reverse alphabetical order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2413,
"level": 1,
"question": "Give me a Python function that takes a dictionary as input and returns a new dictionary with keys in reverse alphabetical order.",
"split": "train"
} |
def rotate(arr, k):
n = len(arr)
if n == 0 or k == 0:
return arr
effective_k = k % n
return arr[-effective_k:] + arr[:-effective_k] | simplelr_Code_Contests | [
{
"content": "Question:\nTime Limit: 5 sec / Memory Limit: 128 MB\n\nWrite a function that takes an integer array and an integer k, and rotates the array to the right by k steps, where k is non-negative.\n\nExample:\n\nInput\n\n[1, 2, 3, 4, 5, 6, 7]\n3\n\nOutput\n\n[5, 6, 7, 1, 2, 3, 4]\n\nInput\n\n[-1, -100, 3... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2414,
"level": 1,
"question": "Time Limit: 5 sec / Memory Limit: 128 MB\n\nWrite a function that takes an integer array and an integer k, and rotates the array to the right by k steps, where k is non-negative.\n\nExample:\n\nInput\n\n[1, 2, 3, 4, 5, 6, 7]\n3\n\nOutput\n\n[5, 6, 7, 1... |
import re
def most_repeated_word(s):
s_lower = s.lower()
words = re.findall(r"[a-z']+", s_lower)
words = [word.strip("'") for word in words]
words = [word for word in words if word]
word_info = {}
for index, word in enumerate(words):
if word not in word_info:
word_... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the most repeated word in a given string `s` and return it. If there are multiple words with the same highest frequency, return the one that appears first in the string. The function should also handle punctuation and consider words in a case-insensitive ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2415,
"level": 1,
"question": "Write a python function to find the most repeated word in a given string `s` and return it. If there are multiple words with the same highest frequency, return the one that appears first in the string. The function should also handle punctuation and co... |
def rotate_matrix(mat):
n = len(mat)
for i in range(n):
for j in range(i, n):
mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
for row in mat:
row.reverse()
return mat | simplelr_Leetcode | [
{
"content": "Question:\nGiven an `n x n` matrix `mat`, rotate the matrix 90 degrees clockwise in-place and return the resulting matrix. The rotation should be performed by first transposing the matrix and then reversing each row. \n\n* For example, given the matrix:\n\n ```\n [\n [1, 2, 3],\n [4, 5, 6]... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2416,
"level": 1,
"question": "Given an `n x n` matrix `mat`, rotate the matrix 90 degrees clockwise in-place and return the resulting matrix. The rotation should be performed by first transposing the matrix and then reversing each row. \n\n* For example, given the matrix:\n\n ```\... |
import email
from email.encoders import encode_quopri, encode_base64, encode_7or8bit, encode_noop
from email.message import Message
def encode_email_message(msg: Message, encoding_scheme: str) -> Message:
"""
Encodes the payload of an email Message object using the specified encoding scheme.
Parameters:
... | simplelr_Docs | [
{
"content": "Question:\n### Email Encoding Utility\n\nAs an email security application developer, you are tasked with creating a utility that processes email messages by encoding their payloads using different encoding schemes and then verifying the encoded content. While the `email.encoders` module is depreca... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2417,
"level": 1,
"question": "### Email Encoding Utility\n\nAs an email security application developer, you are tasked with creating a utility that processes email messages by encoding their payloads using different encoding schemes and then verifying the encoded content. While the... |
from collections import Counter
def are_anagrams(str1, str2):
return Counter(str1) == Counter(str2)
# Example usage:
print(are_anagrams("listen", "silent")) # Returns: True
print(are_anagrams("hello", "world")) # Returns: False | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to Check if Two Strings are Anagrams using Python (using collections.Counter)\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2418,
"level": 1,
"question": "Write a python function to Check if Two Strings are Anagrams using Python (using collections.Counter)",
"split": "train"
} |
def swap_first_last(s):
if len(s) <= 1:
return s
return s[-1] + s[1:-1] + s[0] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a string and returns a new string where the first letter and the last letter of the original string are swapped.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2419,
"level": 1,
"question": "Create a function that takes in a string and returns a new string where the first letter and the last letter of the original string are swapped.",
"split": "train"
} |
import csv
def parse_csv_to_list_of_dicts(filename):
with open(filename, 'r') as csvfile:
reader = csv.DictReader(csvfile)
rows = [row for row in reader]
return rows
# Example usage:
# data = csv_to_list_of_dicts('data.csv')
# print(data) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code snippet to parse a CSV file and convert it into a list of dictionaries, where each dictionary represents a row in the CSV file with column headers as keys.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2420,
"level": 1,
"question": "Write a Python code snippet to parse a CSV file and convert it into a list of dictionaries, where each dictionary represents a row in the CSV file with column headers as keys.",
"split": "train"
} |
def min_cards_to_exchange(alice_cards: str, bob_cards: str) -> int:
alice_sets = set(alice_cards)
bob_sets = set(bob_cards)
x = len(alice_sets - bob_sets)
y = len(bob_sets - alice_sets)
return x + y
| simplelr_Taco | [
{
"content": "Question:\nTwo famous collectors, Alice and Bob, are planning to exchange their collectible cards. Each card has a value and belongs to different sets denoted by a unique lowercase letter. Alice and Bob want to know the minimum number of cards each has to give away in order to collect one card eac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2421,
"level": 1,
"question": "Two famous collectors, Alice and Bob, are planning to exchange their collectible cards. Each card has a value and belongs to different sets denoted by a unique lowercase letter. Alice and Bob want to know the minimum number of cards each has to give aw... |
def longest_subarray_with_sum(nums, target):
sum_map = {0: -1} # Initialize with a sum of 0 at index -1
current_sum = 0
max_length = 0
start = 0
end = 0
for i, num in enumerate(nums):
current_sum += num
# Check if (current_sum - target) is present in sum_map
if (current... | simplelr_Evol | [
{
"content": "Question:\nDevelop a function that accepts an array of integers and returns the longest contiguous subarray whose sum is equal to a given target. The function should explore all possible subarrays in search of the one with the maximum length, which meets the criterion. If there is no such subarray... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2422,
"level": 1,
"question": "Develop a function that accepts an array of integers and returns the longest contiguous subarray whose sum is equal to a given target. The function should explore all possible subarrays in search of the one with the maximum length, which meets the crit... |
def f2(x: int) -> bool:
"""
Determines if a given positive integer is even.
Args:
x (int): A positive integer to check for evenness.
Returns:
bool: True if the number is even, False otherwise.
"""
return x % 2 == 0 | simplelr_Filter | [
{
"content": "Question:\nI have been studying the performance of two functions. The ideal code that I am working on has two functions. Function `f1(x)` returns true if a given input `x` is prime and false otherwise. Function `f2(x)` returns true if `x` is an even number and false otherwise. Both functions take ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2423,
"level": 1,
"question": "I have been studying the performance of two functions. The ideal code that I am working on has two functions. Function `f1(x)` returns true if a given input `x` is prime and false otherwise. Function `f2(x)` returns true if `x` is an even number and fa... |
def max_non_adjacent_sum(nums):
n = len(nums)
if n == 0:
return 0
if n == 1:
return nums[0]
prev_prev = nums[0]
prev = max(nums[0], nums[1])
for i in range(2, n):
current = max(prev, nums[i] + prev_prev)
prev_prev, prev = prev, current
return prev | simplelr_Algorithm | [
{
"content": "Question:\n### Maximum Sum Subsequence with Non-Adjacent Elements\n\nGiven an array of positive integers, you need to find the maximum sum of a subsequence such that no two elements in the subsequence are adjacent in the original array.\n\n#### Function Specification:\n\n**Function Name**: `max_no... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2424,
"level": 1,
"question": "### Maximum Sum Subsequence with Non-Adjacent Elements\n\nGiven an array of positive integers, you need to find the maximum sum of a subsequence such that no two elements in the subsequence are adjacent in the original array.\n\n#### Function Specifica... |
def sum_and_product(lst):
if not lst:
return (0, 1)
total = sum(lst)
product = 1
for num in lst:
product *= num
return (total, product) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum and product of all integers in a given list. The function should return the sum and product as a tuple. If the list is empty, the function should return 0 for the sum and 1 for the product.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2425,
"level": 1,
"question": "Write a function to calculate the sum and product of all integers in a given list. The function should return the sum and product as a tuple. If the list is empty, the function should return 0 for the sum and 1 for the product.",
"split": "train"
} |
from typing import Sequence
def binary_search(data: Sequence[int], target: int) -> int:
low = 0
high = len(data)
while low < high:
mid = (low + high) // 2
if data[mid] == target:
return mid
elif data[mid] > target:
high = mid
else:
low = m... | simplelr_Algorithm | [
{
"content": "Question:\n### Binary Search Algorithm\n\n**Context:**\n\nYou are tasked with building a feature for an online bookstore that helps users quickly find books by their unique ID numbers. The server stores a sorted list of book IDs, and you need to implement an efficient search algorithm to find the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2426,
"level": 1,
"question": "### Binary Search Algorithm\n\n**Context:**\n\nYou are tasked with building a feature for an online bookstore that helps users quickly find books by their unique ID numbers. The server stores a sorted list of book IDs, and you need to implement an effi... |
def count_less_than_ten(lst):
count = 0
for num in lst:
if num < 10:
count += 1
return count | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts a list and returns the number of elements in the list that are less than 10.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2427,
"level": 1,
"question": "Create a function that accepts a list and returns the number of elements in the list that are less than 10.",
"split": "train"
} |
def swap_elements(arr, pos1, pos2):
# Check if the positions are valid
if pos1 < 0 or pos1 >= len(arr) or pos2 < 0 or pos2 >= len(arr):
return arr.copy() # Return a copy if positions are invalid
# Swap the elements at the given positions
arr[pos1], arr[pos2] = arr[pos2], arr[pos1]
return ar... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to exchange the positions of a given pair of elements in an array. For example, if we have an array of integers like [5, 3, 8, 2] and we are asked to swap the elements at positions 1 and 3, the resulting array should be [5, 2, 8, 3].\nAnswer:\nLet's think step by step.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2428,
"level": 1,
"question": "Write a function to exchange the positions of a given pair of elements in an array. For example, if we have an array of integers like [5, 3, 8, 2] and we are asked to swap the elements at positions 1 and 3, the resulting array should be [5, 2, 8, 3].",... |
def can_reach_target(distances, d):
return sum(distances) >= d | simplelr_Codeforces | [
{
"content": "Question:\nA spaceship is traveling between planets in the galaxy using a warp drive. The warp drive allows the spaceship to instantaneously jump a certain number of light years each day, but it can only make one jump per day. The spaceship's fuel cells get exhausted depending on the total number ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2429,
"level": 1,
"question": "A spaceship is traveling between planets in the galaxy using a warp drive. The warp drive allows the spaceship to instantaneously jump a certain number of light years each day, but it can only make one jump per day. The spaceship's fuel cells get exhau... |
def longest_unique_substring(s):
char_index = {}
left = 0
max_length = 0
for right in range(len(s)):
char = s[right]
if char in char_index and char_index[char] >= left:
left = char_index[char] + 1
char_index[char] = right
current_length = right - left + 1
... | simplelr_Taco | [
{
"content": "Question:\n## Task\nWrite a function that takes a string `s` and returns the longest substring containing only unique characters.\n\n# Example\n\nFor `s = \"abcabcbb\"`, the output should be `3`. (The substring is: \"abc\")\n\nFor `s = \"bbbbb\"`, the output should be `1`. (The substring is: \"b\"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2430,
"level": 1,
"question": "## Task\nWrite a function that takes a string `s` and returns the longest substring containing only unique characters.\n\n# Example\n\nFor `s = \"abcabcbb\"`, the output should be `3`. (The substring is: \"abc\")\n\nFor `s = \"bbbbb\"`, the output shou... |
def contains_keyword(text, keyword):
if not keyword:
return True
key_len = len(keyword)
text_len = len(text)
if key_len > text_len:
return False
for i in range(text_len - key_len + 1):
match = True
for j in range(key_len):
if text[i + j] != keyword[j]:
... | simplelr_Filter | [
{
"content": "Question:\nThis question comes from a real-world problem I'm working on.\n\nI need to create a method that determines if a\n\ngiven text string contains a specific keyword.\n\nThe method should return \"True\" if the keyword\n\nis present in the text, and \"False\" otherwise.\n\nFor example:\n\n``... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2431,
"level": 1,
"question": "This question comes from a real-world problem I'm working on.\n\nI need to create a method that determines if a\n\ngiven text string contains a specific keyword.\n\nThe method should return \"True\" if the keyword\n\nis present in the text, and \"False... |
from collections import defaultdict
def count_substrings(patterns, text):
len_map = defaultdict(list)
for idx, p in enumerate(patterns):
len_map[len(p)].append((p, idx))
counts = [0] * len(patterns)
for l in range(1, 51):
if l not in len_map:
continue
if l ... | simplelr_Leetcode | [
{
"content": "Question:\nYou have been given a list of strings `patterns` and a string `text`. Each string in `patterns` contains only lowercase English letters and has a length between `1` and `50`. The `text` string contains only lowercase English letters and can have a length of up to `10^5`. Write a functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2432,
"level": 1,
"question": "You have been given a list of strings `patterns` and a string `text`. Each string in `patterns` contains only lowercase English letters and has a length between `1` and `50`. The `text` string contains only lowercase English letters and can have a leng... |
from typing import List
def selectionSortDescending(arr: List[int]) -> None:
n = len(arr)
for i in range(n):
max_index = i
for j in range(i + 1, n):
if arr[j] > arr[max_index]:
max_index = j
arr[i], arr[max_index] = arr[max_index], arr[i] | simplelr_Code_Contests | [
{
"content": "Question:\nIn a computer science class, students are learning about various sorting algorithms. One concept that intrigued them is the selection sort algorithm. Instead of sorting the array in ascending order, the students are asked to write a function that sorts the array in descending order usin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2433,
"level": 1,
"question": "In a computer science class, students are learning about various sorting algorithms. One concept that intrigued them is the selection sort algorithm. Instead of sorting the array in ascending order, the students are asked to write a function that sorts... |
def count_occurrences(nums):
counts = {}
for num in nums:
counts[num] = counts.get(num, 0) + 1
if not counts:
return {}, None
min_count = min(counts.values())
min_keys = [k for k, v in counts.items() if v == min_count]
least_occurrence = min(min_keys) # Ensure the smallest key i... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns a dictionary where the key is the integer and the value is the number of times it appears in the list. Additionally, the function should return the integer that appears the least number of times. If there is a tie, return any on... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2434,
"level": 1,
"question": "Write a function that takes a list of integers and returns a dictionary where the key is the integer and the value is the number of times it appears in the list. Additionally, the function should return the integer that appears the least number of time... |
def calculate_bills(purchases: [(str, str, float, int)]) -> dict:
totals = {}
for purchase in purchases:
customer = purchase[0]
price = purchase[2]
quantity = purchase[3]
cost = price * quantity
if customer in totals:
totals[customer] += cost
else:
... | simplelr_Apps | [
{
"content": "Question:\n# Task\n\nYour task is to write a function that calculates the total amount each customer will be billed based on their shopping cart. The input is a list of items purchased where each item is represented by a tuple containing the item name, price per unit, and quantity purchased. The o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2435,
"level": 1,
"question": "# Task\n\nYour task is to write a function that calculates the total amount each customer will be billed based on their shopping cart. The input is a list of items purchased where each item is represented by a tuple containing the item name, price per ... |
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_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum subarray sum. The maximum subarray sum is the sum of a contiguous subarray within a one-dimensional array of numbers that has the largest sum. To solve this, you can use Kadane's algorithm, which is efficient and has a linear time complexity.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2436,
"level": 1,
"question": "Write a python function to find the maximum subarray sum. The maximum subarray sum is the sum of a contiguous subarray within a one-dimensional array of numbers that has the largest sum. To solve this, you can use Kadane's algorithm, which is efficient... |
def max_profit(prices):
max_profit = 0
for i in range(len(prices) - 1):
if prices[i+1] > prices[i]:
max_profit += prices[i+1] - prices[i]
return max_profit | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to determine the maximum profit that can be made by buying and selling a stock on any number of days (buying at one price and selling at a higher price in the future). You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2437,
"level": 1,
"question": "Write a function to determine the maximum profit that can be made by buying and selling a stock on any number of days (buying at one price and selling at a higher price in the future). You may not engage in multiple transactions at the same time (i.e.,... |
def is_palindrome(s: str) -> bool:
"""
Checks if the given string is a palindrome considering only alphanumeric characters and ignoring cases.
Args:
s (str): The input string.
Returns:
bool: True if the string is a palindrome, False otherwise.
"""
# Remove non-alphanumeric characters a... | simplelr_Filter | [
{
"content": "Question:\nGiven a string, determine if it is a palindrome considering only alphanumeric characters and ignoring cases.\n\n### Example 1:\nInput: \"A man, a plan, a canal: Panama\"\nOutput: `true`\n\n### Example 2:\nInput: \"Not a palindrome\"\nOutput: `false`\n\n### Solution\n\nTo solve this, we ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2438,
"level": 1,
"question": "Given a string, determine if it is a palindrome considering only alphanumeric characters and ignoring cases.\n\n### Example 1:\nInput: \"A man, a plan, a canal: Panama\"\nOutput: `true`\n\n### Example 2:\nInput: \"Not a palindrome\"\nOutput: `false`\n\... |
from collections import deque
def bfs_shortest_path(graph: dict, start: int) -> dict:
# Create a set of all nodes including the start node
nodes = set(graph.keys())
nodes.add(start)
# Initialize distances to -1 for all nodes
distances = {node: -1 for node in nodes}
# If start is not in the... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question\n\n#### Context:\nIn graph theory, the shortest path between two nodes in an unweighted graph can be efficiently found using Breadth-First Search (BFS). Given an unweighted, undirected graph and a starting node, you are required to find the shortest distance from the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2439,
"level": 1,
"question": "### Coding Question\n\n#### Context:\nIn graph theory, the shortest path between two nodes in an unweighted graph can be efficiently found using Breadth-First Search (BFS). Given an unweighted, undirected graph and a starting node, you are required to ... |
def most_frequent_char(s: str) -> str:
# Create a frequency dictionary
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
# Find the maximum frequency
max_count = max(freq.values())
# Collect all characters with the ma... | simplelr_Evol | [
{
"content": "Question:\nGiven a string of lowercase letters, determine the most frequently occurring character. If there are multiple characters with the same highest frequency, return the one that appears earliest in the alphabet. For example, in the string \"examplestring\", the most frequent character is 'e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2440,
"level": 1,
"question": "Given a string of lowercase letters, determine the most frequently occurring character. If there are multiple characters with the same highest frequency, return the one that appears earliest in the alphabet. For example, in the string \"examplestring\"... |
def sort_strings_by_length(lst):
return sorted(lst, key=lambda x: (len(x), x)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to sort a list of strings based on their length. If two strings have the same length, sort those strings alphabetically in ascending order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2441,
"level": 1,
"question": "Write a python function to sort a list of strings based on their length. If two strings have the same length, sort those strings alphabetically in ascending order.",
"split": "train"
} |
def encode_message(message: str) -> str:
# Create a frequency dictionary for alphabetic characters
freq = {}
for char in message:
if not char.isalpha():
continue # Ignore non-alphabetic characters
lower_char = char.lower()
freq[lower_char] = freq.get(lower_char, 0) + 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem: Character Frequency Encoder\n\nYou are designing a character frequency encoder that transforms messages into a frequency-based code. Each character in the message is replaced by its frequency within the message, sorted alphabetically by the character. The encoding should be... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2442,
"level": 1,
"question": "### Problem: Character Frequency Encoder\n\nYou are designing a character frequency encoder that transforms messages into a frequency-based code. Each character in the message is replaced by its frequency within the message, sorted alphabetically by th... |
import random
def generate_random_number():
return random.randint(1, 10) | simplelr_Filter | [
{
"content": "Question:\nwrite a Python 3 function to generate random numbers between 1 and 10.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2443,
"level": 1,
"question": "write a Python 3 function to generate random numbers between 1 and 10.",
"split": "train"
} |
from collections import deque
def rolling_window_average(data, window_size):
q = deque()
current_sum = 0
for num in data:
q.append(num)
current_sum += num
if len(q) > window_size:
removed = q.popleft()
current_sum -= removed
count = len(q)
yie... | simplelr_Docs | [
{
"content": "Question:\n### Functional Programming in Python\n\n#### Problem Statement\n\nYou are tasked with implementing a Python function that processes a stream of data using various functional programming constructs including iterators, generators, and functionalities from the itertools module. \n\nThe fu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2444,
"level": 1,
"question": "### Functional Programming in Python\n\n#### Problem Statement\n\nYou are tasked with implementing a Python function that processes a stream of data using various functional programming constructs including iterators, generators, and functionalities fr... |
def validate_payload(payload):
required_keys = {'name', 'age', 'city', 'interests', 'isEmployed', 'workExperience'}
# Check if payload is a dictionary
if not isinstance(payload, dict):
return False
# Check all required keys are present
for key in required_keys:
if key not i... | simplelr_Filter | [
{
"content": "Question:\nI have been tasked with writing a JSON payload that must be sent to an API. The API expects the JSON payload to contain certain properties and values such that they fulfill certain conditions. \nHere are the conditions for the JSON payload:\n1. It must contain a \"name\" property with a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2445,
"level": 1,
"question": "I have been tasked with writing a JSON payload that must be sent to an API. The API expects the JSON payload to contain certain properties and values such that they fulfill certain conditions. \nHere are the conditions for the JSON payload:\n1. It must... |
def min_edit_distance(word1: str, word2: str) -> int:
m = len(word1)
n = len(word2)
# Create a DP table with (m+1) rows and (n+1) columns
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Initialize the base cases
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[... | simplelr_Data_Structure | [
{
"content": "Question:\n### Edit Distance Minimization\n\n**Context**: In many text processing applications, it’s useful to determine how similar two strings are. A robust measure of similarity is the minimum number of single-character edits (insertions, deletions, or substitutions) required to convert one str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2446,
"level": 1,
"question": "### Edit Distance Minimization\n\n**Context**: In many text processing applications, it’s useful to determine how similar two strings are. A robust measure of similarity is the minimum number of single-character edits (insertions, deletions, or substit... |
def longest_common_subsequence(s1, s2):
# Create a dictionary to map each character in s2 to its index
char_to_pos = {char: idx for idx, char in enumerate(s2)}
# Convert s1 into an array of indices based on s2's characters
a = []
for char in s1:
if char in char_to_pos:
a.app... | simplelr_Data_Structure | [
{
"content": "Question:\n### Longest Common Subsequence Finder\n\nYou are given two strings, `s1` and `s2`. The string `s2` consists of all distinct characters. Write a function `longest_common_subsequence(s1, s2)` that returns the length of the longest common subsequence (LCS) found in both strings.\n\n#### In... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2447,
"level": 1,
"question": "### Longest Common Subsequence Finder\n\nYou are given two strings, `s1` and `s2`. The string `s2` consists of all distinct characters. Write a function `longest_common_subsequence(s1, s2)` that returns the length of the longest common subsequence (LCS... |
def exists_pair_with_sum(arr, target):
seen = set()
for num in arr:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` and an integer `target`. Determine if there exist **two distinct elements** in the array such that their sum is equal to `target`. If such a pair exists, return `true`; otherwise, return `false`. You can assume that each input would have exactly ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2448,
"level": 1,
"question": "You are given an array of integers `arr` and an integer `target`. Determine if there exist **two distinct elements** in the array such that their sum is equal to `target`. If such a pair exists, return `true`; otherwise, return `false`. You can assume ... |
def longest_common_subsequence(nums1, nums2):
m = len(nums1)
n = len(nums2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if nums1[i-1] == nums2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
d... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two integer arrays `nums1` and `nums2`, both of which contain unique elements. A subset of `nums1` can be regarded as a subsequence in `nums2` if all elements of the subset appear in `nums2` in the same order as they do in `nums1`, but not necessarily consecutively. Return... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2449,
"level": 1,
"question": "You are given two integer arrays `nums1` and `nums2`, both of which contain unique elements. A subset of `nums1` can be regarded as a subsequence in `nums2` if all elements of the subset appear in `nums2` in the same order as they do in `nums1`, but no... |
def limit(arr, min_lim=None, max_lim=None):
"""
Filters the given array so that only elements in the specified range are included.
Parameters:
arr (list): List of integers to be filtered.
min_lim (int, optional): Minimum limit of the range (inclusive). Default is None, which means no minimum limit.... | simplelr_Data_Structure | [
{
"content": "Question:\n**Scenario**: You are given an array of integers and want to filter the array to include only elements within a specified range. This is a common requirement in data processing where you might want to focus only on relevant numerical data.\n\n**Task**: Implement a function that filters ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2450,
"level": 1,
"question": "**Scenario**: You are given an array of integers and want to filter the array to include only elements within a specified range. This is a common requirement in data processing where you might want to focus only on relevant numerical data.\n\n**Task**:... |
import unicodedata
def process_unicode_file(input_file: str, output_file: str) -> None:
# Read the input file using ASCII encoding with surrogateescape to handle unknown/mixed encodings
with open(input_file, 'r', encoding='ascii', errors='surrogateescape') as f:
content = f.read()
# Normalize ... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\nYou are tasked to write a Python function that reads a text file with unknown or mixed encodings, processes the contents to convert all text to UTF-8 encoding, and writes the processed text to a new file. During processing, you should normalize all Unicode strings to the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2451,
"level": 1,
"question": "#### Objective\nYou are tasked to write a Python function that reads a text file with unknown or mixed encodings, processes the contents to convert all text to UTF-8 encoding, and writes the processed text to a new file. During processing, you should n... |
def remove_vowels(s):
if not isinstance(s, str):
return "Invalid input"
vowels = {'a', 'e', 'i', 'o', 'u'}
return ''.join([c for c in s if c.lower() not in vowels]) | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a string as input and returns a new string where all the vowels (a, e, i, o, u) have been removed. The function should handle both uppercase and lowercase vowels, but should preserve the case of all other letters and the positioning of non-letter characters.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2452,
"level": 1,
"question": "Write a function that takes a string as input and returns a new string where all the vowels (a, e, i, o, u) have been removed. The function should handle both uppercase and lowercase vowels, but should preserve the case of all other letters and the pos... |
def resize_list(lst, target_length, fill_value=None):
if target_length == 0:
return []
current_length = len(lst)
if current_length > target_length:
return lst[:target_length]
else:
additional = target_length - current_length
return lst + [fill_value] * additional | simplelr_Filter | [
{
"content": "Question:\nI need to resize a list in Python to a specific length by either truncating it or filling it with a specific value. Can you show me how to do this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2453,
"level": 1,
"question": "I need to resize a list in Python to a specific length by either truncating it or filling it with a specific value. Can you show me how to do this?",
"split": "train"
} |
from collections import deque
def can_reach(roads, start, target, closed_roads):
# Build adjacency list using sets for efficient removal
adj = {}
for u, v in roads:
if u not in adj:
adj[u] = set()
if v not in adj:
adj[v] = set()
adj[u].add(v)
adj[v].a... | simplelr_Apps | [
{
"content": "Question:\n**Story** \nYou are tasked with monitoring a city's traffic by tracking the movement of vehicles at various intersections. Each intersection can be represented as a node in a graph, and each road between intersections can be represented as an edge. Due to a recent city planning initiat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2454,
"level": 1,
"question": "**Story** \nYou are tasked with monitoring a city's traffic by tracking the movement of vehicles at various intersections. Each intersection can be represented as a node in a graph, and each road between intersections can be represented as an edge. Du... |
def robot_end_position(s):
x, y = 0, 0
for char in s:
if char == 'U':
y += 1
elif char == 'D':
y -= 1
elif char == 'R':
x += 1
elif char == 'L':
x -= 1
return (x, y)
| simplelr_Taco | [
{
"content": "Question:\nYou are given a string that represents a sequence of movements made by a robot in a 2D grid. The robot starts at the origin point (0, 0) and can move in four directions: up, down, left, and right. Each movement is represented by a character: 'U' for up, 'D' for down, 'L' for left, and '... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2455,
"level": 1,
"question": "You are given a string that represents a sequence of movements made by a robot in a 2D grid. The robot starts at the origin point (0, 0) and can move in four directions: up, down, left, and right. Each movement is represented by a character: 'U' for up... |
def trap(height):
left = 0
right = len(height) - 1
max_left = 0
max_right = 0
res = 0
while left <= right:
if max_left < max_right:
if height[left] > max_left:
max_left = height[left]
else:
res += max_left - height[left]
... | simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers representing the amount of water trapped between heights in a histogram, return the quantity of trapped water.\n\nThe \"height\" list represents a histogram where the width of each bar is 1 unit.\n\nExample 1:\nInput: height = [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput: ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2456,
"level": 1,
"question": "Given a list of integers representing the amount of water trapped between heights in a histogram, return the quantity of trapped water.\n\nThe \"height\" list represents a histogram where the width of each bar is 1 unit.\n\nExample 1:\nInput: height = ... |
import bisect
def find_lexicographic_rank(s):
n = len(s)
if n == 0:
return 1
# Precompute factorials up to (n-1)!
fact = [1] * n
for i in range(1, n):
fact[i] = fact[i-1] * i
# Create a sorted list of characters
sorted_chars = sorted(s)
rank = 0
for i ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s`, return _the rank of the string amongst its permutations sorted lexicographically_. Assume no characters are repeated in the string. The rank should be `1`-indexed. For example, the string \"abc\" is the first permutation in lexicographical order, so its rank is `1`. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2457,
"level": 1,
"question": "Given a string `s`, return _the rank of the string amongst its permutations sorted lexicographically_. Assume no characters are repeated in the string. The rank should be `1`-indexed. For example, the string \"abc\" is the first permutation in lexicogr... |
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the factorial of a number using recursion. The factorial of a number n, denoted by n!, is the product of all positive integers not greater than n. For instance, 5! = 5 * 4 * 3 * 2 * 1 = 120. The factorial of 0 is defined as 1. Please provide a Python... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2458,
"level": 1,
"question": "Write a python function to calculate the factorial of a number using recursion. The factorial of a number n, denoted by n!, is the product of all positive integers not greater than n. For instance, 5! = 5 * 4 * 3 * 2 * 1 = 120. The factorial of 0 is de... |
def is_palindrome(n):
# Convert the number to a string
s = str(n)
# Reverse the string
reversed_s = s[::-1]
# Check if the string is equal to its reverse
return s == reversed_s
# Example usage:
print(is_palindrome(121)) # Output: True
print(is_palindrome(123)) # Output: False | simplelr_Filter | [
{
"content": "Question:\nhow can I write a Python function to check if a given number is a palindrome? A palindrome is a number that reads the same backward as forward, such as 12321 or 111.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2459,
"level": 1,
"question": "how can I write a Python function to check if a given number is a palindrome? A palindrome is a number that reads the same backward as forward, such as 12321 or 111.",
"split": "train"
} |
import random
import string
def generate_password(n):
if n < 4:
return ""
lower = string.ascii_lowercase
upper = string.ascii_uppercase
digits = string.digits
specials = '!@#$%^&*'
password = [
random.choice(lower),
random.choice(upper),
random.choice(d... | simplelr_Code_Contests | [
{
"content": "Question:\nA password manager application needs a function to generate secure passwords. The password must follow these rules:\n\n1. The password length should be exactly n characters.\n2. It must include at least one lowercase letter, one uppercase letter, one digit, and one special character (!,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2460,
"level": 1,
"question": "A password manager application needs a function to generate secure passwords. The password must follow these rules:\n\n1. The password length should be exactly n characters.\n2. It must include at least one lowercase letter, one uppercase letter, one d... |
def get_max_value(x, y):
if x >= 0 and y >= 0:
return max(x, y)
else:
return x ** 2 + y ** 2 | simplelr_Filter | [
{
"content": "Question:\nYou have been tasked with designing a function `get_max_value` that takes two integer parameters, `x` and `y`. The function should return the maximum value between `x` and `y` if both are non-negative. If either `x` or `y` is negative, the function should return the sum of their squares... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2461,
"level": 1,
"question": "You have been tasked with designing a function `get_max_value` that takes two integer parameters, `x` and `y`. The function should return the maximum value between `x` and `y` if both are non-negative. If either `x` or `y` is negative, the function sho... |
import csv
def read_csv_to_dict_list(filename):
with open(filename, 'r') as csvfile:
csvreader = csv.DictReader(csvfile)
rows = [row for row in csvreader]
return rows | simplelr_Filter | [
{
"content": "Question:\nI need to write a Python function that reads a CSV file and returns a list of dictionaries, where each dictionary represents a row in the CSV file with keys corresponding to the column headers. If the CSV file is empty, the function should return an empty list. How can I achieve this us... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2462,
"level": 1,
"question": "I need to write a Python function that reads a CSV file and returns a list of dictionaries, where each dictionary represents a row in the CSV file with keys corresponding to the column headers. If the CSV file is empty, the function should return an em... |
def warehouse_manager(commands):
inventory = {}
output = []
for command in commands:
parts = command.split()
if parts[0] == 'add':
product_id = parts[1]
quantity = int(parts[2])
inventory[product_id] = inventory.get(product_id, 0) + quantity
elif p... | simplelr_Codeforces | [
{
"content": "Question:\n### Problem Statement\n\nA warehouse management system needs to keep track of inventory levels for various products. Each product is identified by a string `productID`, and its quantity in stock is represented by an integer. The system receives a series of instructions in the form of co... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2463,
"level": 1,
"question": "### Problem Statement\n\nA warehouse management system needs to keep track of inventory levels for various products. Each product is identified by a string `productID`, and its quantity in stock is represented by an integer. The system receives a serie... |
def all_components_functioning(mat):
result = 1
for row in mat:
for elem in row:
result &= elem
return bool(result) | simplelr_Filter | [
{
"content": "Question:\nSuppose we have a 10x10 matrix of boolean variables representing the status of components of an industrial process. The variable is true if the component is functioning properly, and false otherwise. You need to write a Python function that returns True if and only if all the variables ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2464,
"level": 1,
"question": "Suppose we have a 10x10 matrix of boolean variables representing the status of components of an industrial process. The variable is true if the component is functioning properly, and false otherwise. You need to write a Python function that returns Tru... |
import json
def merge_lists(file_path):
try:
with open(file_path, 'r') as file:
data = json.load(file)
except FileNotFoundError:
return
# Extract the lists from the data
if isinstance(data, dict) and 'lists' in data and isinstance(data['lists'], list):
lists_in_... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with writing a function called `merge_lists` that merges multiple lists of integers into a single sorted list without duplicates. The lists will be provided in a JSON file with the following structure:\n\n```json\n{\n \"lists\": [[1, 3, 5], [1, 2, 3], [4, 6, 3], ...]\n}\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2465,
"level": 1,
"question": "You are tasked with writing a function called `merge_lists` that merges multiple lists of integers into a single sorted list without duplicates. The lists will be provided in a JSON file with the following structure:\n\n```json\n{\n \"lists\": [[1, 3,... |
def min_operations_to_reduce(nums):
return len(nums) - 1 | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array `nums` consisting of `n` positive integers. You can perform the following operation on the array any number of times: choose any two adjacent elements and replace them with their sum. Your task is to determine the minimum number of operations required to reduce th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2466,
"level": 1,
"question": "You are given an array `nums` consisting of `n` positive integers. You can perform the following operation on the array any number of times: choose any two adjacent elements and replace them with their sum. Your task is to determine the minimum number ... |
def fahrenheit_to_celsius(fahrenheit):
"""
Converts a temperature from Fahrenheit to Celsius.
Args:
fahrenheit (float): The temperature in Fahrenheit.
Returns:
float: The temperature in Celsius.
"""
celsius = (fahrenheit - 32) * 5/9
return celsius
# Example usage:
... | simplelr_Filter | [
{
"content": "Question:\nCan you help me write a function in Python that converts a given temperature from Fahrenheit to Celsius?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2467,
"level": 1,
"question": "Can you help me write a function in Python that converts a given temperature from Fahrenheit to Celsius?",
"split": "train"
} |
def negate_if_negative(num):
return abs(num) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as an argument and returns the negation of the passed number, if it is negative, and returns the number itself if it is non-negative.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2468,
"level": 1,
"question": "Create a function that takes an integer as an argument and returns the negation of the passed number, if it is negative, and returns the number itself if it is non-negative.",
"split": "train"
} |
def sort_decimal_strings(strings):
return sorted(strings, key=lambda x: float(x)) | simplelr_Evol | [
{
"content": "Question:\nWrite a function in Python that takes a list of strings, where each string represents a decimal number. The function should return a new list containing the strings sorted in ascending order according to their numeric value. If two strings represent the same number, their order should r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2469,
"level": 1,
"question": "Write a function in Python that takes a list of strings, where each string represents a decimal number. The function should return a new list containing the strings sorted in ascending order according to their numeric value. If two strings represent th... |
import unicodedata
def unicode_string_analysis(input_string: str) -> dict:
result = {}
seen = set()
unique_chars = []
# Collect unique characters in the order of their first occurrence
for c in input_string:
if c not in seen:
seen.add(c)
unique_chars.append(c)
... | simplelr_Docs | [
{
"content": "Question:\n### Unicode String Processing with unicodedata Module\n\nYou are tasked with creating a function that processes a given Unicode string and returns a detailed analysis of its characters. The analysis should include the following information for each character in the string:\n\n1. The cha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2470,
"level": 1,
"question": "### Unicode String Processing with unicodedata Module\n\nYou are tasked with creating a function that processes a given Unicode string and returns a detailed analysis of its characters. The analysis should include the following information for each cha... |
def sort_even_odd(numbers):
evens = [num for num in numbers if num % 2 == 0]
odds = [num for num in numbers if num % 2 != 0]
evens.sort()
odds.sort()
return evens + odds | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that sorts a list of numbers into two separate lists of even and odd numbers, and then combines them, with even numbers first, both in ascending order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2471,
"level": 1,
"question": "Write a Python function that sorts a list of numbers into two separate lists of even and odd numbers, and then combines them, with even numbers first, both in ascending order.",
"split": "train"
} |
from typing import List, Tuple
def schedule_meeting(start_hour: int, meeting_duration: int, break_duration: int) -> List[Tuple[int, int]]:
meetings = []
current_start = start_hour
while current_start + meeting_duration <= 24:
end_time = current_start + meeting_duration
meetings.append((curr... | simplelr_Package | [
{
"content": "Question:\nThe goal is to create a function named `schedule_meeting` which takes three integer inputs: `start_hour`, `meeting_duration`, and `break_duration`. This function should return a list of tuples representing possible meeting starting times within a 24-hour period.\n\nTo determine the poss... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2472,
"level": 1,
"question": "The goal is to create a function named `schedule_meeting` which takes three integer inputs: `start_hour`, `meeting_duration`, and `break_duration`. This function should return a list of tuples representing possible meeting starting times within a 24-ho... |
def sort_list_of_dictionaries(data, key):
"""Sorts a list of dictionaries by a specified key.
Args:
data: A list of dictionaries.
key: The key to sort by.
Returns:
A new list of dictionaries sorted by the specified key.
"""
return sorted(data, key=lambda dictionary: diction... | simplelr_Filter | [
{
"content": "Question:\nIt says:\n\n**Write a Python script that:**\n\n\n\n1. **Takes a list of dictionaries as input.**\n2. **Sorts the list of dictionaries by a specified key.**\n\nHere's an example input and expected output:\n\n**Input:**\n\n```python\ndata = [\n {'name': 'John', 'age': 30},\n {'name': 'A... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2473,
"level": 1,
"question": "It says:\n\n**Write a Python script that:**\n\n\n\n1. **Takes a list of dictionaries as input.**\n2. **Sorts the list of dictionaries by a specified key.**\n\nHere's an example input and expected output:\n\n**Input:**\n\n```python\ndata = [\n {'name':... |
def count_non_overlapping_substrings(s):
return len(s) // 3 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that returns the number of non-overlapping sub-strings of length 3 that can be formed from a given string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2474,
"level": 1,
"question": "Create a function that returns the number of non-overlapping sub-strings of length 3 that can be formed from a given string.",
"split": "train"
} |
def unique_elements(lst):
seen = set()
result = []
for num in lst:
if num not in seen:
seen.add(num)
result.append(num)
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a new list containing only the unique elements from the input list. The order of the elements in the output list should be the same as their first occurrence in the input list.\nAnswer:\nLet's think step by step.\n",
"role"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2475,
"level": 1,
"question": "Create a function that takes a list of integers and returns a new list containing only the unique elements from the input list. The order of the elements in the output list should be the same as their first occurrence in the input list.",
"split": "t... |
def process_instructions(instructions: list) -> int:
num_set = set()
for instruction in instructions:
action, value = instruction.split()
value = int(value)
if action == "add":
num_set.add(value)
elif action == "remove":
num_set.discard(value... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python program that processes a list of strings, where each string represents an instruction to either \"add\" or \"remove\" a number from a set. Your program should maintain the set of numbers accordingly and print the sum of the elements in the set after processing all the ins... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2476,
"level": 1,
"question": "Write a Python program that processes a list of strings, where each string represents an instruction to either \"add\" or \"remove\" a number from a set. Your program should maintain the set of numbers accordingly and print the sum of the elements in t... |
import bisect
def longest_increasing_subsequence(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_Prefill | [
{
"content": "Question:\nWrite a python function to solve the longest increasing subsequence problem (LIS).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2477,
"level": 1,
"question": "Write a python function to solve the longest increasing subsequence problem (LIS).",
"split": "train"
} |
def max_of_four(a, b, c, d):
return max(a, b, c, d) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum of four numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2478,
"level": 1,
"question": "Write a python function to find the maximum of four numbers.",
"split": "train"
} |
def increment_elements(lst):
return [x + 1 for x in lst] | simplelr_Filter | [
{
"content": "Question:\nYou can use Python to solve this problem. Write a function that takes in a list of integers as input, and returns a list where all the elements from the input list are incremented by 1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2479,
"level": 1,
"question": "You can use Python to solve this problem. Write a function that takes in a list of integers as input, and returns a list where all the elements from the input list are incremented by 1.",
"split": "train"
} |
import difflib
from difflib import HtmlDiff
def generate_diffs(seq1, seq2, unified=False, context=False, html=False):
result = {}
# Determine which formats to generate
if not (unified or context or html):
selected_formats = ['unified']
else:
selected_formats = []
if unified... | simplelr_Docs | [
{
"content": "Question:\n### Question: Analyzing and Displaying Sequence Differences in Various Formats\n\nYou are tasked with creating a script that analyzes differences between two sequences of strings. You will use the `difflib` package to compare the sequences and output the differences in three specified f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2480,
"level": 1,
"question": "### Question: Analyzing and Displaying Sequence Differences in Various Formats\n\nYou are tasked with creating a script that analyzes differences between two sequences of strings. You will use the `difflib` package to compare the sequences and output t... |
def minimum(a, b):
return min(a, b) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes 2 numbers as input and returns the minimum of these two.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2481,
"level": 1,
"question": "Create a function that takes 2 numbers as input and returns the minimum of these two.",
"split": "train"
} |
def hasPairWithSum(arr, K):
seen = set()
for num in arr:
complement = K - num
if complement in seen:
return "YES"
seen.add(num)
return "NO"
| simplelr_Taco | [
{
"content": "Question:\nYou are given a list of integers and a target integer K. Your task is to determine if there exist two distinct integers in the list whose sum is equal to K.\n\nExample 1:\nInput:\narr = [1, 3, 4, 2, 5]\nK = 6\nOutput:\nYES\nExplanation:\nBecause 1 + 5 = 6 or 2 + 4 = 6\n\nExample 2:\nInp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2482,
"level": 1,
"question": "You are given a list of integers and a target integer K. Your task is to determine if there exist two distinct integers in the list whose sum is equal to K.\n\nExample 1:\nInput:\narr = [1, 3, 4, 2, 5]\nK = 6\nOutput:\nYES\nExplanation:\nBecause 1 + 5 ... |
def calculate_sum(numbers):
"""Calculates the sum of all numbers in a list."""
return sum(numbers) | simplelr_Filter | [
{
"content": "Question:\n* Your code should handle the following inputs:\n * Positive integers\n * Negative integers\n * Zero\n\n**Write a Python function called 'calculate_sum' that takes a list of numbers as input and returns the sum of all the numbers in the list.**\n\n```python\ndef calculate_sum(n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2483,
"level": 1,
"question": "* Your code should handle the following inputs:\n * Positive integers\n * Negative integers\n * Zero\n\n**Write a Python function called 'calculate_sum' that takes a list of numbers as input and returns the sum of all the numbers in the list.*... |
def sort_complex_desc(complex_list):
"""
Sorts a list of complex numbers in descending order based on their magnitude.
Args:
complex_list (list): A list of complex numbers.
Returns:
list: A new list sorted by the magnitude of the complex numbers in descending order.
"""
return ... | simplelr_Filter | [
{
"content": "Question:\nHow can I create a function in Python that sorts a list of complex numbers based on their magnitude in descending order?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2484,
"level": 1,
"question": "How can I create a function in Python that sorts a list of complex numbers based on their magnitude in descending order?",
"split": "train"
} |
def is_valid_bracket_sequence(s: str) -> bool:
stack = []
for char in s:
if char == '[':
stack.append(char)
else:
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Evol | [
{
"content": "Question:\nDetermine whether a given string contains valid pairs of brackets. A pair of brackets is valid if every opening bracket \"[\" has a corresponding closing bracket \"]\", and they are correctly nested.\n\nFunction Signature: `def is_valid_bracket_sequence(s: str) -> bool`\n\nParameters:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2485,
"level": 1,
"question": "Determine whether a given string contains valid pairs of brackets. A pair of brackets is valid if every opening bracket \"[\" has a corresponding closing bracket \"]\", and they are correctly nested.\n\nFunction Signature: `def is_valid_bracket_sequenc... |
def findMaxLength(arr):
balance_map = {0: -1}
current_balance = 0
max_length = 0
for i, num in enumerate(arr):
current_balance += 1 if num == 1 else -1
if current_balance in balance_map:
length = i - balance_map[current_balance]
if length > max_length:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `arr`, find the maximum length of a subarray with equal number of 0s and 1s. Return _the length of the longest subarray that contains an equal number of 0s and 1s_.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2486,
"level": 1,
"question": "Given an integer array `arr`, find the maximum length of a subarray with equal number of 0s and 1s. Return _the length of the longest subarray that contains an equal number of 0s and 1s_.",
"split": "train"
} |
def getPrimeNumbers(n):
primes = []
for i in range(2, n + 1):
is_prime = True
for j in range(2, int(i ** 0.5) + 1):
if i % j == 0:
is_prime = False
break
if is_prime:
primes.append(i)
return primes
| simplelr_Taco | [
{
"content": "Question:\nGiven an integer n, return a list of all prime numbers up to and including n. A prime number is a natural number greater than 1 that is not divisible by any number other than 1 and itself. The order in the output list should be from smallest to largest prime.\n\nExample 1:\nInput: n = 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2487,
"level": 1,
"question": "Given an integer n, return a list of all prime numbers up to and including n. A prime number is a natural number greater than 1 that is not divisible by any number other than 1 and itself. The order in the output list should be from smallest to largest... |
from typing import List
def counting_sort(arr: List[int], max_val: int) -> List[int]:
"""
Sorts an array of non-negative integers using the Counting Sort algorithm.
Args:
arr (List[int]): The input array to be sorted.
max_val (int): The maximum value in the input array.
Returns:
... | simplelr_Data_Structure | [
{
"content": "Question:\n**Objective**: Implement and utilize a non-comparison-based sorting algorithm.\n\n**Context**: Stooge Sort is an inefficient sorting algorithm with a time complexity of \\(O(n^{2.709})\\), chiefly used for educational purposes. In contrast, non-comparison sorts like Counting Sort, Radix... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2488,
"level": 1,
"question": "**Objective**: Implement and utilize a non-comparison-based sorting algorithm.\n\n**Context**: Stooge Sort is an inefficient sorting algorithm with a time complexity of \\(O(n^{2.709})\\), chiefly used for educational purposes. In contrast, non-compari... |
def reorderEvenOdd(arr):
evens = []
odds = []
for num in arr:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens + odds
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, create a function to reorder the list so that all even integers appear before all odd integers, while maintaining the relative order of the even integers and the relative order of the odd integers.\n\nExample 1:\nInput:\narr = [1, 2, 3, 4, 5, 6]\nOutput:\n[2, 4... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2489,
"level": 1,
"question": "Given a list of integers, create a function to reorder the list so that all even integers appear before all odd integers, while maintaining the relative order of the even integers and the relative order of the odd integers.\n\nExample 1:\nInput:\narr =... |
def remove_duplicates(users):
seen = set()
unique_users = []
for user in users:
name = user['name']
email = user['email']
phone = user['phone']
# Generate all possible pairs sorted lexicographically
pairs = [
tuple(sorted((name, email))),
... | simplelr_Apps | [
{
"content": "Question:\nA company has a database storing users' details. Occasionally, a script must run to identify and remove duplicate records. Each record is a dictionary containing keys: 'name', 'email', and 'phone'. Two records are considered duplicates if at least two out of these three fields match.\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2490,
"level": 1,
"question": "A company has a database storing users' details. Occasionally, a script must run to identify and remove duplicate records. Each record is a dictionary containing keys: 'name', 'email', and 'phone'. Two records are considered duplicates if at least two ... |
def sort_people(people):
return sorted(people, key=lambda x: (x['last_name'], x['first_name'], x['age'])) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of dictionaries, where each dictionary represents a person with keys for their first name, last name, and age. The function should return a new list of dictionaries sorted by last name, then by first name. If two people have the same last name a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2491,
"level": 1,
"question": "Write a Python function that takes a list of dictionaries, where each dictionary represents a person with keys for their first name, last name, and age. The function should return a new list of dictionaries sorted by last name, then by first name. If t... |
def delete_element(lst, elem):
return [x for x in lst if x != elem] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to delete an element from a given list of integers. The function should delete all occurrences of the specified element. If the element is not found, the function should return the original list unchanged.\nAnswer:\nLet's think step by step.\n",
"role": "user... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2492,
"level": 1,
"question": "Write a python function to delete an element from a given list of integers. The function should delete all occurrences of the specified element. If the element is not found, the function should return the original list unchanged.",
"split": "train"
} |
def count_unique_common_chars(string1: str, string2: str) -> int:
"""
This function calculates the number of unique characters that appear in both input strings,
ignoring case sensitivity.
Args:
string1 (str): The first string.
string2 (str): The second string.
Returns:
in... | simplelr_Filter | [
{
"content": "Question:\nWrite documentation for a Python function that takes two strings as inputs. This function should return the number of unique characters that appear in both strings, ignoring case sensitivity. The function name is `count_unique_common_chars`.\nAnswer:\nLet's think step by step.\n",
"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2493,
"level": 1,
"question": "Write documentation for a Python function that takes two strings as inputs. This function should return the number of unique characters that appear in both strings, ignoring case sensitivity. The function name is `count_unique_common_chars`.",
"split... |
def fib(n: int) -> int:
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b | simplelr_Algorithm | [
{
"content": "Question:\n### Fibonacci Sequence Memory Optimization\n\n#### Problem Statement\n\nYou are required to compute the nth Fibonacci number using a memory-optimized approach. The Fibonacci sequence is defined as:\n\n\\[ F(0) = 0 \\]\n\\[ F(1) = 1 \\]\n\\[ F(n) = F(n-1) + F(n-2) \\,\\, \\text{for} \\,\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2494,
"level": 1,
"question": "### Fibonacci Sequence Memory Optimization\n\n#### Problem Statement\n\nYou are required to compute the nth Fibonacci number using a memory-optimized approach. The Fibonacci sequence is defined as:\n\n\\[ F(0) = 0 \\]\n\\[ F(1) = 1 \\]\n\\[ F(n) = F(n-... |
def next_greater_elements(arr):
n = len(arr)
stack = []
next_greater = [-1] * n
for i in range(n-1, -1, -1):
while stack and stack[-1] <= arr[i]:
stack.pop()
if stack:
next_greater[i] = stack[-1]
else:
next_greater[i] = -1
stack.append(... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the next greater element for each element in an array. The next greater element for a given element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the next greater element as -1. You shou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2495,
"level": 1,
"question": "Write a function to find the next greater element for each element in an array. The next greater element for a given element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the n... |
def count_digits_divisible_by_3(n):
count = 0
for digit in str(abs(n)):
if int(digit) % 3 == 0:
count += 1
return count | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to count the number of digits in an integer that are divisible by 3.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2496,
"level": 1,
"question": "Write a python function to count the number of digits in an integer that are divisible by 3.",
"split": "train"
} |
def draw_pyramid(levels):
width = 2 * levels - 1
pyramid = []
for level in range(1, levels + 1):
stars = '*' * (2 * level - 1)
line = stars.center(width)
pyramid.append(line)
return '\n'.join(pyramid) | simplelr_Filter | [
{
"content": "Question:\nCan you create a Python function that draws a pyramid with ASCII characters? The pyramid should have a specified number of levels, where each level has an increasing number of stars, centered horizontally in a line of a fixed width. The width of the line is determined by the number of l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2497,
"level": 1,
"question": "Can you create a Python function that draws a pyramid with ASCII characters? The pyramid should have a specified number of levels, where each level has an increasing number of stars, centered horizontally in a line of a fixed width. The width of the li... |
def largest_integer_whose_square_is_less_than_or_equal_to(n):
if n < 0:
return None
low = 0
high = n
while low <= high:
mid = (low + high) // 2
mid_sq = mid * mid
if mid_sq == n:
return mid
elif mid_sq < n:
low = mid + 1
else:
... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as an input and returns the largest integer whose square is less than or equal to the given integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2498,
"level": 1,
"question": "Create a function that takes an integer as an input and returns the largest integer whose square is less than or equal to the given integer.",
"split": "train"
} |
def uniquePathsWithObstacles(obstacleGrid):
m = len(obstacleGrid)
n = len(obstacleGrid[0]) if m > 0 else 0
# Create a dp table initialized to 0
dp = [[0]*n for _ in range(m)]
# Check if the starting position is blocked
if obstacleGrid[0][0] == 1:
return 0
dp[0][0] = 1 # St... | simplelr_Taco | [
{
"content": "Question:\n# Unique Paths with Obstacles\n\nYou are given a 2D grid, `obstacleGrid`, of size `m x n` representing a robot's map where:\n- `0` represents an empty space.\n- `1` represents an obstacle.\n\nThe robot can only move either down or right at any point in time. The robot is trying to reach... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2499,
"level": 1,
"question": "# Unique Paths with Obstacles\n\nYou are given a 2D grid, `obstacleGrid`, of size `m x n` representing a robot's map where:\n- `0` represents an empty space.\n- `1` represents an obstacle.\n\nThe robot can only move either down or right at any point in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.