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 process_boolean_list(input_list: list) -> dict:
counts = {True: 0, False: 0}
for x in input_list:
b = bool(x)
counts[b] += 1
return counts
| simplelr_Docs | [
{
"content": "Question:\n### Question\n\nWrite a function `process_boolean_list(input_list)` that takes a list of boolean values and integers as input and returns a dictionary with the count of `True` and `False` values. The function should handle integers by converting them to their boolean equivalents. For th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1000,
"level": 1,
"question": "### Question\n\nWrite a function `process_boolean_list(input_list)` that takes a list of boolean values and integers as input and returns a dictionary with the count of `True` and `False` values. The function should handle integers by converting them t... |
def first_k_elements(lst, k):
if k < 0:
return []
else:
return lst[:k] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list `lst` and an integer `k`. The function should return a list containing the first `k` elements of the input list `lst`. If `k` is greater than the length of the list, return the entire list. If `k` is negative, return an empty list.\nAnswer:\nLet's thi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1001,
"level": 1,
"question": "Create a function that takes a list `lst` and an integer `k`. The function should return a list containing the first `k` elements of the input list `lst`. If `k` is greater than the length of the list, return the entire list. If `k` is negative, return... |
def find_missing_number(nums: list[int]) -> int:
n = len(nums) + 1
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Task: Finding the Missing Number in a Consecutive Sequence\n\nGiven an unsorted list of distinct integers in the range from 1 to \\( n \\) (inclusive), with exactly one integer missing, your task is to find and return the missing integer. This type of question is common in pr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1002,
"level": 1,
"question": "### Coding Task: Finding the Missing Number in a Consecutive Sequence\n\nGiven an unsorted list of distinct integers in the range from 1 to \\( n \\) (inclusive), with exactly one integer missing, your task is to find and return the missing integer. Th... |
from typing import List
def first_occurrence(array: List[int], query: int) -> int:
low = 0
high = len(array) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if array[mid] == query:
result = mid
high = mid - 1 # Continue searching left for earlier occu... | simplelr_Data_Structure | [
{
"content": "Question:\n## Coding Assessment Question\n\n### Context\nYou are tasked with developing a function that provides the index of the first occurrence of a given element within a sorted array. Your implementation should efficiently search through the array, leveraging its sorted property to minimize t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1003,
"level": 1,
"question": "## Coding Assessment Question\n\n### Context\nYou are tasked with developing a function that provides the index of the first occurrence of a given element within a sorted array. Your implementation should efficiently search through the array, leveragin... |
def parse_floats(strings):
result = []
for s in strings:
try:
result.append(float(s))
except ValueError:
result.append(None)
return result | simplelr_Filter | [
{
"content": "Question:\nYou've been tasked with writing a Python function `parse_floats` that takes a list of strings as input, and returns a new list where each element is the float equivalent of the corresponding string in the input list. If a string cannot be converted to a float, the function should append... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1004,
"level": 1,
"question": "You've been tasked with writing a Python function `parse_floats` that takes a list of strings as input, and returns a new list where each element is the float equivalent of the corresponding string in the input list. If a string cannot be converted to ... |
def students_above_threshold(students, threshold):
result = []
for student in students:
name = student['name']
grades = student['grades']
average = sum(grades) / len(grades)
if average > threshold:
result.append(name)
return result | simplelr_Evol | [
{
"content": "Question:\nWrite a function in Python that takes a list of dictionaries containing student records and a threshold grade as input. The function should return a list of names of students whose average grade is above the threshold. Each student record contains the following keys: 'name' (a string), ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1005,
"level": 1,
"question": "Write a function in Python that takes a list of dictionaries containing student records and a threshold grade as input. The function should return a list of names of students whose average grade is above the threshold. Each student record contains the ... |
from dateutil.parser import parse
def convert_date(date_str):
"""
Converts a date string to YYYY-MM-DD format.
Args:
date_str (str): The date string to convert.
Returns:
str: The date in YYYY-MM-DD format.
Raises:
TypeError: If the input is not a string.
ValueErro... | simplelr_Filter | [
{
"content": "Question:\nI am trying to create a method in Python that can convert any date to a standard format (in this case \"YYYY-MM-DD\"). I have a function that works, but it has some issues. \n\nHere are the issues with my current function:\n\n1. **Inconsistent Parameters:** The current function has two ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1006,
"level": 1,
"question": "I am trying to create a method in Python that can convert any date to a standard format (in this case \"YYYY-MM-DD\"). I have a function that works, but it has some issues. \n\nHere are the issues with my current function:\n\n1. **Inconsistent Paramete... |
def process_inventory(inventory, transactions):
for transaction in transactions:
transaction_type = transaction['type']
if transaction_type in ('add', 'remove'):
item_id = transaction['id']
for item in inventory:
if item['id'] == item_id:
i... | simplelr_Apps | [
{
"content": "Question:\nYou are given an inventory list of items in a store, and each item has a unique ID, a name, and a quantity available.\n\nYour task is to implement a function that will process a list of transactions. Each transaction will either add to the quantity of an item, remove from the quantity o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1007,
"level": 1,
"question": "You are given an inventory list of items in a store, and each item has a unique ID, a name, and a quantity available.\n\nYour task is to implement a function that will process a list of transactions. Each transaction will either add to the quantity of ... |
def unique_substrings_count(s):
substrings = set()
n = len(s)
for i in range(n):
for j in range(i + 1, n + 1):
substrings.add(s[i:j])
return len(substrings) | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function named `unique_substrings_count` that takes a string as input and returns the number of unique substrings that can be derived from it.\n\n#### Requirements:\n1. **Function Name:** `unique_substrings_count`\n2. **Parameter**:\n - `s` (str): The i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1008,
"level": 1,
"question": "You are tasked with creating a function named `unique_substrings_count` that takes a string as input and returns the number of unique substrings that can be derived from it.\n\n#### Requirements:\n1. **Function Name:** `unique_substrings_count`\n2. **P... |
def unique_letters_count(s):
unique_letters = set()
for char in s:
if char.isalpha():
unique_letters.add(char.lower())
return len(unique_letters) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to calculate the total number of unique letters in a string, ignoring the case (uppercase or lowercase) of the letters. For example, in the string \"Apple\", the function should return 4, as there are four unique letters: 'a', 'p', 'l', and 'e'.\nAnswer:\nLet's t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1009,
"level": 1,
"question": "Write a Python function to calculate the total number of unique letters in a string, ignoring the case (uppercase or lowercase) of the letters. For example, in the string \"Apple\", the function should return 4, as there are four unique letters: 'a', '... |
def total_cost(shopping_list):
total = 0
for item in shopping_list:
total += item[0] * item[1]
return total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the total cost of items in a shopping list. The list contains tuples where the first element of each tuple is the number of items and the cost per item. For example, [(2, 3.5), (1, 5.99), (3, 1.49)].\nAnswer:\nLet's think step by step.\n",
"role": "... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1010,
"level": 1,
"question": "Create a function that calculates the total cost of items in a shopping list. The list contains tuples where the first element of each tuple is the number of items and the cost per item. For example, [(2, 3.5), (1, 5.99), (3, 1.49)].",
"split": "trai... |
import numpy as np
def calculate_critical_points(function, derivative, points):
critical_points = []
for point in points:
if derivative(point) == 0:
critical_points.append(point)
return critical_points | simplelr_Filter | [
{
"content": "Question:\nHere is the code to calculate the critical points for an equation: \n```python\nimport numpy as np\n\ndef calculate_critical_points(function, derivative, points):\n \"\"\"\n Calculate critical points for the given function.\n\n Parameters:\n function (function): The function... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1011,
"level": 1,
"question": "Here is the code to calculate the critical points for an equation: \n```python\nimport numpy as np\n\ndef calculate_critical_points(function, derivative, points):\n \"\"\"\n Calculate critical points for the given function.\n\n Parameters:\n ... |
def has_all_unique_chars(s: str) -> bool:
n = len(s)
for i in range(1, n):
for j in range(i):
if s[i] == s[j]:
return False
return True | simplelr_Algorithm | [
{
"content": "Question:\n### Unique Characters Detection\n\nDevelop a utility to determine if all characters in a given string are unique without using any additional data structures.\n\n### Problem Statement\nCreate a function `has_all_unique_chars` that checks if all characters in a given string are unique.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1012,
"level": 1,
"question": "### Unique Characters Detection\n\nDevelop a utility to determine if all characters in a given string are unique without using any additional data structures.\n\n### Problem Statement\nCreate a function `has_all_unique_chars` that checks if all charact... |
def trapWater(arr):
n = len(arr)
if n < 2:
return 0
left_max = [0] * n
for i in range(1, n):
left_max[i] = max(left_max[i-1], arr[i-1])
right_max = [0] * n
for i in range(n-2, -1, -1):
right_max[i] = max(arr[i+1], right_max[i+1])
total_water = 0
for i in range(n):... | simplelr_Taco | [
{
"content": "Question:\nGiven an array `arr` of positive integers representing the heights of buildings along a street. Suppose it starts raining and all water falling on buildings gets accumulated on top of the buildings and between the buildings. Your task is to find the total amount of water accumulated in ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1013,
"level": 1,
"question": "Given an array `arr` of positive integers representing the heights of buildings along a street. Suppose it starts raining and all water falling on buildings gets accumulated on top of the buildings and between the buildings. Your task is to find the to... |
from collections import defaultdict
def remove_excessive_characters(s):
counts = defaultdict(int)
res = []
for c in s:
if counts[c] < 2:
res.append(c)
counts[c] += 1
return ''.join(res) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` of lowercase letters. You need to remove the minimum number of characters from the string so that every letter appears at most twice. Return _the resulting string after the removal_. If there are multiple valid results, you may return **any of them**.\nAnswer:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1014,
"level": 1,
"question": "You are given a string `s` of lowercase letters. You need to remove the minimum number of characters from the string so that every letter appears at most twice. Return _the resulting string after the removal_. If there are multiple valid results, you m... |
def binary_search(array, target):
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == target:
return mid
elif target < array[mid]:
high = mid - 1
else:
low = mid + 1
return -1 | simplelr_Filter | [
{
"content": "Question:\nCreate a function to implement a binary search algorithm that has a time complexity of O(log n) and a space complexity of O(1). The function should also handle cases where the target value is not present in the array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1015,
"level": 1,
"question": "Create a function to implement a binary search algorithm that has a time complexity of O(log n) and a space complexity of O(1). The function should also handle cases where the target value is not present in the array.",
"split": "train"
} |
def reverse_words(sentence):
words = sentence.split()
reversed_words = words[::-1]
return ' '.join(reversed_words)
| simplelr_Taco | [
{
"content": "Question:\n## Reverse Words in a Sentence\nYou are given a sentence consisting of multiple words separated by spaces. Your task is to reverse the order of the words in the sentence while keeping the characters in each word unchanged.\n\n## Task\n\nWrite a function that takes a string input represe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1016,
"level": 1,
"question": "## Reverse Words in a Sentence\nYou are given a sentence consisting of multiple words separated by spaces. Your task is to reverse the order of the words in the sentence while keeping the characters in each word unchanged.\n\n## Task\n\nWrite a functio... |
def check_subarray_sum(arr, k):
if k == 0:
# Handle the case where k is zero by checking for any subarray with sum zero and size >=2
n = len(arr)
for i in range(n):
current_sum = 0
for j in range(i, n):
current_sum += arr[j]
if current_... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr`, write a function to determine if it contains a continuous subarray of size at least 2 that sums up to a multiple of `k`, where `k` is a given integer. A continuous subarray is a sequence of elements within the array that you can identify by specifying t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1017,
"level": 1,
"question": "Given an array of integers `arr`, write a function to determine if it contains a continuous subarray of size at least 2 that sums up to a multiple of `k`, where `k` is a given integer. A continuous subarray is a sequence of elements within the array th... |
def sort_heights(heights):
return sorted(heights) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `heights` representing the heights of students in a class. The array is arranged in any random order. Your task is to sort the students such that everyone's height is in non-decreasing order. Return the sorted array of heights. Note that the same age may a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1018,
"level": 1,
"question": "You are given an integer array `heights` representing the heights of students in a class. The array is arranged in any random order. Your task is to sort the students such that everyone's height is in non-decreasing order. Return the sorted array of he... |
from collections import Counter
def can_form_by_rearranging(str1, str2):
if len(str1) != len(str2):
return False
return Counter(str1.lower()) == Counter(str2.lower()) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given string can be formed by rearranging the characters of another string. The function should handle cases where the strings may contain any characters and ensure that the function is case-insensitive.\nAnswer:\nLet's think step by step.\n",
"role": ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1019,
"level": 1,
"question": "Write a function to check if a given string can be formed by rearranging the characters of another string. The function should handle cases where the strings may contain any characters and ensure that the function is case-insensitive.",
"split": "tra... |
def largestRectangleArea(heights):
n = len(heights)
if n == 0:
return 0
left = [-1] * n
stack = []
for i in range(n):
while stack and heights[stack[-1]] >= heights[i]:
stack.pop()
if stack:
left[i] = stack[-1]
else:
left[i] = -1
... | simplelr_Apps | [
{
"content": "Question:\nYou are given an array of integers representing a histogram. Each integer describes the height of a bar in the histogram. Compute the area of the largest rectangle that can be formed within the bounds of the histogram. The rectangle must be aligned with the x-axis.\n\nFor example, given... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1020,
"level": 1,
"question": "You are given an array of integers representing a histogram. Each integer describes the height of a bar in the histogram. Compute the area of the largest rectangle that can be formed within the bounds of the histogram. The rectangle must be aligned wit... |
from collections import deque
def shortest_path(grid):
if not grid or len(grid) == 0 or len(grid[0]) == 0:
return -1
m = len(grid)
n = len(grid[0])
if grid[0][0] != 0 or grid[m-1][n-1] != 0:
return -1
if m == 1 and n == 1:
return 0
visited = [[False for _ in range(n... | simplelr_Apps | [
{
"content": "Question:\nGiven a grid, where some cells are walkable and others are obstacles, determine the shortest path from the top-left corner to the bottom-right corner. The grid is represented as a 2D array where a 0 represents a walkable cell and a 1 represents an obstacle.\n\nWrite a function `shortest... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1021,
"level": 1,
"question": "Given a grid, where some cells are walkable and others are obstacles, determine the shortest path from the top-left corner to the bottom-right corner. The grid is represented as a 2D array where a 0 represents a walkable cell and a 1 represents an obst... |
def repeat_string(s, n):
return s * n | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string and an integer as arguments and returns a string that repeats the given string the specified number of times.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1022,
"level": 1,
"question": "Create a function that takes a string and an integer as arguments and returns a string that repeats the given string the specified number of times.",
"split": "train"
} |
def longest_string_with_vowel_count(string_list):
if not string_list:
return (None, 0)
longest_str = string_list[0]
max_length = len(longest_str)
for string in string_list[1:]:
current_length = len(string)
if current_length > max_length:
longest_str = string... | simplelr_Filter | [
{
"content": "Question:\nCreate a function that not only returns the longest string from a list but also count the number of vowels in that string. If there are two or more strings with the same length, return the one that appears first in the list. Include error handling for situations where the list may be em... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1023,
"level": 1,
"question": "Create a function that not only returns the longest string from a list but also count the number of vowels in that string. If there are two or more strings with the same length, return the one that appears first in the list. Include error handling for ... |
def is_palindrome(N):
s = str(N)
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return "Not Palindrome"
left += 1
right -= 1
return "Palindrome"
| simplelr_Taco | [
{
"content": "Question:\nDetermine if a given number is a palindrome. If the number N is a palindrome, return ```\"Palindrome\"``` else ```return \"Not Palindrome\"```. \nHINT: Consider both efficiency and input size, as N can be very large.\n\nInput\n1 ≤ N ≤ 10^(100)\n\nExample \nis_palindrome(121) # should ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1024,
"level": 1,
"question": "Determine if a given number is a palindrome. If the number N is a palindrome, return ```\"Palindrome\"``` else ```return \"Not Palindrome\"```. \nHINT: Consider both efficiency and input size, as N can be very large.\n\nInput\n1 ≤ N ≤ 10^(100)\n\nExam... |
def highest_and_lowest_temperatures(temps):
if not temps:
return None, None
return max(temps), min(temps) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the highest and lowest temperatures in a list of daily temperature readings in Celsius.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1025,
"level": 1,
"question": "Create a function that calculates the highest and lowest temperatures in a list of daily temperature readings in Celsius.",
"split": "train"
} |
import re
def normalize_text_file(input_file: str, output_file: str) -> None:
with open(input_file, 'r') as f:
text = f.read()
# Convert text to lowercase
text = text.lower()
# Replace any non-alphabetic character with a space
text = re.sub(r'[^a-z]', ' ', text)
# Replace... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function called `normalize_text_file` that reads a text file, normalizes the text, and writes the normalized text back to a new file. Normalization involves converting all characters to lowercase, removing punctuation, and replacing multiple spaces with a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1026,
"level": 1,
"question": "You are tasked with creating a function called `normalize_text_file` that reads a text file, normalizes the text, and writes the normalized text back to a new file. Normalization involves converting all characters to lowercase, removing punctuation, an... |
def sum_of_digits(s: str) -> int:
total = 0
for c in s:
if c.isdigit():
total += int(c)
return total | simplelr_Algorithm | [
{
"content": "Question:\n### Sum of Digits in a String\n\n**Context:**\n\nYou are tasked with creating a function that processes a given string consisting of both characters and digits. Your function should calculate the sum of all the numerical digits present in the string. This function is useful in various a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1027,
"level": 1,
"question": "### Sum of Digits in a String\n\n**Context:**\n\nYou are tasked with creating a function that processes a given string consisting of both characters and digits. Your function should calculate the sum of all the numerical digits present in the string. T... |
def sum_of_odds(n):
if n < 1:
return 0
k = (n + 1) // 2
return k * k | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer n as an argument and returns the sum of all odd numbers from 1 to n (inclusive). In Python, how would you write this function?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1028,
"level": 1,
"question": "Create a function that takes an integer n as an argument and returns the sum of all odd numbers from 1 to n (inclusive). In Python, how would you write this function?",
"split": "train"
} |
def remove_duplicates(nums):
seen = set()
result = []
for num in nums:
if num not in seen:
result.append(num)
seen.add(num)
return result | simplelr_Filter | [
{
"content": "Question:\nYou've been tasked with writing a function `remove_duplicates` which takes in a list of integers as input and returns a new list containing all unique integers from the input list, in the order they first appeared. \n\nFor example, given the input `[1, 2, 2, 3, 4, 4, 5, 6, 6]`, the func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1029,
"level": 1,
"question": "You've been tasked with writing a function `remove_duplicates` which takes in a list of integers as input and returns a new list containing all unique integers from the input list, in the order they first appeared. \n\nFor example, given the input `[1,... |
def count_repeated_integers(input_list):
counts = {}
for number in input_list:
if number in counts:
counts[number] += 1
else:
counts[number] = 1
# Create a new dictionary with only those items where count is at least 2
result = {key: value for key, value in counts... | simplelr_Package | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a dictionary containing the frequency of each unique integer in the list. Only include integers that are repeated at least once in the list. The function should output a dictionary where the keys are the repeated integers and t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1030,
"level": 1,
"question": "Create a function that takes a list of integers and returns a dictionary containing the frequency of each unique integer in the list. Only include integers that are repeated at least once in the list. The function should output a dictionary where the k... |
def max_subarray_sum(arr):
if not arr:
return 0 # or handle as needed based on problem constraints
max_current = max_global = arr[0]
for num in arr[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global | simplelr_Filter | [
{
"content": "Question:\nHere's a problem I'm working on:\n\n**Problem:** You are given an array of integers and you need to find the subarray with the maximum sum.\n\n**Input:** An array of integers\n\n**Output:** The maximum sum of any contiguous subarray within the input array\n\n**Example:**\n\n```\nInput: ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1031,
"level": 1,
"question": "Here's a problem I'm working on:\n\n**Problem:** You are given an array of integers and you need to find the subarray with the maximum sum.\n\n**Input:** An array of integers\n\n**Output:** The maximum sum of any contiguous subarray within the input ar... |
def closestElement(arr, n, x):
best_diff = float('inf')
best_element = None
for num in arr:
current_diff = abs(num - x)
if current_diff < best_diff:
best_diff = current_diff
best_element = num
elif current_diff == best_diff:
if num < best_element:
... | simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers Arr of size N and a target integer X, find the element in the array that is closest to X. If there are multiple such elements, return the smallest one.\nExample 1:\nInput:\nN = 6\nArr[] = {10, 22, 28, 29, 30, 40}\nX = 54\nOutput: 40\nExample 2:\nInput:\nN = 6\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1032,
"level": 1,
"question": "Given an array of integers Arr of size N and a target integer X, find the element in the array that is closest to X. If there are multiple such elements, return the smallest one.\nExample 1:\nInput:\nN = 6\nArr[] = {10, 22, 28, 29, 30, 40}\nX = 54\nOut... |
def sum_of_fibonacci(n):
total = 0
a, b = 0, 1
for _ in range(n):
total += a
a, b = b, a + b
return total | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum of the first `n` Fibonacci numbers. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1033,
"level": 1,
"question": "Write a function to calculate the sum of the first `n` Fibonacci numbers. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two.",
"split": "train"
} |
def evaluate_expressions(expressions):
results = []
allowed_chars = set('0123456789+-*/() ')
for expr in expressions:
valid = True
# Step 1: Check all characters are allowed
for c in expr:
if c not in allowed_chars:
valid = False
b... | simplelr_Evol | [
{
"content": "Question:\nDevelop a function that takes a list of strings containing mathematical expressions and evaluates each one for correctness. The expressions can contain integers, addition, subtraction, multiplication, division, and parentheses. Your function should return a list of booleans indicating w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1034,
"level": 1,
"question": "Develop a function that takes a list of strings containing mathematical expressions and evaluates each one for correctness. The expressions can contain integers, addition, subtraction, multiplication, division, and parentheses. Your function should ret... |
import struct
def pack_and_unpack(format_str: str, values: list):
packed = struct.pack(format_str, *values)
unpacked = struct.unpack(format_str, packed)
return unpacked
| simplelr_Docs | [
{
"content": "Question:\nIn this assessment, you are required to manipulate binary data using the `struct` module. The task is to create a function to pack a sequence of mixed data types into a binary format and then unpack it back to its original data structure.\n\n### Instructions\n\nWrite a function `pack_an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1035,
"level": 1,
"question": "In this assessment, you are required to manipulate binary data using the `struct` module. The task is to create a function to pack a sequence of mixed data types into a binary format and then unpack it back to its original data structure.\n\n### Instru... |
def min_coins(coins, amount):
if amount == 0:
return 0
dp = [float('inf')] * (amount + 1)
dp[0] = 0 # Base case: 0 coins needed to make 0 amount
for coin in coins:
for i in range(coin, amount + 1):
if dp[i - coin] + 1 < dp[i]:
dp[i] = dp[i - coin] + 1
... | simplelr_Filter | [
{
"content": "Question:\nIs there a way to solve the problem of finding the minimum number of coins required to make a certain amount of money using dynamic programming in Python? The denominations of the coins are given, and we need to find the minimum number of coins required to make the amount. If it is not ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1036,
"level": 1,
"question": "Is there a way to solve the problem of finding the minimum number of coins required to make a certain amount of money using dynamic programming in Python? The denominations of the coins are given, and we need to find the minimum number of coins require... |
def transform_numbers(numbers):
return [num * 2 if num % 2 == 0 else num * 3 for num in numbers] | simplelr_Filter | [
{
"content": "Question:\nI have a list of integers, and I want to create a function that will iterate through this list, and replace all the even numbers with their double, and if a number is odd, I want it to be replaced with the triple of its value. \n\nHere is my code so far: \n\n```python\ndef transform_num... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1037,
"level": 1,
"question": "I have a list of integers, and I want to create a function that will iterate through this list, and replace all the even numbers with their double, and if a number is odd, I want it to be replaced with the triple of its value. \n\nHere is my code so fa... |
def max_path_sum(grid):
if not grid:
return 0
m = len(grid)
n = len(grid[0]) if m > 0 else 0
if m == 0 or n == 0:
return 0
dp = [[0 for _ in range(n)] for _ in range(m)]
dp[0][0] = grid[0][0]
for j in range(1, n):
dp[0][j] = dp[0][j-1] + grid[0][j]
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a 2D grid `grid` of size `m x n` consisting of non-negative integers. You are initially positioned at cell `(0, 0)` and must move to cell `(m-1, n-1)` while accumulating the maximum sum of values of the cells you visit. You can only move either right or down from a cell. \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1038,
"level": 1,
"question": "You are given a 2D grid `grid` of size `m x n` consisting of non-negative integers. You are initially positioned at cell `(0, 0)` and must move to cell `(m-1, n-1)` while accumulating the maximum sum of values of the cells you visit. You can only move ... |
def read_and_process_file(filename):
with open(filename, 'r') as file:
data = file.read()
digits_in_file = [int(i) for i in data if i.isdigit()]
numbers = digits_in_file # since each num is already a single-digit
return sum(numbers) | simplelr_Filter | [
{
"content": "Question:\nHere is a code that reads a file and looks for digits, if the file contains digits it reads those digits as int and performs an arithmetic operation:\n```python\ndef read_and_process_file(filename):\n with open(filename, 'r') as file:\n data = file.read()\n digits_in_file =... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1039,
"level": 1,
"question": "Here is a code that reads a file and looks for digits, if the file contains digits it reads those digits as int and performs an arithmetic operation:\n```python\ndef read_and_process_file(filename):\n with open(filename, 'r') as file:\n data ... |
def length_of_longest_substring(s):
max_length = 0
last_seen = {}
left = 0
for right in range(len(s)):
current_char = s[right]
if current_char in last_seen:
left = max(left, last_seen[current_char] + 1)
last_seen[current_char] = right
current_length = right - ... | simplelr_Filter | [
{
"content": "Question:\nWrite a function that takes in a string and returns the length of the longest substring without repeating characters. For example, given the string \"abcabcbb\", the longest substring without repeating characters is \"abc\", which has a length of 3. Given the string \"bbbbb\", the longe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1040,
"level": 1,
"question": "Write a function that takes in a string and returns the length of the longest substring without repeating characters. For example, given the string \"abcabcbb\", the longest substring without repeating characters is \"abc\", which has a length of 3. Gi... |
def reverse_string(s):
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse a given string. For example, if the input string is \"coding\", the output should be \"gnidoc\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1041,
"level": 1,
"question": "Write a python function to reverse a given string. For example, if the input string is \"coding\", the output should be \"gnidoc\".",
"split": "train"
} |
from typing import List
def longest_consecutive_sequence(nums: List[int]) -> int:
if not nums:
return 0
num_set = set(nums)
max_length = 0
for x in num_set:
if (x - 1) not in num_set:
current = x
current_length = 1
while (current + 1) in num_set:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Longest Consecutive Sequence\n\n#### Objective\n\nGiven an unsorted array of integers, implement a function to find the length of the longest consecutive sequence of integers in the array. Your algorithm should aim for O(n) complexity.\n\n#### Function Signature\n\n```python\ndef lo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1042,
"level": 1,
"question": "### Longest Consecutive Sequence\n\n#### Objective\n\nGiven an unsorted array of integers, implement a function to find the length of the longest consecutive sequence of integers in the array. Your algorithm should aim for O(n) complexity.\n\n#### Func... |
def canFormSubsetWithSum(x, lengths):
dp = [False] * (x + 1)
dp[0] = True # Base case: sum 0 is always possible with an empty subset
for s in lengths:
# Iterate from high to low to avoid using the same element multiple times
for j in range(x, s - 1, -1):
if dp[j - s]:
... | simplelr_Taco | [
{
"content": "Question:\nYou are given n sticks of varying lengths and an integer x. You need to determine if there is a subset of these sticks such that the sum of their lengths is exactly x. \n\nWrite a function `canFormSubsetWithSum` that takes an integer x and a list of integers representing the lengths of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1043,
"level": 1,
"question": "You are given n sticks of varying lengths and an integer x. You need to determine if there is a subset of these sticks such that the sum of their lengths is exactly x. \n\nWrite a function `canFormSubsetWithSum` that takes an integer x and a list of in... |
def word_frequency(s):
frequency = {}
s_lower = s.lower()
words = s_lower.split()
for word in words:
if word in frequency:
frequency[word] += 1
else:
frequency[word] = 1
return frequency | simplelr_Apps | [
{
"content": "Question:\nA common task in text processing is to count the frequency of each word in a given string. Write a function named `word_frequency` that takes a single string as input and returns a dictionary where the keys are words and the values are the number of times each word appears in the input ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1044,
"level": 1,
"question": "A common task in text processing is to count the frequency of each word in a given string. Write a function named `word_frequency` that takes a single string as input and returns a dictionary where the keys are words and the values are the number of ti... |
def sum_positive_even_numbers(numbers):
return sum(num for num in numbers if num > 0 and num % 2 == 0) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the sum of all positive even numbers in a list. The function should return the sum.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1045,
"level": 1,
"question": "Write a python function to find the sum of all positive even numbers in a list. The function should return the sum.",
"split": "train"
} |
def find_manhattan_distances(R, C, queries):
result = []
for q in queries:
(r1, c1), (r2, c2) = q
distance = abs(r1 - r2) + abs(c1 - c2)
result.append(distance)
return result | simplelr_Codeforces | [
{
"content": "Question:\nIn a large warehouse, there are M storage rooms arranged in a grid of R rows and C columns (R * C = M). The warehouse manager wants to label each storage room with unique numeric identifiers in such a way that the label reflects the row and column position of the storage room. However, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1046,
"level": 1,
"question": "In a large warehouse, there are M storage rooms arranged in a grid of R rows and C columns (R * C = M). The warehouse manager wants to label each storage room with unique numeric identifiers in such a way that the label reflects the row and column posi... |
import math
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
max_divisor = math.sqrt(n)
for d in range(3, int(max_divisor) + 1, 2):
if n % d == 0:
return False
return True | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a number is prime. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1047,
"level": 1,
"question": "Write a function to check if a number is prime. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.",
"split": "train"
} |
def canArrangeMultipleOf3(num):
sum_digits = 0
for c in num:
sum_digits += int(c)
return 1 if sum_digits % 3 == 0 else 0
| simplelr_Taco | [
{
"content": "Question:\nGiven a string containing a large number, check whether the digits of the number can be rearranged to form a multiple of 3. Print 1 if possible, otherwise print 0.\n\nExample 1:\nInput: num = \"120\"\nOutput: 1\nExplanation: The digits can be rearranged to form 102, which is a multiple ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1048,
"level": 1,
"question": "Given a string containing a large number, check whether the digits of the number can be rearranged to form a multiple of 3. Print 1 if possible, otherwise print 0.\n\nExample 1:\nInput: num = \"120\"\nOutput: 1\nExplanation: The digits can be rearrange... |
def min_cost_path(grid):
if not grid or not grid[0]:
return 0
n = len(grid)
m = len(grid[0])
dp = [[0 for _ in range(m)] for __ in range(n)]
dp[0][0] = grid[0][0]
# Fill the first row
for j in range(1, m):
dp[0][j] = dp[0][j-1] + grid[0][j]
# Fill the first colu... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a 2D grid representing a labyrinth where each cell contains a number that shows the cost of moving through that cell. The goal is to find the path from the top-left corner (0,0) to the bottom-right corner (n-1,m-1) that minimizes the cost. You can only move right or down a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1049,
"level": 1,
"question": "You are given a 2D grid representing a labyrinth where each cell contains a number that shows the cost of moving through that cell. The goal is to find the path from the top-left corner (0,0) to the bottom-right corner (n-1,m-1) that minimizes the cost... |
def can_place_rectangles(rectangles, M, N):
sum_min = 0
max_max = 0
for l, w in rectangles:
# Check if the rectangle can fit in either orientation
if (l > M or w > N) and (w > M or l > N):
return False
sum_min += min(l, w)
current_max = max(l, w)
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a 2D integer array `rectangles` where `rectangles[i] = [li, wi]` represents the length and width of the `ith` rectangle. You want to place these rectangles on a plane such that none of them overlap, and they are all aligned with the axes (meaning their sides are parallel t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1050,
"level": 1,
"question": "You are given a 2D integer array `rectangles` where `rectangles[i] = [li, wi]` represents the length and width of the `ith` rectangle. You want to place these rectangles on a plane such that none of them overlap, and they are all aligned with the axes ... |
def improved_selection_sort(arr, simulation=False):
"""
Sort the array using an optimized selection sort algorithm.
Args:
arr (list[int]): The list of integers to be sorted.
simulation (bool): If True, prints the state of the list after each pass for visualization.
Returns:
list[in... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Implement an Improved Selection Sort\n\n#### Scenario\n\nThe current selection sort algorithm is straightforward but not efficient for large datasets. Imagine you're developing software for sorting a small catalog of items and need an optimized version of selection sort th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1051,
"level": 1,
"question": "### Question: Implement an Improved Selection Sort\n\n#### Scenario\n\nThe current selection sort algorithm is straightforward but not efficient for large datasets. Imagine you're developing software for sorting a small catalog of items and need an opt... |
from collections import Counter
def can_form_palindrome(s: str) -> bool:
counts = Counter(s)
return sum(count % 2 for count in counts.values()) <= 1 | simplelr_Algorithm | [
{
"content": "Question:\n### Rearrange Characters to Create Palindrome\n\n**Scenario**:\nYou are working on a project to enhance a text-based puzzle game that involves creating palindromic strings. The player is given a string and must rearrange its characters to form a palindrome, if possible.\n\n**Task**:\nWr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1052,
"level": 1,
"question": "### Rearrange Characters to Create Palindrome\n\n**Scenario**:\nYou are working on a project to enhance a text-based puzzle game that involves creating palindromic strings. The player is given a string and must rearrange its characters to form a palind... |
def sum_unique_transactions(transactions):
seen = set()
sum_unique = 0
for t in transactions:
if t not in seen:
seen.add(t)
sum_unique += t
return sum_unique | simplelr_Apps | [
{
"content": "Question:\nYou are given a list of integers representing transaction amounts on a particular day. Unfortunately, the list also includes some duplicate transactions due to a system error. Your task is to process the list and retain only unique transaction amounts in the same order as they first app... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1053,
"level": 1,
"question": "You are given a list of integers representing transaction amounts on a particular day. Unfortunately, the list also includes some duplicate transactions due to a system error. Your task is to process the list and retain only unique transaction amounts ... |
def calculate_total_cost_on_sale(items):
return sum(item['price'] for item in items if item['on_sale']) | simplelr_Filter | [
{
"content": "Question:\nI have a list of items and I want to find the total cost of items that are on sale. I have the following data: \n* Item name\n* Item price\n* Item sale status (True if the item is on sale, False if it is not)\nI want to write a Python function that calculates the total cost of items on ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1054,
"level": 1,
"question": "I have a list of items and I want to find the total cost of items that are on sale. I have the following data: \n* Item name\n* Item price\n* Item sale status (True if the item is on sale, False if it is not)\nI want to write a Python function that cal... |
def multiply(a, b):
a_is_number = isinstance(a, (int, float)) and not isinstance(a, bool)
b_is_number = isinstance(b, (int, float)) and not isinstance(b, bool)
if a_is_number and b_is_number:
return a * b
else:
return 'Not a number' | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code to multiply two given numbers, and additionally, the functions should return 'Not a number' if a non-numeric input is given. Input-floating numbers should be taken into consideration as well.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1055,
"level": 1,
"question": "Write a Python code to multiply two given numbers, and additionally, the functions should return 'Not a number' if a non-numeric input is given. Input-floating numbers should be taken into consideration as well.",
"split": "train"
} |
def largest_square_submatrix(matrix, k):
if k == 0:
return 0
dp = [[0] * k for _ in range(k)]
max_side = 0
for i in range(k):
for j in range(k):
if matrix[i][j] == 1:
if i == 0 or j == 0:
dp[i][j] = 1
else:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a `k x k` binary matrix `matrix` and an integer `k`. A binary matrix is a matrix that has only `0`s and `1`s as its elements. Your task is to determine the length of the largest square that can be obtained by selecting a submatrix from `matrix` such that all of its element... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1056,
"level": 1,
"question": "You are given a `k x k` binary matrix `matrix` and an integer `k`. A binary matrix is a matrix that has only `0`s and `1`s as its elements. Your task is to determine the length of the largest square that can be obtained by selecting a submatrix from `m... |
from typing import List
def maxProfit(prices: List[int]) -> int:
buy1 = -float('inf')
sell1 = 0
buy2 = -float('inf')
sell2 = 0
for price in prices:
buy1 = max(buy1, -price)
sell1 = max(sell1, price + buy1)
buy2 = max(buy2, sell1 - price)
sell2 = max(sell2, price + bu... | simplelr_Apps | [
{
"content": "Question:\nGiven a list of integers representing the pricing history of a stock, you need to find the maximum profit you can achieve by making exactly two buy-sell transactions. A buy-sell transaction consists of buying one share of the stock at a given day and selling one share of the stock at a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1057,
"level": 1,
"question": "Given a list of integers representing the pricing history of a stock, you need to find the maximum profit you can achieve by making exactly two buy-sell transactions. A buy-sell transaction consists of buying one share of the stock at a given day and s... |
import bisect
def kthSmallest(matrix, k):
if not matrix or not matrix[0]:
return None # Assuming the function should return None for invalid input
low = matrix[0][0]
high = matrix[-1][-1]
while low < high:
mid = (low + high) // 2
count = 0
for row in ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a matrix of integers `matrix` where each row is sorted in ascending order, return the k-th smallest element in the matrix. You must find a solution with better time complexity than O(n*m), where n is the number of rows and m is the number of columns.\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1058,
"level": 1,
"question": "Given a matrix of integers `matrix` where each row is sorted in ascending order, return the k-th smallest element in the matrix. You must find a solution with better time complexity than O(n*m), where n is the number of rows and m is the number of colu... |
def extract_uppercase_words(s):
words = s.split()
uppercase_words = []
for word in words:
if word.isupper() and len(word) > 1:
uppercase_words.append(word)
return uppercase_words | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that can parse a string and extract all words that are in uppercase. The function should be able to handle a string input and return a list of uppercase words. If there are no uppercase words, the function should return an empty list. Additionally, the function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1059,
"level": 1,
"question": "Create a Python function that can parse a string and extract all words that are in uppercase. The function should be able to handle a string input and return a list of uppercase words. If there are no uppercase words, the function should return an empt... |
def chunk_list(lst, size):
chunks = []
current = 0
while current < len(lst):
end = current + size
chunks.append(tuple(lst[current:end]))
current = end
return chunks | simplelr_Filter | [
{
"content": "Question:\nI have a list of tuples, and I need to chunk the list into sublists of a specified size. \n\nFor example, if I have the list `[(1,2), (3,4), (5,6), (7,8), (9,10)]` and I specify a size of `2`, I want to get the following output:\n`[((1,2), (3,4)), ((5,6), (7,8)), ((9,10))]`\n\nSimilarly... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1060,
"level": 1,
"question": "I have a list of tuples, and I need to chunk the list into sublists of a specified size. \n\nFor example, if I have the list `[(1,2), (3,4), (5,6), (7,8), (9,10)]` and I specify a size of `2`, I want to get the following output:\n`[((1,2), (3,4)), ((5,... |
def box_volume(length: float, width: float, height: float) -> float:
if length <= 0:
raise ValueError("The length of the box cannot be zero or negative")
if width <= 0:
raise ValueError("The width of the box cannot be zero or negative")
if height <= 0:
raise ValueError("The height of... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Box Volume Calculator\n\n#### Problem Statement:\nYou are required to implement a Python function that calculates the volume of a rectangular box using its length, width, and height. The volume of a box is given by the formula `V = lwh`, where `l` is the length, `w` is the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1061,
"level": 1,
"question": "### Question: Box Volume Calculator\n\n#### Problem Statement:\nYou are required to implement a Python function that calculates the volume of a rectangular box using its length, width, and height. The volume of a box is given by the formula `V = lwh`, ... |
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert degrees Celsius to degrees Fahrenheit.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1062,
"level": 1,
"question": "Write a python function to convert degrees Celsius to degrees Fahrenheit.",
"split": "train"
} |
def tuples_to_dict(tuples):
result = {}
for key, value in tuples:
if key in result:
result[key].append(value)
else:
result[key] = [value]
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of tuples as input, where each tuple represents a key-value pair. The function should return a dictionary where the keys are the first elements of the tuples, and the values are lists of the second elements of the tuples that share the same key.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1063,
"level": 1,
"question": "Write a Python function that takes a list of tuples as input, where each tuple represents a key-value pair. The function should return a dictionary where the keys are the first elements of the tuples, and the values are lists of the second elements of ... |
import re
def calculate_expression(s: str) -> int:
s = s.replace(' ', '')
initial_match = re.match(r'^([+-]?\d+)', s)
initial = initial_match.group(1) if initial_match else '0'
rest = s[len(initial):]
tokens = re.findall(r'([+-]\d+)', rest)
total = int(initial)
for token in tokens:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\nYou are given a string `s` representing a numeric expression containing digits and the operators `+` and `-`. Your task is to write a function `calculate_expression(s: str) -> int` that evaluates the expression and returns the result as an integer.\n\n#### Constraints:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1064,
"level": 1,
"question": "### Question\n\nYou are given a string `s` representing a numeric expression containing digits and the operators `+` and `-`. Your task is to write a function `calculate_expression(s: str) -> int` that evaluates the expression and returns the result as... |
def shift_string(s, n):
result = []
for c in s:
if c.islower():
shifted = ((ord(c) - ord('a') + n) % 26) + ord('a')
result.append(chr(shifted))
elif c.isupper():
shifted = ((ord(c) - ord('A') + n) % 26) + ord('A')
result.append(chr(shifted))
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` and an integer `n`, return a new string such that each character in the original string `s` is shifted forward in the alphabet by `n` positions. The alphabet is considered to be circular, so if shifting a character forward by `n` positions moves it past 'z', it wraps ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1065,
"level": 1,
"question": "Given a string `s` and an integer `n`, return a new string such that each character in the original string `s` is shifted forward in the alphabet by `n` positions. The alphabet is considered to be circular, so if shifting a character forward by `n` pos... |
def two_sum(numbers, target):
num_dict = {}
for i, num in enumerate(numbers):
complement = target - num
if complement in num_dict:
return [num_dict[complement], i]
num_dict[num] = i
return [] | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of integers `numbers` and an integer `target`, find two distinct indices `i` and `j` such that `numbers[i] + numbers[j]` equals `target`. Return the indices as a list `[i, j]`. You may assume that each input would have exactly one solution, and you may not use the same elem... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1066,
"level": 1,
"question": "Given a list of integers `numbers` and an integer `target`, find two distinct indices `i` and `j` such that `numbers[i] + numbers[j]` equals `target`. Return the indices as a list `[i, j]`. You may assume that each input would have exactly one solution... |
def find_duplicates(lst):
# Initialize dictionaries to track counts and first occurrences
counts = {}
first_occurrence = {}
# First pass: count occurrences and record first occurrence indices
for idx, num in enumerate(lst):
if isinstance(num, int):
if num in counts:
... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns a list of integers that appear more than once in the input list. The function should maintain the original order of their first occurrence. Make sure to handle edge cases gracefully, including when the input list is empty... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1067,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns a list of integers that appear more than once in the input list. The function should maintain the original order of their first occurrence. Make sure to handle edge cases gracefully, inc... |
from typing import List
def detailed_bubble_sort(arr: List[int], simulation: bool = False) -> List[int]:
arr_copy = arr.copy()
n = len(arr_copy)
iteration_count = 0
for i in range(n):
swapped = False
for j in range(n - i - 1):
if arr_copy[j] > arr_copy[j + 1]:
... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked to implement a simulation-enhanced version of the Bubble Sort algorithm. The function should provide information about its inner workings and the sorting process.\n\n### Function Signature\n```python\ndef detailed_bubble_sort(arr: List[int], simulation: bool=False) -> Lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1068,
"level": 1,
"question": "You are tasked to implement a simulation-enhanced version of the Bubble Sort algorithm. The function should provide information about its inner workings and the sorting process.\n\n### Function Signature\n```python\ndef detailed_bubble_sort(arr: List[i... |
from importlib import util
import sys
from typing import Optional, List, Any
def load_module_compat(name: str, path: Optional[List[str]] = None) -> Any:
if name is None:
raise ImportError("Module name cannot be None")
try:
import importlib
have_importlib = True
except ImportErr... | simplelr_Docs | [
{
"content": "Question:\n### Question: Module Importer with Backward Compatibility\n\nPython has deprecated the `imp` module in favor of `importlib`. However, you may encounter legacy code that still relies on `imp`. Your task is to write a function that attempts to find and load a module using `importlib`, but... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1069,
"level": 1,
"question": "### Question: Module Importer with Backward Compatibility\n\nPython has deprecated the `imp` module in favor of `importlib`. However, you may encounter legacy code that still relies on `imp`. Your task is to write a function that attempts to find and l... |
def extract_domain_name(url: str) -> str:
# Remove the protocol by splitting on ://
url_without_protocol = url.split('://')[-1]
# Extract the host by splitting on / and taking the first part
host = url_without_protocol.split('/')[0]
# Split the host into parts based on .
host_parts = h... | simplelr_Data_Structure | [
{
"content": "Question:\n**Problem**:\n\nYou are building a web categorization tool that needs to identify the primary domain from a list of URLs. Write a function `extract_domain_name` that accepts a URL as a string and returns the primary domain name as a string. \n\n**Function Signature:**\n```python\ndef ex... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1070,
"level": 1,
"question": "**Problem**:\n\nYou are building a web categorization tool that needs to identify the primary domain from a list of URLs. Write a function `extract_domain_name` that accepts a URL as a string and returns the primary domain name as a string. \n\n**Funct... |
def count_anagram_groups(words):
groups = set()
for word in words:
sorted_word = ''.join(sorted(word))
groups.add(sorted_word)
return len(groups) | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context:\nAn anagram is a word formed by rearranging the letters of another, such as `cinema`, formed from `iceman`. Your task is to detect the number of unique anagram groups in a given list of strings. Two strings belong to the same anagram group... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1071,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context:\nAn anagram is a word formed by rearranging the letters of another, such as `cinema`, formed from `iceman`. Your task is to detect the number of unique anagram groups in a given list of strings. Two strin... |
def sort_strings_desc_length(lst):
# Remove duplicates by converting to a set and then back to a list
unique_strings = list(set(lst))
# Sort the list based on the specified criteria
sorted_strings = sorted(unique_strings, key=lambda s: (-len(s), s))
return sorted_strings | simplelr_Filter | [
{
"content": "Question:\nYou are given a list of strings. Your task is to write a function that sorts the strings in descending order based on their lengths, and in case of a tie, alphabetically. Additionally, the function should remove any duplicate strings from the list before sorting. Provide a piece of code... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1072,
"level": 1,
"question": "You are given a list of strings. Your task is to write a function that sorts the strings in descending order based on their lengths, and in case of a tie, alphabetically. Additionally, the function should remove any duplicate strings from the list befo... |
def array_sum(arr):
return sum(arr) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the sum of all numbers in an array. The function should return the sum. If the array is empty, the function should return 0. If the array contains negative numbers, the function should still include them in the sum.\nAnswer:\nLet's think step by step.\n",
"r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1073,
"level": 1,
"question": "Write a function to find the sum of all numbers in an array. The function should return the sum. If the array is empty, the function should return 0. If the array contains negative numbers, the function should still include them in the sum.",
"split"... |
def transpose(matrix):
return [list(row) for row in zip(*matrix)] | simplelr_Leetcode | [
{
"content": "Question:\nGiven a `matrix` of integers with `m` rows and `n` columns, return the **transpose** of the matrix. The transpose of a matrix is defined as flipping the matrix over its main diagonal, switching the row and column indices of the matrix. For example, the transpose of the `2 x 3` matrix `[... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1074,
"level": 1,
"question": "Given a `matrix` of integers with `m` rows and `n` columns, return the **transpose** of the matrix. The transpose of a matrix is defined as flipping the matrix over its main diagonal, switching the row and column indices of the matrix. For example, the... |
def char_count(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count | simplelr_Filter | [
{
"content": "Question:\nHow can I create a function in Python that takes a string input and returns a dictionary where the keys are the characters in the string and the values are the number of times each character appears in the string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1075,
"level": 1,
"question": "How can I create a function in Python that takes a string input and returns a dictionary where the keys are the characters in the string and the values are the number of times each character appears in the string?",
"split": "train"
} |
from collections import Counter
def can_form_string(s, t):
cnt_s = Counter(s)
cnt_t = Counter(t)
for char, count in cnt_t.items():
if cnt_s.get(char, 0) < count:
return False
return True | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` and a string `t`. You want to form string `t` from `s` by removing some characters from `s` and rearranging the remaining characters. Return _true_ if it is possible to form string `t` from `s` in this way, and _false_ otherwise.\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1076,
"level": 1,
"question": "You are given a string `s` and a string `t`. You want to form string `t` from `s` by removing some characters from `s` and rearranging the remaining characters. Return _true_ if it is possible to form string `t` from `s` in this way, and _false_ otherw... |
def longest_bitonic_subsequence(arr):
n = len(arr)
if n == 0:
return 0
# Compute the inc array (longest increasing subsequence ending at each index)
inc = [1] * n
for i in range(n):
for j in range(i):
if arr[j] < arr[i]:
inc[i] = max(inc[i], inc[j] + ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `arr`. You need to identify the **longest** possible **bitonic subsequence** in `arr`. A **bitonic subsequence** is a subsequence which first increases and then, after reaching a maximum value, decreases. Note that the subsequence may also be ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1077,
"level": 1,
"question": "You are given a **0-indexed** integer array `arr`. You need to identify the **longest** possible **bitonic subsequence** in `arr`. A **bitonic subsequence** is a subsequence which first increases and then, after reaching a maximum value, decreases. Not... |
def transpose_matrix(matrix: list[list[int]]) -> list[list[int]]:
# Check if the input is a list
if not isinstance(matrix, list):
raise ValueError("transpose_matrix() received an invalid input: not a matrix")
# Check if each element is a list
for row in matrix:
if not isinstance(row... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Matrix Transposition\n\nYou are tasked with implementing a function that transposes a given matrix. The function should handle both square and rectangular matrices, including edge cases and input validation appropriately.\n\nTransposing a matrix involves swapping its rows ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1078,
"level": 1,
"question": "### Question: Matrix Transposition\n\nYou are tasked with implementing a function that transposes a given matrix. The function should handle both square and rectangular matrices, including edge cases and input validation appropriately.\n\nTransposing a... |
def gcd(a, b):
if a == 0 and b == 0:
return 0
a = abs(a)
b = abs(b)
while b != 0:
a, b = b, a % b
return a | simplelr_Filter | [
{
"content": "Question:\nQ3 Write a Python function `gcd(a, b)` to find the Greatest Common Divisor of two integers a and b using the Euclidean\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1079,
"level": 1,
"question": "Q3 Write a Python function `gcd(a, b)` to find the Greatest Common Divisor of two integers a and b using the Euclidean",
"split": "train"
} |
def longest_common_subsequence(s1, s2):
m = len(s1)
n = len(s2)
# Create a DP table with (m+1) rows and (n+1) columns
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Fill the DP table
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i-1] == s2[j-1]:
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the longest common subsequence between two strings. The function should take two string parameters and return the longest common subsequence as a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1080,
"level": 1,
"question": "Write a python function to find the longest common subsequence between two strings. The function should take two string parameters and return the longest common subsequence as a string.",
"split": "train"
} |
def max_of_two(a, b):
return max(a, b) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two numbers a and b as parameters. The function should return the maximum of a and b.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1081,
"level": 1,
"question": "Create a function that takes two numbers a and b as parameters. The function should return the maximum of a and b.",
"split": "train"
} |
from typing import List
def trap(height: List[int]) -> int:
if not height:
return 0
n = len(height)
left = 0
right = n - 1
left_max = right_max = 0
res = 0
while left < right:
if height[left] < height[right]:
if height[left] > left_max:
left_max =... | simplelr_Taco | [
{
"content": "Question:\n***Question:*** \nYou are given an array of integers representing the heights of buildings in a row. The goal is to trap as much rainwater as possible after it rains. Write a function that calculates the maximum amount of trapped water.\n\nThe way to trap water is to find the elevation... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1082,
"level": 1,
"question": "***Question:*** \nYou are given an array of integers representing the heights of buildings in a row. The goal is to trap as much rainwater as possible after it rains. Write a function that calculates the maximum amount of trapped water.\n\nThe way to ... |
from typing import List, Optional
def average_feedback(scores: List[Optional[int]]) -> float:
total = 0
count = 0
for score in scores:
if score is not None:
total += score
count += 1
if count == 0:
return 0.0
average = total / count
return round(average, ... | simplelr_Taco | [
{
"content": "Question:\nA company wants to implement a system for tracking customer feedback. They receive feedback scores from customers on a daily basis, but due to server issues, they often lose some of the data. They want to estimate the average feedback score for a set number of consecutive days, but they... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1083,
"level": 1,
"question": "A company wants to implement a system for tracking customer feedback. They receive feedback scores from customers on a daily basis, but due to server issues, they often lose some of the data. They want to estimate the average feedback score for a set n... |
import re
def is_palindrome(s):
# Remove all non-alphanumeric characters and convert to lowercase
cleaned = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
# Check if the cleaned string is a palindrome
return cleaned == cleaned[::-1] | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a string as input and returns true if the string is a palindrome (a word, phrase, number, or other sequences of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization) and false otherwise. The function should ign... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1084,
"level": 1,
"question": "Write a function that takes a string as input and returns true if the string is a palindrome (a word, phrase, number, or other sequences of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization) and false... |
import torch.distributed.elastic.events as events
def log_training_event(iteration_number: int, loss_value: float, additional_metadata: dict):
# Create the metadata with required fields
metadata = {
'iteration_number': iteration_number,
'loss_value': loss_value
}
# Update with additiona... | simplelr_Docs | [
{
"content": "Question:\n### PyTorch Distributed Event Handling\n\n#### Objective\nIn this task, you will be required to implement a function to handle and log events in a distributed PyTorch environment using the `torch.distributed.elastic.events` API.\n\n#### Description\nWrite a function `log_training_event`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1085,
"level": 1,
"question": "### PyTorch Distributed Event Handling\n\n#### Objective\nIn this task, you will be required to implement a function to handle and log events in a distributed PyTorch environment using the `torch.distributed.elastic.events` API.\n\n#### Description\nWr... |
def sum_list(lst):
return sum(lst) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers as input and returns the sum of all the integers in the list. Use the `sum` function in Python to compute the sum. Name the function `sum_list`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1086,
"level": 1,
"question": "Write a Python function that takes a list of integers as input and returns the sum of all the integers in the list. Use the `sum` function in Python to compute the sum. Name the function `sum_list`.",
"split": "train"
} |
def convert_tuples_to_dict_list(tuple_list):
return [{'a': t[0], 'b': t[1], 'c': t[2]} for t in tuple_list] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of tuples as input and returns a list of dictionaries, where each tuple is converted into a dictionary with keys 'a', 'b', and 'c'. Each tuple should have exactly three elements.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1087,
"level": 1,
"question": "Write a Python function that takes a list of tuples as input and returns a list of dictionaries, where each tuple is converted into a dictionary with keys 'a', 'b', and 'c'. Each tuple should have exactly three elements.",
"split": "train"
} |
def find_nth_digit(n: int) -> int:
digits = 1
count = 9
start = 1
while n > digits * count:
n -= digits * count
digits += 1
count *= 10
start *= 10
number = start + (n - 1) // digits
digit_index = (n - 1) % digits
return int(str(number)[digit_index]) | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Find the nth Digit in an Infinite Integer Sequence\n\n#### Scenario:\nWrite a function `find_nth_digit(n: int) -> int` that takes an integer `n` and returns the nth digit of an infinite concatenated sequence of positive integers: \"123456789101112...\". The sequence starts... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1088,
"level": 1,
"question": "### Question: Find the nth Digit in an Infinite Integer Sequence\n\n#### Scenario:\nWrite a function `find_nth_digit(n: int) -> int` that takes an integer `n` and returns the nth digit of an infinite concatenated sequence of positive integers: \"123456... |
def is_divisible_by_3(num):
if num % 3 == 0:
return "Divisible"
else:
return "Not Divisible" | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer and returns whether it is divisible by 3 or not. If it is, return \"Divisible\", otherwise return \"Not Divisible\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1089,
"level": 1,
"question": "Create a function that takes an integer and returns whether it is divisible by 3 or not. If it is, return \"Divisible\", otherwise return \"Not Divisible\".",
"split": "train"
} |
def longest_common_substring_length(s1, s2):
n = len(s1)
m = len(s2)
dp = [[0] * (m + 1) for _ in range(n + 1)]
max_len = 0
for i in range(1, n + 1):
for j in range(1, m + 1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
if dp[i][j] > max_len... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings `s1` and `s2`. Write a function that returns _the length of the longest common substring of_ `s1` _and_ `s2`. A substring is a contiguous sequence of characters within a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1090,
"level": 1,
"question": "You are given two strings `s1` and `s2`. Write a function that returns _the length of the longest common substring of_ `s1` _and_ `s2`. A substring is a contiguous sequence of characters within a string.",
"split": "train"
} |
def compress_string(s: str) -> str:
if not isinstance(s, str):
raise TypeError("input must be a string")
if len(s) == 0:
raise TypeError("input must be a non-empty string")
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question: Implement String Compression\n\n#### Context\nYou have been tasked with creating a function that compresses a string using run-length encoding (RLE). This technique is useful for reducing the size of repetitive data, making it more efficient for storage and transmis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1091,
"level": 1,
"question": "### Coding Question: Implement String Compression\n\n#### Context\nYou have been tasked with creating a function that compresses a string using run-length encoding (RLE). This technique is useful for reducing the size of repetitive data, making it more... |
def is_rotation(list1, list2):
if len(list1) != len(list2):
return False
if not list1:
return True
# Create the doubled list and its string representation
doubled_list = list1 + list1
str_doubled = ','.join(map(str, doubled_list))
str2 = ','.join(map(str, list2))
return str2 ... | simplelr_Filter | [
{
"content": "Question:\nI have two lists of integers. I want to check if one is a rotation of the other. For example, [1, 2, 3] and [3, 1, 2] are rotations of each other.\n\nHere's my current implementation:\n\n```python\ndef is_rotation(list1, list2):\n if len(list1) != len(list2):\n return False\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1092,
"level": 1,
"question": "I have two lists of integers. I want to check if one is a rotation of the other. For example, [1, 2, 3] and [3, 1, 2] are rotations of each other.\n\nHere's my current implementation:\n\n```python\ndef is_rotation(list1, list2):\n if len(list1) != l... |
def reverse_string(input_string: str) -> str:
return input_string[::-1] | simplelr_Evol | [
{
"content": "Question:\nWrite a function `reverse_string(input_string: str) -> str` that takes a string as input and returns the string reversed. \n\nFor example, given the input `hello world`, the function should return `dlrow olleh`.\n\nAdditionally, ensure the function handles the following cases:\n- If the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1093,
"level": 1,
"question": "Write a function `reverse_string(input_string: str) -> str` that takes a string as input and returns the string reversed. \n\nFor example, given the input `hello world`, the function should return `dlrow olleh`.\n\nAdditionally, ensure the function han... |
def are_permutations(str1, str2):
if len(str1) != len(str2):
return False
return sorted(str1) == sorted(str2) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if one string is a permutation of another string. You should include a brief description of your approach and identify any assumptions you or the question do not clarify. The function should return `True` if the strings are permutations of each other and `F... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1094,
"level": 1,
"question": "Create a function that checks if one string is a permutation of another string. You should include a brief description of your approach and identify any assumptions you or the question do not clarify. The function should return `True` if the strings ar... |
from typing import List, Tuple
def missing_ranges(arr: List[int], lo: int, hi: int) -> List[Tuple[int, int]]:
if lo > hi:
return []
if not arr:
return [(lo, hi)] if lo <= hi else []
result = []
prev = lo - 1
for num in arr:
if num > hi:
break
if num ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Missing Ranges\n\nOne common problem in numerical sequences is finding the gaps within a specified range. Given a sorted list of integers and two boundary values `lo` and `hi`, your task is to find all missing ranges that fall between these two boundaries.\n\n#### Function Signature... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1095,
"level": 1,
"question": "### Missing Ranges\n\nOne common problem in numerical sequences is finding the gaps within a specified range. Given a sorted list of integers and two boundary values `lo` and `hi`, your task is to find all missing ranges that fall between these two bou... |
def get_complementary_dna(dna):
tr_table = str.maketrans('ATCG', 'TAGC')
return dna.translate(tr_table) | simplelr_Filter | [
{
"content": "Question:\n# Define a function that takes a DNA sequence as a string as input and returns the complementary DNA sequence.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1096,
"level": 1,
"question": "# Define a function that takes a DNA sequence as a string as input and returns the complementary DNA sequence.",
"split": "train"
} |
import bisect
def max_nested_rectangles(height, width):
rectangles = list(zip(height, width))
# Sort by height ascending, then by width descending
rectangles.sort(key=lambda x: (x[0], -x[1]))
w_list = [r[1] for r in rectangles]
tails = []
for num in w_list:
idx = bisect.bisect_left... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two arrays `height` and `width` where `height[i]` and `width[i]` represent the height and width of the `i-th` rectangle, respectively. A rectangle can be placed inside another rectangle if and only if both the height and width of one rectangle are strictly greater than the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1097,
"level": 1,
"question": "You are given two arrays `height` and `width` where `height[i]` and `width[i]` represent the height and width of the `i-th` rectangle, respectively. A rectangle can be placed inside another rectangle if and only if both the height and width of one rect... |
def union_lists(list1, list2):
return list(set(list1) | set(list2)) | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes two lists and returns their union (i.e., a list of all unique elements present in at least one of the lists).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1098,
"level": 1,
"question": "Write a function in Python that takes two lists and returns their union (i.e., a list of all unique elements present in at least one of the lists).",
"split": "train"
} |
def longest_common_subsequence(seq1: str, seq2: str) -> str:
m = len(seq1)
n = len(seq2)
if m == 0 or n == 0:
return ""
# Initialize the DP table with (m+1) rows and (n+1) columns
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Fill the DP table
for i in range(1, m + 1):
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assignment: Design a Dynamic Programming Solution for the Longest Common Subsequence\n\n#### Scenario\nYou are a software developer at a tech company that deals with large datasets. One of your tasks is to compare genetic sequences in the company's bioinformatics department. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1099,
"level": 1,
"question": "### Coding Assignment: Design a Dynamic Programming Solution for the Longest Common Subsequence\n\n#### Scenario\nYou are a software developer at a tech company that deals with large datasets. One of your tasks is to compare genetic sequences in the co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.