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 maximal_square(matrix):
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
return 0
m = len(matrix)
n = len(matrix[0])
dp = [[0 for _ in range(n)] for _ in range(m)]
max_side = 0
for i in range(m):
for j in range(n):
if matrix[i][j] == 'O':
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a `2D` matrix of dimensions `m x n` containing only the characters 'X' and 'O', where:\n- 'X' represents an obstacle,\n- 'O' represents an open space,\n\nYour task is to determine _the size of the largest square consisting entirely of 'O's_. Return the area of this square.\nAnswer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5000,
"level": 1,
"question": "Given a `2D` matrix of dimensions `m x n` containing only the characters 'X' and 'O', where:\n- 'X' represents an obstacle,\n- 'O' represents an open space,\n\nYour task is to determine _the size of the largest square consisting entirely of 'O's_. Retu... |
def find_first_even_index(nums):
for index, number in enumerate(nums):
if number % 2 == 0:
return index
return -1 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the index of the first even number in a list using a for loop. If no even number is found, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5001,
"level": 1,
"question": "Write a python function to find the index of the first even number in a list using a for loop. If no even number is found, return -1.",
"split": "train"
} |
def group_consecutive_numbers(numbers):
if not numbers:
return []
sorted_numbers = sorted(numbers)
clusters = []
current_cluster = [sorted_numbers[0]]
for num in sorted_numbers[1:]:
if num == current_cluster[-1] + 1:
current_cluster.append(num)
else:
c... | simplelr_Evol | [
{
"content": "Question:\nDevelop a program that reads a list of integers and groups them into clusters of consecutive sequences. The program should return a list of lists, where each inner list contains a consecutive sequence of integers from the input list. Ensure that the integers within each sequence are sor... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5002,
"level": 1,
"question": "Develop a program that reads a list of integers and groups them into clusters of consecutive sequences. The program should return a list of lists, where each inner list contains a consecutive sequence of integers from the input list. Ensure that the in... |
def filter_strings_with_a(string_list):
return [s for s in string_list if len(s) > 5 and 'a' in s] | simplelr_Filter | [
{
"content": "Question:\nGiven a list of strings, write a Python function that returns a new list containing only the strings that have a length greater than 5 and contain the letter 'a'. The function should be named `filter_strings_with_a` and should take a single argument, `string_list`, which is a list of st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5003,
"level": 1,
"question": "Given a list of strings, write a Python function that returns a new list containing only the strings that have a length greater than 5 and contain the letter 'a'. The function should be named `filter_strings_with_a` and should take a single argument, `... |
def product_or_sum(lst):
sum_total = 0
product = 1
has_even = False
for num in lst:
sum_total += num
product *= num
if num % 2 == 0:
has_even = True
return product if has_even else sum_total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that returns the product of all elements in a list if any element is even, and the sum of all elements if all elements are odd.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5004,
"level": 1,
"question": "Create a function that returns the product of all elements in a list if any element is even, and the sum of all elements if all elements are odd.",
"split": "train"
} |
def partitionArray(arr, n, k):
if n % k != 0:
return []
arr_sorted = sorted(arr)
partitions = []
for i in range(0, n, k):
partitions.append(arr_sorted[i:i+k])
return partitions
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers `arr` of size `n` and an integer `k`, partition the array in such a way that each partition has exactly `k` elements and all the partitions are in increasing order. If it is impossible to do so, return an empty array.\n\nExample 1:\nInput:\narr = [3, 1, 2, 4, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5005,
"level": 1,
"question": "Given an array of integers `arr` of size `n` and an integer `k`, partition the array in such a way that each partition has exactly `k` elements and all the partitions are in increasing order. If it is impossible to do so, return an empty array.\n\nExam... |
def convert_list_to_string(numbers):
result = []
for index, num in enumerate(numbers):
s = str(num)
if (index + 1) % 3 == 0:
s = f"*{s}*"
result.append(s)
return ','.join(result) | simplelr_Filter | [
{
"content": "Question:\nCan you write a function in Python that converts a given list of numbers into a string, where the numbers are separated by commas and every third number is highlighted with asterisks before and after it? For example, if the input is `[1, 2, 3, 4, 5, 6, 7]`, the output should be `\"1,2,*... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5006,
"level": 1,
"question": "Can you write a function in Python that converts a given list of numbers into a string, where the numbers are separated by commas and every third number is highlighted with asterisks before and after it? For example, if the input is `[1, 2, 3, 4, 5, 6,... |
def can_form_palindrome(s: str) -> bool:
mask = 0
for c in s:
if c.islower():
idx = ord(c) - ord('a')
elif c.isupper():
idx = 26 + (ord(c) - ord('A'))
else: # digit
idx = 52 + (ord(c) - ord('0'))
mask ^= (1 << idx)
return bin(mask).count('... | simplelr_Algorithm | [
{
"content": "Question:\n# Palindrome Substring Function Implementation\n\n### Scenario\nYou are building a text editor with advanced string manipulation features. One of the features required is to identify if a given substring can be rearranged to form a palindrome. This is useful for special text effects and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5007,
"level": 1,
"question": "# Palindrome Substring Function Implementation\n\n### Scenario\nYou are building a text editor with advanced string manipulation features. One of the features required is to identify if a given substring can be rearranged to form a palindrome. This is ... |
def find_nth_digit(n: int) -> int:
k = 1
while True:
count = 9 * 10 ** (k - 1) * k
if n > count:
n -= count
k += 1
else:
break
start = 10 ** (k - 1)
number = start + (n - 1) // k
digit_index = (n - 1) % k
return int(str(number)[digit_in... | simplelr_Data_Structure | [
{
"content": "Question:\nFind the Nth Digit in an Infinite Sequence\nIn an infinite sequence of integers where all positive numbers are concatenated together, find the nth digit of this sequence.\n\n### Example\nIf the sequence looks like \"1234567891011121314...\", the digit positions would map as follows:\n* ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5008,
"level": 1,
"question": "Find the Nth Digit in an Infinite Sequence\nIn an infinite sequence of integers where all positive numbers are concatenated together, find the nth digit of this sequence.\n\n### Example\nIf the sequence looks like \"1234567891011121314...\", the digit ... |
def reverse_string_and_words(s):
reversed_str = s[::-1]
words = reversed_str.split()
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words) | simplelr_Filter | [
{
"content": "Question:\nYou are given a string \"hello world\". Your task is to reverse the string, and then reverse each word in the string. For example, if the input is \"hello world\", the output should first be \"dlrow olleh\" (string reversed), and then \"world hello\" (each word reversed). Write a Python... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5009,
"level": 1,
"question": "You are given a string \"hello world\". Your task is to reverse the string, and then reverse each word in the string. For example, if the input is \"hello world\", the output should first be \"dlrow olleh\" (string reversed), and then \"world hello\" (... |
def findAnagrams(s, p):
m = len(p)
n = len(s)
result = []
if m > n:
return result
# Count arrays for p and current window
p_count = [0] * 26
s_count = [0] * 26
# Initialize counts for p
for c in p:
p_count[ord(c) - ord('a')] += 1
# Initialize c... | simplelr_Taco | [
{
"content": "Question:\nGiven a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,000.\n\nExample 1:\nInput:\ns = \"cbaebabacd\"\np = \"abc\"\nOutput:\n[0, 6]\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5010,
"level": 1,
"question": "Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,000.\n\nExample 1:\nInput:\ns = \"cbaebabac... |
def is_valid_password(password: str) -> bool:
"""
Checks if the given password meets the security criteria.
A valid password must:
- Contain at least one uppercase letter
- Contain at least one lowercase letter
- Contain at least one digit
- Contain at least one special character
- ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to check whether the input password is valid or not. The password is considered valid if it contains at least one uppercase letter, one lowercase letter, one digit, and one special character, and its length is at least 8 characters.\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5011,
"level": 1,
"question": "Write a python function to check whether the input password is valid or not. The password is considered valid if it contains at least one uppercase letter, one lowercase letter, one digit, and one special character, and its length is at least 8 charact... |
def compress_string(s):
if not s:
return s
res = []
current = s[0]
count = 1
for c in s[1:]:
if c == current:
count += 1
else:
res.append(f"{current}{count}")
current = c
count = 1
res.append(f"{current}{count}")
compres... | simplelr_Taco | [
{
"content": "Question:\nZara is a software developer who loves to work with strings. She is currently working on a project where she needs to compress a given string using Run-Length Encoding (RLE) technique. The Run-Length Encoding is a simple form of data compression in which consecutive occurrences of the s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5012,
"level": 1,
"question": "Zara is a software developer who loves to work with strings. She is currently working on a project where she needs to compress a given string using Run-Length Encoding (RLE) technique. The Run-Length Encoding is a simple form of data compression in whi... |
def first_index(lst, target):
for i, val in enumerate(lst):
if val == target:
return i
return -1
print(first_index([1, 2, 3, 4, 5], 4)) | simplelr_Filter | [
{
"content": "Question:\ndef first_index(lst, target):\n for i, val in enumerate(lst):\n if val == target:\n return i\n return -1\nprint(first_index([1, 2, 3, 4, 5], 4))\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5013,
"level": 1,
"question": "def first_index(lst, target):\n for i, val in enumerate(lst):\n if val == target:\n return i\n return -1\nprint(first_index([1, 2, 3, 4, 5], 4))",
"split": "train"
} |
def ip_to_binary(ip):
octets = ip.split('.')
binary_octets = [format(int(octet), '08b') for octet in octets]
return '.'.join(binary_octets) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert an IP address from dot-decimal notation to binary Notation.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5014,
"level": 1,
"question": "Write a python function to convert an IP address from dot-decimal notation to binary Notation.",
"split": "train"
} |
def maxDifference(arr):
min_so_far = arr[0]
max_diff = 0
for num in arr[1:]:
if num > min_so_far:
current_diff = num - min_so_far
if current_diff > max_diff:
max_diff = current_diff
else:
min_so_far = num
return max_diff | simplelr_Evol | [
{
"content": "Question:\nYou are given a list of integers. Write a function that finds the largest difference between any two integers where the larger integer comes after the smaller integer in the list. If no such elements exist, return 0. Your solution should efficiently handle large lists.\n\n```python\ndef... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5015,
"level": 1,
"question": "You are given a list of integers. Write a function that finds the largest difference between any two integers where the larger integer comes after the smaller integer in the list. If no such elements exist, return 0. Your solution should efficiently ha... |
def count_frequency(numbers):
"""
Counts the frequency of each integer in a given list and returns the result as a dictionary.
Args:
numbers (list): A list of integers.
Returns:
dict: A dictionary where keys are the integers from the list and values are their respective frequencies.
... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a list of integers and returns a dictionary with the frequency of each number. Ensure the function is named `count_frequency` and is well-documented. Additionally, include a simple way to test the function using a provided list to verify its correctne... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5016,
"level": 1,
"question": "Create a Python function that takes a list of integers and returns a dictionary with the frequency of each number. Ensure the function is named `count_frequency` and is well-documented. Additionally, include a simple way to test the function using a pr... |
def reverse_first_n_elements(arr, n):
return arr[:n][::-1] + arr[n:] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse the first `n` elements of a list. The function should take two parameters: a list `arr` and an integer `n`. The function should return a new list where the first `n` elements are reversed, and the rest of the list remains unchanged.\nAnswer:\nLet's thi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5017,
"level": 1,
"question": "Write a python function to reverse the first `n` elements of a list. The function should take two parameters: a list `arr` and an integer `n`. The function should return a new list where the first `n` elements are reversed, and the rest of the list rem... |
def can_form_palindrome(s):
# Preprocess the string: keep only alphanumeric characters and convert to lowercase
processed = [c.lower() for c in s if c.isalnum()]
n = len(processed)
# Count the frequency of each character
from collections import Counter
counts = Counter(processed)
#... | simplelr_Package | [
{
"content": "Question:\n#### Context\nIn the context of computer science, a palindrome is a string that reads the same forward and backward. A more challenging variety of palindrome-related problems involves checking if a string can be re-arranged to form a palindrome. Your task is to write a function that det... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5018,
"level": 1,
"question": "#### Context\nIn the context of computer science, a palindrome is a string that reads the same forward and backward. A more challenging variety of palindrome-related problems involves checking if a string can be re-arranged to form a palindrome. Your t... |
def sanitize_input(input_string: str) -> str:
return input_string.replace("'", "''") | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nA database administrator needs to sanitize user-input data before storing it in the database to prevent SQL injection attacks. They decide to implement a simple escape mechanism that ensures any single quotes (`'`) in the user input are properly escaped by doubling them up... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5019,
"level": 1,
"question": "### Scenario\nA database administrator needs to sanitize user-input data before storing it in the database to prevent SQL injection attacks. They decide to implement a simple escape mechanism that ensures any single quotes (`'`) in the user input are p... |
from datetime import datetime
def get_overdue_tasks(tasks, current_date):
current_date_obj = datetime.strptime(current_date, "%Y-%m-%d")
overdue = []
for task in tasks:
due_date_str = task["due_date"]
due_date = datetime.strptime(due_date_str, "%Y-%m-%d")
if due_date < current_... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nYou are developing a web application that allows users to manage their tasks. As part of this application, you need to implement a feature that identifies all overdue tasks based on the current date.\n\n### Task\nWrite a function in Python that takes a list of tasks and the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5020,
"level": 1,
"question": "### Context\nYou are developing a web application that allows users to manage their tasks. As part of this application, you need to implement a feature that identifies all overdue tasks based on the current date.\n\n### Task\nWrite a function in Python... |
def calculate_total_price(orders):
return round(sum(order['quantity'] * order['price'] for order in orders), 2) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function named `calculate_total_price` that computes the total price for a list of product orders. Each order is represented as a dictionary with the keys `quantity` and `price`, indicating the number of items and the price per item, respectively. The function should ret... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5021,
"level": 1,
"question": "Create a Python function named `calculate_total_price` that computes the total price for a list of product orders. Each order is represented as a dictionary with the keys `quantity` and `price`, indicating the number of items and the price per item, re... |
def is_unique_within_set(s, allowed):
seen = set()
for c in s:
if c not in allowed:
return False
if c in seen:
return False
seen.add(c)
return True | simplelr_Filter | [
{
"content": "Question:\nGiven a string and a set of characters, write a program to determine if the string has all unique characters within the set. Additionally, ensure the string doesn't contain any character outside the set.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5022,
"level": 1,
"question": "Given a string and a set of characters, write a program to determine if the string has all unique characters within the set. Additionally, ensure the string doesn't contain any character outside the set.",
"split": "train"
} |
def some_magic_function(list1, list2):
seen = set()
result = []
for item in list1:
if item not in seen:
seen.add(item)
result.append(item)
for item in list2:
if item not in seen:
seen.add(item)
result.append(item)
return result | simplelr_Filter | [
{
"content": "Question:\nI have two Python lists, list1 and list2, and I want to create a new list that contains all the elements from both lists, without duplicates, and with each element appearing in the order they appeared in the original lists.\n\nHere's an example of what I'm trying to achieve:\n```python\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5023,
"level": 1,
"question": "I have two Python lists, list1 and list2, and I want to create a new list that contains all the elements from both lists, without duplicates, and with each element appearing in the order they appeared in the original lists.\n\nHere's an example of what... |
def longest_substring_with_k_distinct(s, k):
window_counts = {}
window_start = 0
max_length = 0
max_substring = ""
# Iterate through each character in the string with the end pointer
for end in range(len(s)):
current_char = s[end]
window_counts[current_char] = window_counts.... | simplelr_Filter | [
{
"content": "Question:\nGiven a string, write a method that finds the longest substring with at most K distinct characters. Here we want the longest substring that only contains at most K different characters.\n\nExample:\nInput: \"eceba\", K = 2\nOutput: \"ece\" or \"eba\"\n\nInput: \"aa\", K=1\nOutput: \"aa\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5024,
"level": 1,
"question": "Given a string, write a method that finds the longest substring with at most K distinct characters. Here we want the longest substring that only contains at most K different characters.\n\nExample:\nInput: \"eceba\", K = 2\nOutput: \"ece\" or \"eba\"\n... |
def delete_reoccurring_characters_optimized(string: str) -> str:
seen = set()
result = []
for char in string:
if char not in seen:
seen.add(char)
result.append(char)
return ''.join(result) | simplelr_Data_Structure | [
{
"content": "Question:\nGiven a string as input, write a function `delete_reoccurring_characters_optimized` that removes all reoccurring characters from the string and returns a new string containing only the unique characters in the order of their first occurrence.\n\n### Function Signature:\n```python\ndef d... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5025,
"level": 1,
"question": "Given a string as input, write a function `delete_reoccurring_characters_optimized` that removes all reoccurring characters from the string and returns a new string containing only the unique characters in the order of their first occurrence.\n\n### Fu... |
import os
def manage_env_and_large_file(env_vars: dict, large_file_path: str):
# Update environment variables
for var, value in env_vars.items():
try:
os.environ[var] = value
print(f'Environment variable {var} set to {value}')
except Exception as e:
print(f'E... | simplelr_Docs | [
{
"content": "Question:\n### Environment Variables and Large File Handling in Python\n\n**Objective:**\n\nDesign a function that demonstrates the manipulation of environment variables and the handling of large files using the `os` module in Python.\n\n**Task:**\n\n1. Create a function that accepts a dictionary ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5026,
"level": 1,
"question": "### Environment Variables and Large File Handling in Python\n\n**Objective:**\n\nDesign a function that demonstrates the manipulation of environment variables and the handling of large files using the `os` module in Python.\n\n**Task:**\n\n1. Create a ... |
def find_product_index(product_ids: list[int], target_id: int) -> int:
"""
Searches for the target_id in the list of product_ids.
Returns the index if found, otherwise returns -1.
Args:
product_ids (list[int]): A list of product IDs.
target_id (int): The target product ID to find.
... | simplelr_Data_Structure | [
{
"content": "Question:\n**Objective**: Demonstrate understanding of searching algorithms with an implementation that handles edge cases and optimizes performance within given constraints.\n\n### Scenario:\nImagine you are a software engineer at a company dealing with products in different categories. You are f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5027,
"level": 1,
"question": "**Objective**: Demonstrate understanding of searching algorithms with an implementation that handles edge cases and optimizes performance within given constraints.\n\n### Scenario:\nImagine you are a software engineer at a company dealing with products... |
def invert_case(s):
return s.swapcase()
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `invert_case` that takes a single string as input and returns a new string where the case of each letter is inverted. For example, all lowercase letters should become uppercase, and all uppercase letters should become lowercase. \n\nYour function should handle both alph... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5028,
"level": 1,
"question": "Write a function `invert_case` that takes a single string as input and returns a new string where the case of each letter is inverted. For example, all lowercase letters should become uppercase, and all uppercase letters should become lowercase. \n\nYo... |
def length_of_longest_subarray(arr):
if not arr:
return 0
max_len = 0
count = {}
left = 0
for right in range(len(arr)):
num = arr[right]
if num in count:
count[num] += 1
else:
count[num] = 1
# If there are more than two distinc... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `arr`. Find the **length of the longest subarray** that contains at most two distinct integers. If the array is empty, return 0. The subarray should be a contiguous segment of the array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5029,
"level": 1,
"question": "You are given an integer array `arr`. Find the **length of the longest subarray** that contains at most two distinct integers. If the array is empty, return 0. The subarray should be a contiguous segment of the array.",
"split": "train"
} |
def sanitize_url(url: str, params_to_strip: list = None) -> str:
if params_to_strip is None:
params_to_strip = []
parts = url.split('?', 1)
base = parts[0]
if len(parts) == 1:
return base
query = parts[1]
new_params = []
seen = set()
for param in query.spli... | simplelr_Data_Structure | [
{
"content": "Question:\nURL Query Parameter Stripping and Deduplication\n\nYou are working on a web analytics project and need to sanitize URLs by removing duplicate query parameters and optionally stripping out specified parameters. The task is to implement a function that achieves this in an efficient manner... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5030,
"level": 1,
"question": "URL Query Parameter Stripping and Deduplication\n\nYou are working on a web analytics project and need to sanitize URLs by removing duplicate query parameters and optionally stripping out specified parameters. The task is to implement a function that a... |
def num_distinct(s, t):
m = len(t)
n = len(s)
if m > n:
return 0
# Initialize DP table
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Base case: empty t can be formed in one way
for j in range(n + 1):
dp[0][j] = 1
for i in range(1, m + 1):
for j in ra... | simplelr_Filter | [
{
"content": "Question:\nGiven a string s and a string t, find the number of distinct subsequences of s which equals t. \n\nExample 1:\nInput: s = \"rabbbit\", t = \"rabbit\"\nOutput: 3\nExplanation:\nAs shown below, there are 3 ways you can generate \"rabbit\" from S.\n(1) rabbbit => rabbbit \n (p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5031,
"level": 1,
"question": "Given a string s and a string t, find the number of distinct subsequences of s which equals t. \n\nExample 1:\nInput: s = \"rabbbit\", t = \"rabbit\"\nOutput: 3\nExplanation:\nAs shown below, there are 3 ways you can generate \"rabbit\" from S.\n(1) ra... |
from typing import List, Tuple
def find_transaction_pairs(transactions: List[int], target: int) -> Tuple[int, int]:
seen = {}
for i, value in enumerate(transactions):
complement = target - value
if complement in seen:
return (seen[complement], i)
seen[value] = i
return N... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nYou have been hired by a fintech startup to develop a system that detects pairs of transactions adding up to a specific target value. This will help in underwriting processes where specific transaction pairs are required to validate operations.\n\n#### Task\nImplement the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5032,
"level": 1,
"question": "#### Scenario\nYou have been hired by a fintech startup to develop a system that detects pairs of transactions adding up to a specific target value. This will help in underwriting processes where specific transaction pairs are required to validate oper... |
def isSubsequence(s: str, t: str) -> bool:
i = j = 0
len_s, len_t = len(s), len(t)
if len_t > len_s:
return False
while i < len_s and j < len_t:
if s[i] == t[j]:
j += 1
i += 1
return j == len_t
| simplelr_Taco | [
{
"content": "Question:\nYou are given two strings, `s` and `t`, each containing only lowercase alphabetical characters. You need to determine if you can transform string `s` into string `t` by removing some characters from `s` without reordering the remaining characters. In other words, check if `t` is a subse... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5033,
"level": 1,
"question": "You are given two strings, `s` and `t`, each containing only lowercase alphabetical characters. You need to determine if you can transform string `s` into string `t` by removing some characters from `s` without reordering the remaining characters. In o... |
import math
def generate_pascals_triangle(n: int) -> list:
if n <= 0:
return []
triangle = []
for i in range(n):
row = [math.comb(i, j) for j in range(i + 1)]
triangle.append(row)
return triangle | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a non-negative integer `n` representing the number of rows of Pascal’s Triangle to generate, and returns the triangle as a list of lists.\n\nPascal's Triangle is a triangular array where the entries are binomial coefficients. That means:\n- The first and last... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5034,
"level": 1,
"question": "Write a function that takes a non-negative integer `n` representing the number of rows of Pascal’s Triangle to generate, and returns the triangle as a list of lists.\n\nPascal's Triangle is a triangular array where the entries are binomial coefficients... |
def find_first_last_occurrences(lst):
first_occurrence = {}
last_occurrence = {}
for index, num in enumerate(lst):
if num not in first_occurrence:
first_occurrence[num] = index
last_occurrence[num] = index
result = {num: (first_occurrence[num], last_occurrence[num]) for num i... | simplelr_Filter | [
{
"content": "Question:\nI have a collection of integers in a list. I want to find the first and last occurrence of each number in the list.\n\nExample Input: `[1, 2, 3, 2, 1]`\n\nExample Output:\n```\n1: (0, 4)\n2: (1, 3)\n3: (2, 2)\n```\nHow can I do this in Python?\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5035,
"level": 1,
"question": "I have a collection of integers in a list. I want to find the first and last occurrence of each number in the list.\n\nExample Input: `[1, 2, 3, 2, 1]`\n\nExample Output:\n```\n1: (0, 4)\n2: (1, 3)\n3: (2, 2)\n```\nHow can I do this in Python?",
"sp... |
def canPartition(nums):
total = sum(nums)
if total % 2 != 0:
return False
target = total // 2
dp = {0}
for num in nums:
for s in list(dp):
new_sum = s + num
if new_sum == target:
return True
if new_sum < target:
dp.a... | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers, you need to determine if it is possible to partition the array into exactly two subsets such that the sum of elements in both subsets is equal.\n\nWrite a function `canPartition(nums: List[int]) -> bool` that takes an array of integers `nums` and returns a bo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5036,
"level": 1,
"question": "Given an array of integers, you need to determine if it is possible to partition the array into exactly two subsets such that the sum of elements in both subsets is equal.\n\nWrite a function `canPartition(nums: List[int]) -> bool` that takes an array ... |
def categorize_comments(comments):
categorized = {
"Positive": [],
"Negative": [],
"Neutral": []
}
positive_keywords = {'good', 'great', 'excellent'}
negative_keywords = {'bad', 'terrible', 'awful'}
for comment in comments:
lower_comment = comment.lower()
... | simplelr_Package | [
{
"content": "Question:\nYou are developing a platform that requires analyzing user comments and categorizing them based on the presence of certain keywords. Write a function called `categorize_comments` in Python that processes a list of user comments and classifies each comment into predefined categories.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5037,
"level": 1,
"question": "You are developing a platform that requires analyzing user comments and categorizing them based on the presence of certain keywords. Write a function called `categorize_comments` in Python that processes a list of user comments and classifies each comm... |
def sum_of_squares(numbers):
"""
Calculate the sum of the squares of a list of numbers.
Args:
numbers (list): A list of integers or floats.
Returns:
int or float: The sum of the squares of the numbers in the list.
"""
return sum(x ** 2 for x in numbers) | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python function that calculates the sum of the squares of a list of numbers? I want to make sure it's efficient and works for any list of integers or floats.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5038,
"level": 1,
"question": "Can you help me with a Python function that calculates the sum of the squares of a list of numbers? I want to make sure it's efficient and works for any list of integers or floats.",
"split": "train"
} |
def prime_check(n: int) -> bool:
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0:
return False
# Write n-1 as d * 2^s
d = n - 1
s = 0
while d % 2 == 0:
d //= 2
s += 1
# Test for bases that are sufficient for n < 2^64
bases = ... | simplelr_Data_Structure | [
{
"content": "Question:\nPrime Check Performance Analysis\n\n#### Objective:\nTo assess your understanding of prime checking algorithms and your ability to enhance their efficiency.\n\n#### Problem Statement:\nYou are provided with a prime checking function using a common efficient algorithm. Based on its princ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5039,
"level": 1,
"question": "Prime Check Performance Analysis\n\n#### Objective:\nTo assess your understanding of prime checking algorithms and your ability to enhance their efficiency.\n\n#### Problem Statement:\nYou are provided with a prime checking function using a common effi... |
from collections import Counter
def can_form_palindrome(s):
counts = Counter(s)
odd_count = 0
for count in counts.values():
if count % 2 != 0:
odd_count += 1
if len(s) % 2 == 0:
return odd_count == 0
else:
return odd_count == 1 | simplelr_Apps | [
{
"content": "Question:\nGiven a string s, determine if it can be reordered to form a palindrome.\n\nA string is a palindrome if it reads the same forwards and backwards. For instance, \"racecar\" and \"madam\" are palindromes.\n\nYour task is to design an algorithm that checks if any permutation of the input s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5040,
"level": 1,
"question": "Given a string s, determine if it can be reordered to form a palindrome.\n\nA string is a palindrome if it reads the same forwards and backwards. For instance, \"racecar\" and \"madam\" are palindromes.\n\nYour task is to design an algorithm that check... |
from urllib.parse import urlparse
def get_domain_name(url):
# Ensure the URL has a scheme for proper parsing
if not url.startswith(('http://', 'https://')):
url = 'http://' + url
parsed_url = urlparse(url)
# Split the netloc to remove port if present
netloc = parsed_url.netloc
host... | simplelr_Filter | [
{
"content": "Question:\nI need to write a Python function that takes a URL and returns the domain name. For example, if the URL is \"https://www.example.com/path/to/page?query=123\", the function should return \"example.com\". How can I achieve this using Python?\nAnswer:\nLet's think step by step.\n",
"ro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5041,
"level": 1,
"question": "I need to write a Python function that takes a URL and returns the domain name. For example, if the URL is \"https://www.example.com/path/to/page?query=123\", the function should return \"example.com\". How can I achieve this using Python?",
"split":... |
def split_into_chunks(lst, chunk_size):
return [[lst[j] for j in range(i, min(i + chunk_size, len(lst)))] for i in range(0, len(lst), chunk_size)] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to split a list into chunks of a given size and return a list of chunks. However, you can only use list comprehension and no other built-in Python functions like 'split', 'slice', or 'chunks'.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5042,
"level": 1,
"question": "Write a Python function to split a list into chunks of a given size and return a list of chunks. However, you can only use list comprehension and no other built-in Python functions like 'split', 'slice', or 'chunks'.",
"split": "train"
} |
def maximum_product_of_three(nums):
sorted_nums = sorted(nums)
n = len(sorted_nums)
if n < 3:
raise ValueError("List must have at least three elements")
candidate1 = sorted_nums[-1] * sorted_nums[-2] * sorted_nums[-3]
candidate2 = sorted_nums[0] * sorted_nums[1] * sorted_nums[-1]
return ... | simplelr_Evol | [
{
"content": "Question:\nGiven a list of integers, find the maximum product of any three numbers. Write a function named `maximum_product_of_three` to achieve this. You cannot use any built-in functions that directly solve the problem.\n\n```python\ndef maximum_product_of_three(nums):\n # Your code here\n\n#... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5043,
"level": 1,
"question": "Given a list of integers, find the maximum product of any three numbers. Write a function named `maximum_product_of_three` to achieve this. You cannot use any built-in functions that directly solve the problem.\n\n```python\ndef maximum_product_of_thre... |
def max_non_overlapping_concerts(intervals):
# Sort intervals based on end time
sorted_intervals = sorted(intervals, key=lambda x: x[1])
current_end = float('-inf')
count = 0
for interval in sorted_intervals:
start, end = interval
if start >= current_end:
count += 1
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are tasked with organizing a series of concerts for a music festival. Each concert has a starting and ending time and is represented by an interval [start, end]. You are given a list of `n` intervals where each interval [start, end] represents a concert. Two concerts cannot be sched... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5044,
"level": 1,
"question": "You are tasked with organizing a series of concerts for a music festival. Each concert has a starting and ending time and is represented by an interval [start, end]. You are given a list of `n` intervals where each interval [start, end] represents a co... |
def write_to_file(file_name, content):
with open(file_name, 'w') as file:
file.write(content) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to write a file with a given string content.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5045,
"level": 1,
"question": "Write a python function to write a file with a given string content.",
"split": "train"
} |
def reverse_words_in_sentence(s):
return ' '.join(s.split()[::-1]) | simplelr_Apps | [
{
"content": "Question:\nDiana is learning to code, and she's practicing string manipulation. She wants to write a function that takes a string and reverses the words in it.\n\nWrite a program where Diana can input a sentence (string) and your function will return the words in the sentence reversed, but the ord... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5046,
"level": 1,
"question": "Diana is learning to code, and she's practicing string manipulation. She wants to write a function that takes a string and reverses the words in it.\n\nWrite a program where Diana can input a sentence (string) and your function will return the words in... |
def replace_cat_with_dog(s, t):
count = s.count('cat')
if count == t:
return s.replace('cat', 'dog')
else:
return s | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string `s` and an integer `t` as input and returns a modified version of `s`. The modification involves replacing each occurrence of the word \"cat\" with \"dog\" in the string `s`, but only if the word \"cat\" appears `t` times in the string `s`. If... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5047,
"level": 1,
"question": "Write a Python function that takes a string `s` and an integer `t` as input and returns a modified version of `s`. The modification involves replacing each occurrence of the word \"cat\" with \"dog\" in the string `s`, but only if the word \"cat\" appe... |
def count_vowels_consonants(s):
vowels_count = 0
consonants_count = 0
for char in s:
if char.isalpha():
lower_char = char.lower()
if lower_char in {'a', 'e', 'i', 'o', 'u'}:
vowels_count += 1
else:
consonants_count += 1
return f... | simplelr_Apps | [
{
"content": "Question:\nWrite a function called `count_vowels_consonants` that takes a string as an argument and returns a formatted string that specifies the number of vowels and consonants in the input string. For this task, vowels are considered to be 'a', 'e', 'i', 'o', 'u' (both uppercase and lowercase), ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5048,
"level": 1,
"question": "Write a function called `count_vowels_consonants` that takes a string as an argument and returns a formatted string that specifies the number of vowels and consonants in the input string. For this task, vowels are considered to be 'a', 'e', 'i', 'o', '... |
def stutter_stack(stack: list) -> list:
return [x for x in stack for _ in range(2)] | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem: Stack Element Duplicator\n\nYou are given a stack of integers. Your task is to create a function `stutter_stack` that takes this stack as an input and modifies it such that every original element in the stack is replaced with two consecutive occurrences of that element, pre... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5049,
"level": 1,
"question": "### Problem: Stack Element Duplicator\n\nYou are given a stack of integers. Your task is to create a function `stutter_stack` that takes this stack as an input and modifies it such that every original element in the stack is replaced with two consecuti... |
def has_unique_chars(s):
for i in range(len(s)):
for j in range(i + 1, len(s)):
if s[i] == s[j]:
return False
return True
| simplelr_Taco | [
{
"content": "Question:\nCreate a function that determines if a string has all unique characters. The function should take a single string as input and return a boolean value indicating whether all characters in the string are unique. The function should be case-sensitive, meaning 'A' and 'a' are considered dif... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5050,
"level": 1,
"question": "Create a function that determines if a string has all unique characters. The function should take a single string as input and return a boolean value indicating whether all characters in the string are unique. The function should be case-sensitive, mea... |
def third_highest_number(nums):
unique = list(set(nums))
unique.sort(reverse=True)
if len(unique) >= 3:
return unique[2]
else:
return None | simplelr_Filter | [
{
"content": "Question:\nWrite a code snippet that finds the 3rd highest number in the given list. If such a number exists, return it. Otherwise, return None.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5051,
"level": 1,
"question": "Write a code snippet that finds the 3rd highest number in the given list. If such a number exists, return it. Otherwise, return None.",
"split": "train"
} |
def findPairs(nums, target):
pairs = set()
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
a, b = sorted((nums[i], nums[j]))
pairs.add((a, b))
sorted_pairs = sorted(pairs)
return sorted_pairs
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers nums and an integer target, find all unique pairs of elements from the array whose sum is equal to the target. Return the pairs in lexicographical order.\n\nExample 1:\nInput: nums = [1, 2, 3, 4, 5], target = 5\nOutput: [(1, 4), (2, 3)]\nExplanation: Pairs (1,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5052,
"level": 1,
"question": "Given an array of integers nums and an integer target, find all unique pairs of elements from the array whose sum is equal to the target. Return the pairs in lexicographical order.\n\nExample 1:\nInput: nums = [1, 2, 3, 4, 5], target = 5\nOutput: [(1, ... |
from collections import Counter
from typing import List
def sum_of_unique_elements(lst: List[int]) -> int:
counts = Counter(lst)
total = 0
for num, count in counts.items():
if count == 1:
total += num
return total | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of Unique Elements in a List\n\nYou are given a list of integers. Write a function that returns the sum of all unique elements in the list. An element is considered unique if it appears exactly once in the list.\n\n#### Function Signature\n```python\ndef sum_of_unique_elements(l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5053,
"level": 1,
"question": "### Sum of Unique Elements in a List\n\nYou are given a list of integers. Write a function that returns the sum of all unique elements in the list. An element is considered unique if it appears exactly once in the list.\n\n#### Function Signature\n```p... |
def single_number(arr):
res = 0
for num in arr:
res ^= num
return res | simplelr_Apps | [
{
"content": "Question:\n## Description\n\nYou are given an unsorted array of integers where each element appears exactly twice, except for one element which appears exactly once. Your task is to find that single element in linear time complexity and without using extra memory.\n\n**Examples**\n```\nsingle_numb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5054,
"level": 1,
"question": "## Description\n\nYou are given an unsorted array of integers where each element appears exactly twice, except for one element which appears exactly once. Your task is to find that single element in linear time complexity and without using extra memory... |
def power(base_number, exp_number):
if exp_number == 0:
return 1
elif exp_number < 0:
return 1 / power(base_number, -exp_number)
else:
return base_number * power(base_number, exp_number - 1) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the power of a number to another number using recursion. The function should take two parameters: the base (base_number) and the exponent (exp_number). The function should return the power of base_number raised to exp_number.\nAnswer:\nLet's think step by s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5055,
"level": 1,
"question": "Write a function to calculate the power of a number to another number using recursion. The function should take two parameters: the base (base_number) and the exponent (exp_number). The function should return the power of base_number raised to exp_numb... |
def max_sum_subarray(nums, k):
if k == 0:
return 0
n = len(nums)
if k > n:
return 0 # As per problem constraints, this should not happen
current_sum = sum(nums[:k])
max_sum = current_sum
for i in range(k, n):
current_sum = current_sum - nums[i - k] + nums[i]
if c... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array `nums` of size `n`, return _the maximum sum of any contiguous subarray of length `k`_. If there is no subarray of length `k`, return `0`. The input length will satisfy \\(1 \\leq k \\leq n \\leq 10^5\\) and \\(-10^4 \\leq nums[i] \\leq 10^4\\) for \\(0 \\leq i < n\\).\nAn... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5056,
"level": 1,
"question": "Given an array `nums` of size `n`, return _the maximum sum of any contiguous subarray of length `k`_. If there is no subarray of length `k`, return `0`. The input length will satisfy \\(1 \\leq k \\leq n \\leq 10^5\\) and \\(-10^4 \\leq nums[i] \\leq 1... |
from collections import defaultdict
def get_skyline(buildings: list[list[int]]) -> list[list[int]]:
if not buildings:
return []
# Generate events for each building
events = []
for L, R, H in buildings:
events.append((L, 1, H)) # Start event
events.append((R, 0, H)) # En... | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem: Compute the Skyline\n\nA city's skyline is the outer contour of the silhouette formed by a collection of buildings when viewed from a distance. You are provided with the locations and heights of various buildings in a cityscape and asked to compute the skyline formed by the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5057,
"level": 1,
"question": "### Problem: Compute the Skyline\n\nA city's skyline is the outer contour of the silhouette formed by a collection of buildings when viewed from a distance. You are provided with the locations and heights of various buildings in a cityscape and asked t... |
from typing import List, Tuple
from collections import Counter
def top_n_purchased_items(transactions: List[Tuple[int, int]], N: int) -> List[int]:
frequency_counter = Counter()
for item_id, quantity in transactions:
frequency_counter[item_id] += quantity
items = list(frequency_counter.items()... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\nYou are designing a program to help analyze patterns in a list of transactions. Each transaction contains an item ID and its purchased quantity. Your goal is to implement a function that identifies the top N most frequently purchased items.\n\n### Function Defini... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5058,
"level": 1,
"question": "### Problem Statement:\nYou are designing a program to help analyze patterns in a list of transactions. Each transaction contains an item ID and its purchased quantity. Your goal is to implement a function that identifies the top N most frequently purc... |
import pandas as pd
def read_csv_to_dataframe(file_path):
"""
Reads a CSV file and returns its contents as a pandas DataFrame.
Args:
file_path (str): The path to the CSV file.
Returns:
pd.DataFrame: A DataFrame containing the data from the CSV file.
None: If there's an error r... | simplelr_Filter | [
{
"content": "Question:\nI am trying to create a function in Python that can read a CSV file and store it into a pandas DataFrame. Could you help me with a code snippet to accomplish this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5059,
"level": 1,
"question": "I am trying to create a function in Python that can read a CSV file and store it into a pandas DataFrame. Could you help me with a code snippet to accomplish this?",
"split": "train"
} |
def alongSightline(heights):
if not heights:
return []
max_left = float('-inf')
max_right = float('-inf')
visible = set()
# Iterate from the left
for i in range(len(heights)):
if heights[i] > max_left:
max_left = heights[i]
visible.add(i)
# I... | simplelr_Filter | [
{
"content": "Question:\nWe are given an array of integers, where each integer represents the height of a building in an array of buildings. We want to write a function `alongSightline` that takes this array of heights and returns an array of the indices of the buildings that can be seen when looking from the l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5060,
"level": 1,
"question": "We are given an array of integers, where each integer represents the height of a building in an array of buildings. We want to write a function `alongSightline` that takes this array of heights and returns an array of the indices of the buildings that ... |
def decimal_to_binary(n):
if n == 0:
return '0'
remainder = n % 2
quotient = n // 2
if quotient == 0:
return str(remainder)
else:
return decimal_to_binary(quotient) + str(remainder) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to convert a decimal number to its binary representation using recursion. The function should take a single integer as input and return a string representing the binary equivalent of the given number. Ensure your function handles the edge case where the input is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5061,
"level": 1,
"question": "Write a Python function to convert a decimal number to its binary representation using recursion. The function should take a single integer as input and return a string representing the binary equivalent of the given number. Ensure your function handle... |
def calculate_whitespace_percentage(image, threshold):
white_count = 0
total_pixels = 0
for row in image:
for pixel in row:
total_pixels += 1
if pixel > threshold:
white_count += 1
return (white_count / total_pixels) * 100 | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario:\nYou are developing a feature for an image processing software that helps users quickly determine the amount of \"whitespace\" in an image. For simplicity, we define \"whitespace\" as any pixel with a grayscale value above a certain threshold.\n\nWrite a function that calc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5062,
"level": 1,
"question": "### Scenario:\nYou are developing a feature for an image processing software that helps users quickly determine the amount of \"whitespace\" in an image. For simplicity, we define \"whitespace\" as any pixel with a grayscale value above a certain thres... |
def count_rectangles(n, m):
return (n * (n + 1) // 2) * (m * (m + 1) // 2)
| simplelr_Taco | [
{
"content": "Question:\nYou are given a rectangle of size `n x m` that is made up of `1 x 1` unit squares. Your task is to calculate the number of distinct rectangles (including squares) that can be formed within the `n x m` rectangle.\n\nImplement the function `count_rectangles(n, m)` that takes in two intege... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5063,
"level": 1,
"question": "You are given a rectangle of size `n x m` that is made up of `1 x 1` unit squares. Your task is to calculate the number of distinct rectangles (including squares) that can be formed within the `n x m` rectangle.\n\nImplement the function `count_rectang... |
def most_frequent_element(lst):
if not lst:
return None
freq = {}
for item in lst:
freq[item] = freq.get(item, 0) + 1
max_count = max(freq.values())
candidates = [k for k, v in freq.items() if v == max_count]
return min(candidates) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the element that occurs most frequently in a given list. If there are multiple elements with the same maximum frequency, return the smallest one. If the list is empty, return None.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5064,
"level": 1,
"question": "Write a python function to find the element that occurs most frequently in a given list. If there are multiple elements with the same maximum frequency, return the smallest one. If the list is empty, return None.",
"split": "train"
} |
def sort_odd_even(nums):
odds = []
evens = []
for num in nums:
if num % 2 == 1:
odds.append(num)
else:
evens.append(num)
return odds + evens | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of integers `nums`, your task is to sort the list such that all the odd numbers appear before all the even numbers while maintaining their relative order within their respective groups. For example, given the list `[3, 1, 2, 4]`, the sorted list should be `[3, 1, 2, 4]` sin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5065,
"level": 1,
"question": "Given a list of integers `nums`, your task is to sort the list such that all the odd numbers appear before all the even numbers while maintaining their relative order within their respective groups. For example, given the list `[3, 1, 2, 4]`, the sorte... |
def longest_word(words):
longest = words[0]
for word in words[1:]:
if len(word) > len(longest):
longest = word
return longest | simplelr_Apps | [
{
"content": "Question:\nYou have been given a list of words. Your task is to write a function that returns the longest word from the list. If there are multiple words with the same length, return the one that appears first.\n\nExamples:\n``` python\nlongest_word([\"apple\", \"banana\", \"cherry\", \"date\"]) =... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5066,
"level": 1,
"question": "You have been given a list of words. Your task is to write a function that returns the longest word from the list. If there are multiple words with the same length, return the one that appears first.\n\nExamples:\n``` python\nlongest_word([\"apple\", \... |
def findMaxConsecutiveOnes(nums):
left = 0
max_len = 0
zero_count = 0
for right in range(len(nums)):
if nums[right] == 0:
zero_count += 1
while zero_count > 1:
if nums[left] == 0:
zero_count -= 1
left += 1
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a binary array `nums`, you are allowed to flip at most one `0` to `1`. Return the maximum length of a contiguous subarray that contains only `1`s after performing the flip. If the array consists entirely of `1`s, return the length of the entire array.\nAnswer:\nLet's think step by... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5067,
"level": 1,
"question": "Given a binary array `nums`, you are allowed to flip at most one `0` to `1`. Return the maximum length of a contiguous subarray that contains only `1`s after performing the flip. If the array consists entirely of `1`s, return the length of the entire a... |
from collections import Counter
def count_string_frequencies(string_list):
return dict(Counter(string_list)) | simplelr_Filter | [
{
"content": "Question:\nI need to create a Python function that can take a list of strings and return a dictionary mapping each unique string to its frequency count. How can I do this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5068,
"level": 1,
"question": "I need to create a Python function that can take a list of strings and return a dictionary mapping each unique string to its frequency count. How can I do this?",
"split": "train"
} |
from collections import Counter
def findSubstring(s, words):
if not words:
return []
total_length = sum(len(word) for word in words)
if total_length == 0 or len(s) < total_length:
return []
word_counts = Counter(words)
target = Counter()
for word in words:
for c in ... | simplelr_Evol | [
{
"content": "Question:\nGiven a string s and a list of words, return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.\n\nExample 1:\nInput: s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]\nOutput: [0,9]\nExplanati... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5069,
"level": 1,
"question": "Given a string s and a list of words, return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.\n\nExample 1:\nInput: s = \"barfoothefoobarman\", words = [\"foo\"... |
def rotate_matrix(matrix: list[list[int]]) -> list[list[int]]:
return [list(row[::-1]) for row in zip(*matrix)] | simplelr_Algorithm | [
{
"content": "Question:\n### Matrix Rotation\n\n**Context**: You are tasked with rotating a square 2D matrix by 90 degrees in a clockwise direction. The input matrix will always be a square, meaning it will have the same number of rows and columns.\n\n**Task**: Write a function `rotate_matrix(matrix: list[list[... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5070,
"level": 1,
"question": "### Matrix Rotation\n\n**Context**: You are tasked with rotating a square 2D matrix by 90 degrees in a clockwise direction. The input matrix will always be a square, meaning it will have the same number of rows and columns.\n\n**Task**: Write a functio... |
def increment_list(lst):
return [x + 1 for x in lst] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns a new list with each element incremented by 1. For example, given the input list `[1, 2, 3]`, the function should return `[2, 3, 4]`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5071,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns a new list with each element incremented by 1. For example, given the input list `[1, 2, 3]`, the function should return `[2, 3, 4]`.",
"split": "train"
} |
def sum_of_elements(arr):
return sum(arr) | simplelr_Filter | [
{
"content": "Question:\nHow do you create a function in Python that calculates the sum of elements in an array of integers?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5072,
"level": 1,
"question": "How do you create a function in Python that calculates the sum of elements in an array of integers?",
"split": "train"
} |
def sumOfSubmatrix(matrix, r1, c1, r2, c2):
total = 0
for r in range(r1, r2 + 1):
total += sum(matrix[r][c1:c2 + 1])
return total
| simplelr_Taco | [
{
"content": "Question:\nGiven a matrix of size N x M, with each cell containing an integer, the task is to find the sum of all elements in any submatrix within the given matrix. The submatrix is defined by its top-left corner (r1, c1) and bottom-right corner (r2, c2).\n\nExample 1:\nInput:\nmatrix: [\n [1, 2,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5073,
"level": 1,
"question": "Given a matrix of size N x M, with each cell containing an integer, the task is to find the sum of all elements in any submatrix within the given matrix. The submatrix is defined by its top-left corner (r1, c1) and bottom-right corner (r2, c2).\n\nExam... |
def generate_even_numbers(n):
return [2 * i for i in range(n)] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that generates and returns a list of the first N even numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5074,
"level": 1,
"question": "Create a function that generates and returns a list of the first N even numbers.",
"split": "train"
} |
def euclidean_distance(point1, point2):
# Check if both points are tuples
if not isinstance(point1, tuple) or not isinstance(point2, tuple):
raise TypeError("Both points must be tuples.")
# Check if each point has exactly two coordinates
if len(point1) != 2 or len(point2) != 2:
rais... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that can calculate the Euclidean distance between two points in 2D space. The points are provided as tuples of coordinates (x, y). Ensure to check the validity of the input before performing any calculation.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5075,
"level": 1,
"question": "Create a function that can calculate the Euclidean distance between two points in 2D space. The points are provided as tuples of coordinates (x, y). Ensure to check the validity of the input before performing any calculation.",
"split": "train"
} |
import importlib
import importlib.metadata as metadata
import modulefinder
def import_module_and_analyze(script_path: str, module_name: str) -> None:
# Retrieve module version
try:
version = metadata.version(module_name)
except (metadata.PackageNotFoundError, ValueError):
version = '0.0.0'
... | simplelr_Docs | [
{
"content": "Question:\n### Question: Dynamic Importing and Metadata Extraction in Python\n\n**Objective**: This question assesses your ability to dynamically import and manipulate Python modules, and to work with package metadata.\n\n**Background**:\nYou are tasked with creating a utility function that:\n1. D... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5076,
"level": 1,
"question": "### Question: Dynamic Importing and Metadata Extraction in Python\n\n**Objective**: This question assesses your ability to dynamically import and manipulate Python modules, and to work with package metadata.\n\n**Background**:\nYou are tasked with crea... |
def delete_substring(main_str, sub_str, count):
return main_str.replace(sub_str, '', count) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to delete a substring from a string. The function should take three parameters: the main string, the substring to be deleted, and the number of times the substring should be deleted. If the substring appears less than the specified number of times, the function s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5077,
"level": 1,
"question": "Write a Python function to delete a substring from a string. The function should take three parameters: the main string, the substring to be deleted, and the number of times the substring should be deleted. If the substring appears less than the specif... |
def is_armstrong_number(n):
if n < 0:
return False
s = str(n)
num_digits = len(s)
total = 0
for ch in s:
digit = int(ch)
total += digit ** num_digits
return total == n | simplelr_Filter | [
{
"content": "Question:\nIs there a way to create a Python function that can determine if a number is an Armstrong number? An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5078,
"level": 1,
"question": "Is there a way to create a Python function that can determine if a number is an Armstrong number? An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstr... |
import re
def extract_emails(text):
pattern = r'\b[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9.-]+\.)+[A-Za-z]{2,}\b'
regex = re.compile(pattern, flags=re.IGNORECASE)
emails = regex.findall(text)
return emails | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python function to extract and return a list of email addresses from a given text?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5079,
"level": 1,
"question": "Can you help me with a Python function to extract and return a list of email addresses from a given text?",
"split": "train"
} |
def manipulate_bytearray(init_string: str, resize_length: int, concat_string: str) -> str:
# Step 1: Create a bytearray from the initial string
b1 = bytearray(init_string, 'utf-8')
# Step 2: Resize the bytearray
current_length = len(b1)
if resize_length > current_length:
# Extend with z... | simplelr_Docs | [
{
"content": "Question:\n### Bytearray Manipulation Challenge\n\nIn this task, you will create and manipulate bytearrays using the Python C-API functions as described. The goal is to implement a function that performs the following steps:\n\n1. **Create** a bytearray from a given string.\n2. **Resize** the newl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5080,
"level": 1,
"question": "### Bytearray Manipulation Challenge\n\nIn this task, you will create and manipulate bytearrays using the Python C-API functions as described. The goal is to implement a function that performs the following steps:\n\n1. **Create** a bytearray from a gi... |
from collections import Counter
def can_form_word(word, characters):
word_counts = Counter(word)
available_counts = Counter(characters)
for char, count in word_counts.items():
if available_counts.get(char, 0) < count:
return False
return True | simplelr_Apps | [
{
"content": "Question:\nDevelop a function to evaluate if a word can be formed using characters from a list of available characters. Your function should meet these requirements:\n\n+ Accepts a string representing the word to be formed and a list of individual characters available.\n+ Returns a boolean value i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5081,
"level": 1,
"question": "Develop a function to evaluate if a word can be formed using characters from a list of available characters. Your function should meet these requirements:\n\n+ Accepts a string representing the word to be formed and a list of individual characters avai... |
def unique_elements(list1, list2):
return list(set(list1 + list2)) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes two lists of integers as input and returns a new list that contains all the unique elements from both input lists.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5082,
"level": 1,
"question": "Write a Python function that takes two lists of integers as input and returns a new list that contains all the unique elements from both input lists.",
"split": "train"
} |
import heapq
from typing import Dict
def dijkstra_shortest_path(graph: Dict[str, Dict[str, int]], start: str) -> Dict[str, int]:
# Initialize the distances dictionary with infinity for all nodes except the start node
distances = {node: float('infinity') for node in graph}
distances[start] = 0
# Priori... | simplelr_Package | [
{
"content": "Question:\n**Context:**\n\nGraphs are essential data structures in computer science, often used to represent networks, relationships, or pathways between elements. A common problem when dealing with graphs is finding the shortest path from one node to another. A popular algorithm for this is Dijks... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5083,
"level": 1,
"question": "**Context:**\n\nGraphs are essential data structures in computer science, often used to represent networks, relationships, or pathways between elements. A common problem when dealing with graphs is finding the shortest path from one node to another. A ... |
def string_lengths(strings_list):
result = {}
for string in strings_list:
if string not in result:
result[string] = len(string)
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of strings and returns a dictionary where each key is a string from the list and the corresponding value is the length of that string. If the list contains duplicate strings, the dictionary should store the length of the string only once, associ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5084,
"level": 1,
"question": "Write a Python function that takes a list of strings and returns a dictionary where each key is a string from the list and the corresponding value is the length of that string. If the list contains duplicate strings, the dictionary should store the len... |
def is_palindrome(n):
s = str(n)
return s == s[::-1] | simplelr_Filter | [
{
"content": "Question:\nIs there a function in Python to determine if a given number is a palindrome? If so, what is it, and if not, how can I write one?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5085,
"level": 1,
"question": "Is there a function in Python to determine if a given number is a palindrome? If so, what is it, and if not, how can I write one?",
"split": "train"
} |
def search_in_a_sorted_matrix(matrix, key):
"""
:param matrix: List of Lists of integers, where each row and each column is sorted in non-decreasing order
:param key: Integer, the value to search for within the matrix
:return: Tuple of (row, column) if the key is found or (-1, -1) if the key is not foun... | simplelr_Data_Structure | [
{
"content": "Question:\n## Coding Assessment Question:\n\n### Scenario:\nYou are working on a large dataset embedded in an application that allows users to search for specific values efficiently. The data is stored in a 2D matrix, where each row and each column is sorted in non-decreasing order. Your task is t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5086,
"level": 1,
"question": "## Coding Assessment Question:\n\n### Scenario:\nYou are working on a large dataset embedded in an application that allows users to search for specific values efficiently. The data is stored in a 2D matrix, where each row and each column is sorted in n... |
def count_vowels(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
return sum(1 for char in s if char.lower() in vowels) | simplelr_Filter | [
{
"content": "Question:\nObjective: To write a Python program that takes a string as input and returns the number of vowels in the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5087,
"level": 1,
"question": "Objective: To write a Python program that takes a string as input and returns the number of vowels in the string.",
"split": "train"
} |
import re
from collections import OrderedDict
def count_word_frequency(filename):
stop_words = {
'a', 'an', 'the', 'and', 'or', 'but', 'is', 'in', 'it', 'of', 'for', 'with',
'on', 'at', 'by', 'from', 'to', 'be', 'not', 'have', 'this', 'that', 'these',
'those', 'they', 'them', 'their', 'ther... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that reads the text content from a file and counts the frequency of each word in the file. The program should ignore case (i.e., 'The' and 'the' should be considered the same word) and should exclude common English stop words such as 'and', 'the', 'is', etc. The o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5088,
"level": 1,
"question": "Write a Python program that reads the text content from a file and counts the frequency of each word in the file. The program should ignore case (i.e., 'The' and 'the' should be considered the same word) and should exclude common English stop words suc... |
import math
def euclidean_distance(point1, point2):
x1, y1 = point1
x2, y2 = point2
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) | simplelr_Filter | [
{
"content": "Question:\nI need help with a Python function to calculate the Euclidean distance between two points in a 2D space. Could you provide a sample code?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5089,
"level": 1,
"question": "I need help with a Python function to calculate the Euclidean distance between two points in a 2D space. Could you provide a sample code?",
"split": "train"
} |
def has_path(n, edges, start, end):
"""
Determine if there exists a path between two nodes using Depth-First Search (DFS) algorithm.
:param n: An integer representing the number of nodes.
:param edges: A list of tuples (u, v), where 'u' is the starting node, and 'v' is the ending node of a directed edg... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nImplement a function in Python that uses the Depth-First Search (DFS) algorithm to determine if there exists a path between two nodes in a directed graph. If a path exists, return True, otherwise return False.\n\n### Function Signature\n```python\ndef has_path(n, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5090,
"level": 1,
"question": "### Problem Statement\nImplement a function in Python that uses the Depth-First Search (DFS) algorithm to determine if there exists a path between two nodes in a directed graph. If a path exists, return True, otherwise return False.\n\n### Function Sig... |
from typing import List
def can_schedule_meeting(existing_meetings: List[List[int]], new_meeting: List[int]) -> bool:
new_start, new_end = new_meeting[0], new_meeting[1]
for meeting in existing_meetings:
ex_start, ex_end = meeting
if new_start < ex_end and new_end > ex_start:
return... | simplelr_Algorithm | [
{
"content": "Question:\n### Python Data Structure Challenge\n\n**Context**: You've been hired to develop a simple scheduling algorithm for a company's meeting rooms. The company has multiple meeting rooms, and meetings can have different start and end times. The goal is to check if a new meeting can be schedul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5091,
"level": 1,
"question": "### Python Data Structure Challenge\n\n**Context**: You've been hired to develop a simple scheduling algorithm for a company's meeting rooms. The company has multiple meeting rooms, and meetings can have different start and end times. The goal is to ch... |
def is_valid_string(string, case_insensitive=False):
"""
Checks if a string is valid, containing only lowercase letters, underscores, and optionally uppercase letters if case-insensitive.
Args:
string: The string to be checked.
case_insensitive: Optional parameter to allow uppercase let... | simplelr_Filter | [
{
"content": "Question:\nThis is the second problem, please solve this one:\n\n**(a) Suppose you have a string where each character can be either a lowercase letter (a-z) or an underscore (_).\n\nFor example: \"this_is_a_string\"\n\nWrite a function Python function called is_valid_string that takes a string as ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5092,
"level": 1,
"question": "This is the second problem, please solve this one:\n\n**(a) Suppose you have a string where each character can be either a lowercase letter (a-z) or an underscore (_).\n\nFor example: \"this_is_a_string\"\n\nWrite a function Python function called is_v... |
def find_unique_numbers(nums):
count_dict = {}
for num in nums:
count_dict[num] = count_dict.get(num, 0) + 1
unique_nums = [num for num, count in count_dict.items() if count == 1]
unique_nums.sort()
return unique_nums | simplelr_Evol | [
{
"content": "Question:\n小明有一個整數列表,其中包含了若干個重複的數字。請設計一個函數來篩選出列表中只出現過一次的數字(獨特的數字),並以升序排列後返回這些數字的列表。\n\n示例輸入:\nlists = [4, 5, 7, 5, 8, 9, 7, 4, 10]\n\n預期輸出:\n[8, 9, 10]\n\n提示:\n1. 你可以使用字典來追蹤每個數字出現的次數。\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5093,
"level": 1,
"question": "小明有一個整數列表,其中包含了若干個重複的數字。請設計一個函數來篩選出列表中只出現過一次的數字(獨特的數字),並以升序排列後返回這些數字的列表。\n\n示例輸入:\nlists = [4, 5, 7, 5, 8, 9, 7, 4, 10]\n\n預期輸出:\n[8, 9, 10]\n\n提示:\n1. 你可以使用字典來追蹤每個數字出現的次數。",
"split": "train"
} |
def find_min_and_index(lst):
if not lst:
return None
min_value = lst[0]
min_index = 0
for i in range(1, len(lst)):
if lst[i] < min_value:
min_value = lst[i]
min_index = i
return (min_value, min_index) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the minimum integer in a list and its index. The function should return a tuple containing the minimum integer and its index. If the list is empty, return None. The function should also handle lists with duplicate minimum values and return the first occur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5094,
"level": 1,
"question": "Write a python function to find the minimum integer in a list and its index. The function should return a tuple containing the minimum integer and its index. If the list is empty, return None. The function should also handle lists with duplicate minimu... |
def floyd_warshall(adj_matrix):
n = len(adj_matrix)
# Initialize the distance matrix with a copy of the adjacency matrix
dist = [row[:] for row in adj_matrix]
for k in range(n):
for i in range(n):
for j in range(n):
# If the path from i to j through k is shorter, upda... | simplelr_Filter | [
{
"content": "Question:\nCould you provide a Python function that calculates the shortest path between two nodes in a weighted graph using the Floyd-Warshall algorithm? The function should take as input an adjacency matrix representing the graph and return a matrix that shows the shortest path distances between... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5095,
"level": 1,
"question": "Could you provide a Python function that calculates the shortest path between two nodes in a weighted graph using the Floyd-Warshall algorithm? The function should take as input an adjacency matrix representing the graph and return a matrix that shows ... |
def length_of_lis(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers and returns the length of the longest increasing subsequence (LIS) in that array. The LIS is the longest increasing subsequence in an array where the elements are in strictly increasing order. For example, the LIS in the array [10, 9, 2,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5096,
"level": 1,
"question": "Create a function that takes an array of integers and returns the length of the longest increasing subsequence (LIS) in that array. The LIS is the longest increasing subsequence in an array where the elements are in strictly increasing order. For examp... |
def sum_of_minimums(arr):
n = len(arr)
total = 0
for i in range(n):
min_val = arr[i]
total += min_val
for j in range(i + 1, n):
if arr[j] < min_val:
min_val = arr[j]
total += min_val
return total
# Example usage:
# arr = [3, 1, 2, 4]
# pri... | simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers arr, find the sum of the minimum value of each subarray of arr.\n\nExample 1:\nInput: arr = [3,1,2,4]\nOutput: 17\nExplanation: \nSubarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5097,
"level": 1,
"question": "Given an array of integers arr, find the sum of the minimum value of each subarray of arr.\n\nExample 1:\nInput: arr = [3,1,2,4]\nOutput: 17\nExplanation: \nSubarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums ... |
from typing import List
def can_form_triangle(arr: List[int]) -> str:
arr.sort()
for i in range(len(arr) - 2):
if arr[i] + arr[i+1] > arr[i+2]:
return "YES"
return "NO"
| simplelr_Taco | [
{
"content": "Question:\nGiven an unsorted integer array, determine whether there are any three numbers in the array that can form a triangle. A triangle can be formed if and only if the sum of any two sides is greater than the remaining side for all three combinations of the three sides. Return \"YES\" if such... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5098,
"level": 1,
"question": "Given an unsorted integer array, determine whether there are any three numbers in the array that can form a triangle. A triangle can be formed if and only if the sum of any two sides is greater than the remaining side for all three combinations of the ... |
from typing import List
def can_partition(nums: List[int]) -> bool:
total_sum = sum(nums)
if total_sum % 2 != 0:
return False
target = total_sum // 2
sum_neg = sum(x for x in nums if x <= 0)
sum_pos = sum(x for x in nums if x > 0)
if target < sum_neg or target > sum_pos:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge\n\nIn competitive programming, it's often useful to quickly determine if an array can be segmented into two subarrays with equal sums. Your task is to implement an efficient solution that checks if a given array meets this criteria.\n\n#### Objective\nYou need to cr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5099,
"level": 1,
"question": "### Coding Challenge\n\nIn competitive programming, it's often useful to quickly determine if an array can be segmented into two subarrays with equal sums. Your task is to implement an efficient solution that checks if a given array meets this criteria... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.