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 binary_search_2d(matrix, target): if not matrix or not matrix[0]: return -1 m = len(matrix) n = len(matrix[0]) total = m * n low = 0 high = total - 1 while low <= high: mid = (low + high) // 2 mid_row = mid // n mid_col = mid % n mid_val = matrix[m...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to search for a specific value in a two-dimensional array using a binary search algorithm. The function should return the row and column indices of the value if it is found. If the value is not found, the function should return -1.\nAnswer:\nLet's think step by step.\n"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7900, "level": 1, "question": "Write a function to search for a specific value in a two-dimensional array using a binary search algorithm. The function should return the row and column indices of the value if it is found. If the value is not found, the function should return -1.", ...
def split_path(path: str) -> [str, str]: sep_pos = -1 for i in range(len(path)-1, -1, -1): if path[i] in ('/', '\\'): sep_pos = i break if sep_pos == -1: return ["", path] if path else ["", ""] else: base = path[:sep_pos] component = path[sep_pos+1...
simplelr_Data_Structure
[ { "content": "Question:\n### Path Splitting Function for Various File Systems\n\nYou've been asked to implement a robust function that splits a given path into two parts: the base path and the final component. This scenario is common in file system management and URL parsing.\n\n#### Input\n* A single string `p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7901, "level": 1, "question": "### Path Splitting Function for Various File Systems\n\nYou've been asked to implement a robust function that splits a given path into two parts: the base path and the final component. This scenario is common in file system management and URL parsing.\...
def trimmean(arr, per): arr_sorted = sorted(arr) n = len(arr_sorted) k = (per / 200.0) * n k = round(k) start = k end = n - k selected = arr_sorted[start:end] if not selected: return 0.0 total = sum(selected) count = len(selected) return total / count
simplelr_Data_Structure
[ { "content": "Question:\n### Trimmed Mean Calculation\n\nYou are tasked to implement a trimmed mean calculation for a set of data points. The trimmed mean is a measure of central tendency where you remove a specified percentage of the lowest and highest values from the dataset and then calculate the average of ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7902, "level": 1, "question": "### Trimmed Mean Calculation\n\nYou are tasked to implement a trimmed mean calculation for a set of data points. The trimmed mean is a measure of central tendency where you remove a specified percentage of the lowest and highest values from the dataset...
from bisect import bisect_right from typing import List def find_smallest_letter(letters: List[str], target: str) -> str: pos = bisect_right(letters, target) if pos == len(letters): return letters[0] return letters[pos]
simplelr_Data_Structure
[ { "content": "Question:\n### Question: Find the Smallest Letter Greater Than Target\n\nGiven a sorted list of characters `letters` containing only lowercase letters, and a target character `target`, write a function `find_smallest_letter` to find the smallest element in the list that is larger than the given ta...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7903, "level": 1, "question": "### Question: Find the Smallest Letter Greater Than Target\n\nGiven a sorted list of characters `letters` containing only lowercase letters, and a target character `target`, write a function `find_smallest_letter` to find the smallest element in the li...
def compound_interest(P, r, t, n=1): """ Calculate the compound interest amount. Args: P (float): The principal amount. r (float): Annual interest rate (decimal). t (float): Number of years. n (int, optional): Number of times interest is compounded per year. Defaults to 1. ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to calculate compound interest for a given principal amount, interest rate, and number of years.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7904, "level": 1, "question": "Write a python function to calculate compound interest for a given principal amount, interest rate, and number of years.", "split": "train" }
def custom_pigeonhole_sort(arr: list[int]) -> list[int]: if not arr: return [] min_val = min(arr) max_val = max(arr) if min_val == max_val: return arr.copy() size = max_val - min_val + 1 pigeonholes = [0] * size for num in arr: index = num - min_va...
simplelr_Data_Structure
[ { "content": "Question:\nYou are provided with an unsorted list of integers. Your task is to implement a function `custom_pigeonhole_sort` which sorts the list using the pigeonhole sorting algorithm. This algorithm works especially well when the range of integer values in the list is few. Additionally, you must...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7905, "level": 1, "question": "You are provided with an unsorted list of integers. Your task is to implement a function `custom_pigeonhole_sort` which sorts the list using the pigeonhole sorting algorithm. This algorithm works especially well when the range of integer values in the ...
def is_valid_number_string(s: str) -> bool: n = len(s) if n == 0: return False dp = [False] * (n + 1) dp[0] = True # Empty string is a valid starting point for i in range(1, n + 1): for j in range(i): if dp[j]: substr = s[j:i] # Check...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` which contains only digits. We call a string valid if it can be obtained by concatenating one or more positive integers, each without leading zeros. For example, \"1234\" is valid because it can be decomposed into \"1\", \"2\", \"3\", \"4\"; \"12\", \"34\"; \"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7906, "level": 1, "question": "You are given a string `s` which contains only digits. We call a string valid if it can be obtained by concatenating one or more positive integers, each without leading zeros. For example, \"1234\" is valid because it can be decomposed into \"1\", \"2\...
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
simplelr_Filter
[ { "content": "Question:\nWrite a short paragraph explaining the concept of recursion in programming, and provide a simple example in Python.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7907, "level": 1, "question": "Write a short paragraph explaining the concept of recursion in programming, and provide a simple example in Python.", "split": "train" }
def find_pair(nums, target): """ Find the first pair of numbers in the array that add up to a given target sum. The function efficiently checks each number in the list and keeps track of previously seen numbers using a set. For each number, it calculates the complement needed to reach the target sum an...
simplelr_Filter
[ { "content": "Question:\nGiven an array of integers, return the first pair of numbers in the array that add up to a given target sum.\n\nExample:\nInput: [1, 2, 3, 4, 5], 9\nOutput: [4, 5]\n\nHere is the code:\n```python\ndef find_pair(nums, target):\n \"\"\"\n Find the first pair of numbers in the array ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7908, "level": 1, "question": "Given an array of integers, return the first pair of numbers in the array that add up to a given target sum.\n\nExample:\nInput: [1, 2, 3, 4, 5], 9\nOutput: [4, 5]\n\nHere is the code:\n```python\ndef find_pair(nums, target):\n \"\"\"\n Find the ...
def max_sum_of_mins(nums, k): nums_sorted = sorted(nums) return sum(nums_sorted[:k])
simplelr_Leetcode
[ { "content": "Question:\nYou are given an integer array `nums` and an integer `k`. Your task is to split `nums` into `k` non-empty subarrays such that the sum of the minimum values of each subarray is maximized. Return the maximum possible sum of the minimum values of the `k` subarrays.\n\n* Example: `nums = [1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7909, "level": 1, "question": "You are given an integer array `nums` and an integer `k`. Your task is to split `nums` into `k` non-empty subarrays such that the sum of the minimum values of each subarray is maximized. Return the maximum possible sum of the minimum values of the `k` ...
from typing import List def find_missing_number(arr: List[int]) -> int: n = len(arr) + 1 expected_sum = n * (n + 1) // 2 actual_sum = sum(arr) return expected_sum - actual_sum
simplelr_Apps
[ { "content": "Question:\nYou are given an array of unique integers where each integer lies in the range [1, n], where n is the length of the array. Some integer k has been removed from this array, making it have n-1 elements. You need to identify and return the missing integer k.\n\nWrite a function:\n\n```pyth...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7910, "level": 1, "question": "You are given an array of unique integers where each integer lies in the range [1, n], where n is the length of the array. Some integer k has been removed from this array, making it have n-1 elements. You need to identify and return the missing integer...
def factorial(n): if type(n) is not int: raise TypeError("Input must be an integer.") if n < 0: raise ValueError("Input must be a non-negative integer.") result = 1 for i in range(1, n + 1): result *= i return result
simplelr_Filter
[ { "content": "Question:\nCreate a function that calculates the factorial of a number with an added functionality of handling extremely large inputs without integer overflow. Also, incorporate error checking for negative numbers and non-integer types.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7911, "level": 1, "question": "Create a function that calculates the factorial of a number with an added functionality of handling extremely large inputs without integer overflow. Also, incorporate error checking for negative numbers and non-integer types.", "split": "train" }
def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n - 1)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that calculates the factorial of a given number using recursion. Provide a detailed explanation of each step involved in the function.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7912, "level": 1, "question": "Create a function that calculates the factorial of a given number using recursion. Provide a detailed explanation of each step involved in the function.", "split": "train" }
def spiral_traversal(grid): if not grid: return [] rows = len(grid) cols = len(grid[0]) top = 0 bottom = rows - 1 left = 0 right = cols - 1 result = [] while top <= bottom and left <= right: # Traverse top row from left to right for i in ra...
simplelr_Filter
[ { "content": "Question:\nHere's a 2D array of 0s and 1s, let's say it's 10x10 grid. How can you traverse the grid in such a way that you visit every cell at least once while printing out all the cell values.\n\nOne approach is to simply iterate through everything to create a linear scan. However, a more excitin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7913, "level": 1, "question": "Here's a 2D array of 0s and 1s, let's say it's 10x10 grid. How can you traverse the grid in such a way that you visit every cell at least once while printing out all the cell values.\n\nOne approach is to simply iterate through everything to create a l...
def edit_distance(str1: str, str2: str) -> int: len1 = len(str1) len2 = len(str2) # Create a DP table with (len1+1) rows and (len2+1) columns dp = [[0] * (len2 + 1) for _ in range(len1 + 1)] # Initialize the first row and column for i in range(len1 + 1): dp[i][0] = i for j ...
simplelr_Algorithm
[ { "content": "Question:\n### Question: String Edit Distance\n\nYou are given two strings `str1` and `str2`. Your task is to implement a function to compute the minimum number of operations required to convert `str1` into `str2`. The allowed operations are insertion, deletion, or substitution of a single charact...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7914, "level": 1, "question": "### Question: String Edit Distance\n\nYou are given two strings `str1` and `str2`. Your task is to implement a function to compute the minimum number of operations required to convert `str1` into `str2`. The allowed operations are insertion, deletion, ...
def word_pattern(pattern: str, string: str) -> bool: words = string.split() if len(words) != len(pattern): return False p_map = {} w_map = {} for p_char, word in zip(pattern, words): if p_char in p_map: if p_map[p_char] != word: return False else: ...
simplelr_Data_Structure
[ { "content": "Question:\n<|Analysis Begin|>\n\n### Algorithm/Data Structure Identification\n\n* **Algorithm**: Pattern Matching\n* **Type**: Hash Table based mapping\n* **Purpose**: The given algorithm checks if a string `str` follows a specified pattern `pattern`. This means each character in the pattern shoul...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7915, "level": 1, "question": "<|Analysis Begin|>\n\n### Algorithm/Data Structure Identification\n\n* **Algorithm**: Pattern Matching\n* **Type**: Hash Table based mapping\n* **Purpose**: The given algorithm checks if a string `str` follows a specified pattern `pattern`. This means ...
from datetime import datetime def find_closest_date(date_array, date_string): if not date_array: return -1 target = datetime.strptime(date_string, "%Y-%m-%d") min_diff = None min_index = 0 for index, date_str in enumerate(date_array): current_date = datetime.strptime(date_...
simplelr_Filter
[ { "content": "Question:\nI have an array of strings where each string represents a date in the format \"YYYY-MM-DD\". I want to write a function that takes this array and a date string as input, and returns the index of the date in the array that is closest to the given date string. If the array is empty, it sh...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7916, "level": 1, "question": "I have an array of strings where each string represents a date in the format \"YYYY-MM-DD\". I want to write a function that takes this array and a date string as input, and returns the index of the date in the array that is closest to the given date s...
def minTravelTime(n, m, edges): INF = float('inf') # Initialize distance matrix with INF distance = [[INF for _ in range(n)] for _ in range(n)] for i in range(n): distance[i][i] = 0 # Fill the distance matrix with the minimal edges for u, v, w in edges: u -= 1 # conver...
simplelr_Taco
[ { "content": "Question:\nIn a certain city, there are n intersections connected by m bidirectional roads. Each road has an associated travel time. A tourist wants to explore the city starting from one intersection and visiting all other intersections exactly once before returning to the starting point. This pro...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7917, "level": 1, "question": "In a certain city, there are n intersections connected by m bidirectional roads. Each road has an associated travel time. A tourist wants to explore the city starting from one intersection and visiting all other intersections exactly once before return...
def divide_and_remainder(dividend: float, divisor: float) -> tuple: if divisor == 0: return None # Division by zero is undefined quotient = dividend // divisor remainder = dividend - quotient * divisor return (quotient, remainder)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes two numbers and returns the quotient and the remainder.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7918, "level": 1, "question": "Create a function that takes two numbers and returns the quotient and the remainder.", "split": "train" }
def smallest_integer_with_digit_sum(n): m = (n - 1) // 9 + 1 s = n - 9 * (m - 1) return int(str(s) + '9' * (m - 1))
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer `n` (1 <= n <= 10^9), return the smallest integer `k` such that the sum of the digits of `k` is equal to `n`. If there are multiple valid answers, return the smallest one.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7919, "level": 1, "question": "Given an integer `n` (1 <= n <= 10^9), return the smallest integer `k` such that the sum of the digits of `k` is equal to `n`. If there are multiple valid answers, return the smallest one.", "split": "train" }
from itertools import groupby def sort_and_remove_duplicates(lst): sorted_lst = sorted(lst) return [key for key, _ in groupby(sorted_lst)]
simplelr_Filter
[ { "content": "Question:\nI have a Python list of integers that I want to sort in ascending order, but I also want to ensure that the integers are unique. Here's how I've attempted to do this so far:\n\n```python\ndef sort_and_remove_duplicates(lst):\n lst.sort()\n return list(set(lst))\n```\n\nHowever, wh...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7920, "level": 1, "question": "I have a Python list of integers that I want to sort in ascending order, but I also want to ensure that the integers are unique. Here's how I've attempted to do this so far:\n\n```python\ndef sort_and_remove_duplicates(lst):\n lst.sort()\n return...
def bubble_sort(arr): arr = arr.copy() n = len(arr) for i in range(n): swapped = False for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] swapped = True if not swapped: break return...
simplelr_Filter
[ { "content": "Question:\nWrite a Python program to implement bubble sort.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7921, "level": 1, "question": "Write a Python program to implement bubble sort.", "split": "train" }
def diamond(n): if n % 2 == 0: return "" m = (n - 1) // 2 result = [] for i in range(n): d = abs(i - m) stars = 1 + 2 * (m - d) leading_spaces = (n - stars) // 2 line = ' ' * leading_spaces + '*' * stars result.append(line) return '\n'.join(result)
simplelr_Apps
[ { "content": "Question:\nWrite a function **diamond(n)** that generates a diamond-shaped pattern given an odd number **n**. The diamond has the widest part in the middle row, and each row has increasing stars up to the middle row and then decreasing. The function should return the pattern as a string.\n\n## Kee...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7922, "level": 1, "question": "Write a function **diamond(n)** that generates a diamond-shaped pattern given an odd number **n**. The diamond has the widest part in the middle row, and each row has increasing stars up to the middle row and then decreasing. The function should return...
def subarray_sum_greater_than_x(arr, x): if len(arr) < 3: return False for i in range(len(arr) - 2): current_sum = arr[i] + arr[i+1] + arr[i+2] if current_sum > x: return True return False
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of integers `arr` and an integer `x`. Your task is to determine if there exists a subarray of `arr` with length `3` whose sum is greater than `x`. A subarray is a contiguous part of an array. Return _`True`_ if such a subarray exists, and _`False`_ otherwise.\nAns...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7923, "level": 1, "question": "You are given an array of integers `arr` and an integer `x`. Your task is to determine if there exists a subarray of `arr` with length `3` whose sum is greater than `x`. A subarray is a contiguous part of an array. Return _`True`_ if such a subarray ex...
import dbm from typing import List, Tuple, Union, Dict def manage_database(file_name: str, operations: List[Tuple[str, Union[str, Tuple[str, str]]]]) -> Dict[str, Union[str, bool]]: result = {} with dbm.open(file_name, 'c') as db: for op in operations: op_type, op_data = op[0], op[1] ...
simplelr_Docs
[ { "content": "Question:\n**Coding Assessment Question: Advanced Database Operations with the `dbm` Module**\n\n**Objective**: Demonstrate your understanding of Python's `dbm` module by implementing a function that performs various database operations.\n\n### Task\n\nYou are required to implement a function `man...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7924, "level": 1, "question": "**Coding Assessment Question: Advanced Database Operations with the `dbm` Module**\n\n**Objective**: Demonstrate your understanding of Python's `dbm` module by implementing a function that performs various database operations.\n\n### Task\n\nYou are re...
def common_elements(list1, list2): return list(set(list1) & set(list2))
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes two lists as inputs and returns a new list that contains the common elements from both lists, without duplicates. How can you implement this in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7925, "level": 1, "question": "Create a function that takes two lists as inputs and returns a new list that contains the common elements from both lists, without duplicates. How can you implement this in Python?", "split": "train" }
from typing import List def summarize_ranges(array: List[int]) -> List[str]: if not array: return [] result = [] start = array[0] end = array[0] for num in array[1:]: if num == end + 1: end = num else: # Add the current range to the result ...
simplelr_Data_Structure
[ { "content": "Question:\n#### Objective\nWrite a function `summarize_ranges` that summarizes ranges of consecutive integers from a given sorted array of unique integers.\n\n#### Scenario\nYou are tasked with compressing a large dataset for ease of readability and storage. The dataset consists of a sorted list o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7926, "level": 1, "question": "#### Objective\nWrite a function `summarize_ranges` that summarizes ranges of consecutive integers from a given sorted array of unique integers.\n\n#### Scenario\nYou are tasked with compressing a large dataset for ease of readability and storage. The ...
def longest_substring_with_n_distinct_chars(n, s): if n == 0: return "" max_len = 0 result_start = 0 result_end = 0 char_count = {} left = 0 count = 0 # Number of distinct characters in the current window for right in range(len(s)): c = s[right] if c not in char...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in two parameters, an integer n and a string s, and returns the longest substring of s that contains exactly n distinct characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7927, "level": 1, "question": "Create a function that takes in two parameters, an integer n and a string s, and returns the longest substring of s that contains exactly n distinct characters.", "split": "train" }
def exchange_sort(arr): if not arr: return [] arr_copy = arr.copy() n = len(arr_copy) for i in range(n): swapped = False for j in range(n - 1 - i): if arr_copy[j] > arr_copy[j + 1]: # Swap elements arr_copy[j], arr_copy[j + 1] = arr_cop...
simplelr_Data_Structure
[ { "content": "Question:\n#### Scenario\nYou have been tasked with implementing a library that includes multiple sorting algorithms to be used in various parts of your company's software. As part of this library, one of the requirements is to have a basic implementation of Exchange Sort for educational purposes ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7928, "level": 1, "question": "#### Scenario\nYou have been tasked with implementing a library that includes multiple sorting algorithms to be used in various parts of your company's software. As part of this library, one of the requirements is to have a basic implementation of Exch...
def movie_schedule(schedule): days = schedule.split() result = [] for i in range(7): start_index = i * 2 end_index = start_index + 1 if start_index < len(days) and end_index < len(days): result.append((days[start_index], days[end_index])) else: result....
simplelr_Filter
[ { "content": "Question:\nThis problem involves reading a weekly schedule for a movie theater and identifying the start and end times of movies. The weekly schedule is represented as a string of characters where each pair of characters represents a time in the format \"hh:mm\" where \"hh\" is the hour and \"mm\"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7929, "level": 1, "question": "This problem involves reading a weekly schedule for a movie theater and identifying the start and end times of movies. The weekly schedule is represented as a string of characters where each pair of characters represents a time in the format \"hh:mm\" ...
def reverse_digits(n): is_negative = n < 0 if is_negative: n = -n reversed_n = int(str(n)[::-1]) if is_negative: reversed_n = -reversed_n return reversed_n
simplelr_Prefill
[ { "content": "Question:\nCreate a function that accepts an integer `n` and return the integer with digits in reverse order. For example, if the input is `123`, the function should return `321`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7930, "level": 1, "question": "Create a function that accepts an integer `n` and return the integer with digits in reverse order. For example, if the input is `123`, the function should return `321`.", "split": "train" }
import heapq def dijkstra(graph, start_node): if start_node not in graph: raise ValueError("Start node not found in the graph") # Initialize distances to infinity for all nodes distances = {node: float('infinity') for node in graph} distances[start_node] = 0 # Priority queue: (dis...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to implement Dijkstra's algorithm for finding the shortest path in a graph.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7931, "level": 1, "question": "Write a python function to implement Dijkstra's algorithm for finding the shortest path in a graph.", "split": "train" }
def extract_alphanumeric_words(s: str) -> list: words = s.split() result = [] for word in words: has_alpha = any(c.isalpha() for c in word) has_digit = any(c.isdigit() for c in word) if has_alpha and has_digit: result.append(word) return result
simplelr_Apps
[ { "content": "Question:\nConsider a string comprising words separated by spaces, where each word contains a mix of alphabetic characters and digits. Write a function that extracts all words containing both alphabetic characters and digits and returns them in a list. Words from the input string should be preserv...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7932, "level": 1, "question": "Consider a string comprising words separated by spaces, where each word contains a mix of alphabetic characters and digits. Write a function that extracts all words containing both alphabetic characters and digits and returns them in a list. Words from...
def trap(heights): if not heights: return 0 left = 0 right = len(heights) - 1 left_max = 0 right_max = 0 total_water = 0 while left <= right: if heights[left] <= heights[right]: if heights[left] >= left_max: left_max = heights[left] els...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of `n` integers representing an elevation map where the width of each bar is 1. Suppose each integer represents the height of a bar at an index position along the list. The elevation map describes a series of units of water trapped after rainfall at various position...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7933, "level": 1, "question": "You are given a list of `n` integers representing an elevation map where the width of each bar is 1. Suppose each integer represents the height of a bar at an index position along the list. The elevation map describes a series of units of water trapped...
from collections import deque def find_first_non_repeating_char(string): char_queue = deque() in_queue = set() # Tracks characters currently in the queue duplicates = set() # Tracks characters that have duplicates for char in string: if char in duplicates: continue if cha...
simplelr_Filter
[ { "content": "Question:\nIn this problem you have to find the first non-repeating character in a string and return it. \nFor example if you have the string \"aabbc\" you should return 'a'. \nBut there are cases when there's no unique character so you should return a special value like None.\n\n### Constraints\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7934, "level": 1, "question": "In this problem you have to find the first non-repeating character in a string and return it. \nFor example if you have the string \"aabbc\" you should return 'a'. \nBut there are cases when there's no unique character so you should return a special va...
def maxNonOverlappingProjects(projects): # Sort projects by their end times projects.sort(key=lambda x: x[1]) count = 0 last_end = -float('inf') for project in projects: start, end = project if start >= last_end: count += 1 last_end = end re...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of `projects` where each project is represented as a tuple `(start, end)`. The `start` and `end` are the starting and ending times of the project, respectively. You need to schedule the projects in such a way that the maximum number of non-overlapping projects can b...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7935, "level": 1, "question": "You are given a list of `projects` where each project is represented as a tuple `(start, end)`. The `start` and `end` are the starting and ending times of the project, respectively. You need to schedule the projects in such a way that the maximum numbe...
def max_diff(arr): if not arr or len(arr) < 2: return 0 min_so_far = arr[0] max_diff = 0 for num in arr[1:]: current_diff = num - min_so_far if current_diff > max_diff: max_diff = current_diff if num < min_so_far: min_so_far = num ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the maximum difference between two elements in an array, where the smaller element appears before the larger element.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7936, "level": 1, "question": "Write a python function to find the maximum difference between two elements in an array, where the smaller element appears before the larger element.", "split": "train" }
def longestUniqueSubstring(s): char_index = {} max_length = 0 left = 0 for right in range(len(s)): char = s[right] if char in char_index: left = max(left, char_index[char] + 1) char_index[char] = right current_length = right - left + 1 if current_lengt...
simplelr_Leetcode
[ { "content": "Question:\nImplement a function `longestUniqueSubstring(s)` that receives a string `s` and returns the length of the longest substring without repeating characters. For instance, given the input `s = \"pwwkew\"`, the output should be `3` because the longest substring without repeating characters i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7937, "level": 1, "question": "Implement a function `longestUniqueSubstring(s)` that receives a string `s` and returns the length of the longest substring without repeating characters. For instance, given the input `s = \"pwwkew\"`, the output should be `3` because the longest subst...
def max_product(nums): if not nums: return 0 global_max = current_max = current_min = nums[0] for num in nums[1:]: temp_max = max(num, current_max * num, current_min * num) temp_min = min(num, current_max * num, current_min * num) current_max, current_min = temp_max, temp_min...
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers, your task is to determine the maximum product of any contiguous subarray. The given array may have both positive and negative integers, and its size will be in the range 1-100.\n\nFirst Example:\n\nInput: [2, 3, -2, 4]\n\nSteps: The contiguous subarrays are:\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7938, "level": 1, "question": "Given an array of integers, your task is to determine the maximum product of any contiguous subarray. The given array may have both positive and negative integers, and its size will be in the range 1-100.\n\nFirst Example:\n\nInput: [2, 3, -2, 4]\n\nSt...
def add_lists_elementwise(list1, list2): if len(list1) != len(list2): return None return [x + y for x, y in zip(list1, list2)]
simplelr_Filter
[ { "content": "Question:\nWrite a Python code snippet to add two lists of numbers element-wise and return a new list with the results. If the lists are of unequal lengths, return None instead.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7939, "level": 1, "question": "Write a Python code snippet to add two lists of numbers element-wise and return a new list with the results. If the lists are of unequal lengths, return None instead.", "split": "train" }
def is_palindrome(s): # Clean the string by keeping only alphanumeric characters and converting to lowercase cleaned = [c.lower() for c in s if c.isalnum()] cleaned_str = ''.join(cleaned) # Check if the cleaned string is equal to its reverse return cleaned_str == cleaned_str[::-1]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that returns `True` if the given string is a palindrome and `False` otherwise. A palindrome is a string that reads the same backward as forward, ignoring spaces, punctuation, and capitalization.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7940, "level": 1, "question": "Create a function that returns `True` if the given string is a palindrome and `False` otherwise. A palindrome is a string that reads the same backward as forward, ignoring spaces, punctuation, and capitalization.", "split": "train" }
def find_students_below_threshold(students, threshold): result = [] for student in students: grades = student['grades'] average = sum(grades) / len(grades) if average < threshold: result.append(student['name']) return result
simplelr_Taco
[ { "content": "Question:\nAnalyze a list of student grades and identify students who need improvement.\n\nEach student is represented by a dictionary containing their name and a list of grades. You will write a program that flags students whose average grade is below a specified threshold.\n\nStudent grades are ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7941, "level": 1, "question": "Analyze a list of student grades and identify students who need improvement.\n\nEach student is represented by a dictionary containing their name and a list of grades. You will write a program that flags students whose average grade is below a specifie...
from collections import defaultdict def max_unique_elements(nums, k): n = len(nums) if n == 0 or k == 0 or n < k: return 0 freq = defaultdict(int) unique_count = 0 max_unique = 0 # Initialize the first window for i in range(k): num = nums[i] if freq[num] ==...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `nums` and an integer `k`, return the maximum number of unique elements among all possible contiguous subarrays of length `k` in `nums`. A contiguous subarray is defined as a non-empty sequence of elements within `nums` such that the elements appear consecutiv...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7942, "level": 1, "question": "Given an array of integers `nums` and an integer `k`, return the maximum number of unique elements among all possible contiguous subarrays of length `k` in `nums`. A contiguous subarray is defined as a non-empty sequence of elements within `nums` such ...
def optimized_edit_distance(s1: str, s2: str) -> int: m = len(s1) n = len(s2) if m == 0: return n if n == 0: return m # Initialize the previous row prev_row = list(range(n + 1)) for i in range(1, m + 1): curr_row = [i] # Initialize current row for j=0 ...
simplelr_Algorithm
[ { "content": "Question:\n### Question:\nYou have been tasked with refactoring a function that calculates the edit distance (Levenshtein distance) between two strings. The current implementation has a high time complexity, and you need to optimize it for better performance.\n\n#### Function Signature:\n```python...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7943, "level": 1, "question": "### Question:\nYou have been tasked with refactoring a function that calculates the edit distance (Levenshtein distance) between two strings. The current implementation has a high time complexity, and you need to optimize it for better performance.\n\n...
from collections import deque def isBipartite(n, edges): if n == 0: return True adj = [[] for _ in range(n)] for u, v in edges: adj[u].append(v) adj[v].append(u) color = [-1] * n for u in range(n): if color[u] == -1: queue = deque([u]) color[u...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an undirected graph with `n` nodes and `edges`, where `edges[i] = [u, v]` indicates that there is an edge between the nodes `u` and `v`. You want to determine if the graph is **bipartite**. A graph is bipartite if the nodes can be divided into two groups such that no two n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7944, "level": 1, "question": "You are given an undirected graph with `n` nodes and `edges`, where `edges[i] = [u, v]` indicates that there is an edge between the nodes `u` and `v`. You want to determine if the graph is **bipartite**. A graph is bipartite if the nodes can be divided...
def max_difference_pairs(arr): if not arr: return 0 min_val = min(arr) max_val = max(arr) if min_val == max_val: return 0 min_count = arr.count(min_val) max_count = arr.count(max_val) return min_count * max_count
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `arr`, where `arr[i]` represents the height of a candle at position `i`, calculate the number of distinct ways to pick two candles so that the difference in their heights is maximum. Return _the number of such pairs_. If there are no pairs, return `0`.\nAnswer...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7945, "level": 1, "question": "Given an array of integers `arr`, where `arr[i]` represents the height of a candle at position `i`, calculate the number of distinct ways to pick two candles so that the difference in their heights is maximum. Return _the number of such pairs_. If ther...
def rotate(matrix): """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) # Transpose the matrix for i in range(n): for j in range(i + 1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # Reverse each row for row in matr...
simplelr_Leetcode
[ { "content": "Question:\nGiven a `n x n` 2D matrix representing an image, rotate the matrix 90 degrees clockwise in-place. You must solve the problem without using extra space for another matrix. Below is the method signature:\n\n```python\ndef rotate(matrix: List[List[int]]) -> None:\n \"\"\"\n Do not re...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7946, "level": 1, "question": "Given a `n x n` 2D matrix representing an image, rotate the matrix 90 degrees clockwise in-place. You must solve the problem without using extra space for another matrix. Below is the method signature:\n\n```python\ndef rotate(matrix: List[List[int]]) ...
def trap(height): if not height: return 0 n = len(height) left, right = 0, n - 1 left_max, right_max = 0, 0 result = 0 while left <= right: if left_max <= right_max: if height[left] >= left_max: left_max = height[left] else: ...
simplelr_Codeforces
[ { "content": "Question:\nGiven an elevation map represented by an array of integers, where each element represents the height of a unit-wide block, calculate the maximum amount of water that can be trapped after a rain.\n\nFor example, given the elevation map [0,1,0,2,1,0,1,3,2,1,2,1], the maximum amount of wat...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7947, "level": 1, "question": "Given an elevation map represented by an array of integers, where each element represents the height of a unit-wide block, calculate the maximum amount of water that can be trapped after a rain.\n\nFor example, given the elevation map [0,1,0,2,1,0,1,3,...
def max_subarray_sum(arr): if not arr: return 0 max_current = max_global = arr[0] for num in arr[1:]: max_current = max(num, max_current + num) if max_current > max_global: max_global = max_current return max_global
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the maximum sum of a subarray in a given array. This function should handle large arrays efficiently.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7948, "level": 1, "question": "Write a python function to find the maximum sum of a subarray in a given array. This function should handle large arrays efficiently.", "split": "train" }
def is_one_bit_difference(a, b): if len(a) != len(b): return False count = 0 for i in range(len(a)): if a[i] != b[i]: count += 1 if count > 1: return False return count == 1
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that checks if the difference between two binary strings (given as text) is exactly one.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7949, "level": 1, "question": "Write a Python function that checks if the difference between two binary strings (given as text) is exactly one.", "split": "train" }
def calculate_total_cost(items, shopping_list) -> float: # Create a dictionary to store item information for quick lookup item_info = {} for item in items: item_id = item[0] price = item[1] discount_type = item[2] discount_param = item[3] item_info[item_id] = (price, ...
simplelr_Taco
[ { "content": "Question:\n# Shopping List Price Calculator\n\nYou are developing a shopping list price calculator for a local grocery store. The store offers certain bulk discounts on items based on their quantities. Each item in the store is identified by its unique item ID and has a base unit price. The store ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7950, "level": 1, "question": "# Shopping List Price Calculator\n\nYou are developing a shopping list price calculator for a local grocery store. The store offers certain bulk discounts on items based on their quantities. Each item in the store is identified by its unique item ID an...
def process_flash_sale(available_items: int, orders: list[int]) -> list[int]: remaining = available_items result = [] for order in orders: if remaining <= 0: result.append(0) else: take = min(order, remaining) result.append(take) remaining -= t...
simplelr_Algorithm
[ { "content": "Question:\n#### Context:\nYou are developing a feature for an e-commerce platform to manage \"flash sales\" which offer a limited number of products at a discounted price for a short duration. Due to the limited quantity and high demand, the platform needs to efficiently handle transactions to ens...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7951, "level": 1, "question": "#### Context:\nYou are developing a feature for an e-commerce platform to manage \"flash sales\" which offer a limited number of products at a discounted price for a short duration. Due to the limited quantity and high demand, the platform needs to eff...
def robot_position(movements: str) -> tuple[int, int]: x, y = 0, 0 for move in movements: if move == 'U': y += 1 elif move == 'D': y -= 1 elif move == 'L': x -= 1 elif move == 'R': x += 1 return (x, y)
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are a developer at a robotics company. Your task is to write a software module that controls the movement of a robot in a 2D grid-based environment. The robot can move in four possible directions: 'up', 'down', 'left', and 'right'. The initial position of th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7952, "level": 1, "question": "### Problem Statement\n\nYou are a developer at a robotics company. Your task is to write a software module that controls the movement of a robot in a 2D grid-based environment. The robot can move in four possible directions: 'up', 'down', 'left', and ...
def find_strings_with_length(strings, length): return [string for string in strings if len(string) == length]
simplelr_Filter
[ { "content": "Question:\nI'll describe a function and you write the code for it in Python:\n\nWrite a function that takes two parameters, a list of strings and an integer. The function checks if the length of any string in the list is equal to the given integer. If such a string exists, the function returns a l...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7953, "level": 1, "question": "I'll describe a function and you write the code for it in Python:\n\nWrite a function that takes two parameters, a list of strings and an integer. The function checks if the length of any string in the list is equal to the given integer. If such a stri...
def factorial(n): """ Calculate the factorial of a non-negative integer using an iterative approach. Args: n (int): A non-negative integer. Returns: int: The factorial of n. Raises: ValueError: If n is a negative integer. """ if not isinstance(n, int): rais...
simplelr_Filter
[ { "content": "Question:\nPlease provide a Python code snippet that calculates the factorial of a given non-negative integer using an iterative approach.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7954, "level": 1, "question": "Please provide a Python code snippet that calculates the factorial of a given non-negative integer using an iterative approach.", "split": "train" }
def transform_list(A): n = len(A) if n == 0: return [] prefix = [1] * n for i in range(1, n): prefix[i] = prefix[i-1] * A[i-1] suffix = [1] * n for i in range(n-2, -1, -1): suffix[i] = suffix[i+1] * A[i+1] result = [] for i in range(n): resu...
simplelr_Taco
[ { "content": "Question:\nGiven a list of negative and positive numbers, write a function that transforms the list in such a way that each element replaced by the product of all elements of the original list except itself. \n\n-----Input-----\nThe input consists of a single list of integers, $A$ ($2 \\leq length...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7955, "level": 1, "question": "Given a list of negative and positive numbers, write a function that transforms the list in such a way that each element replaced by the product of all elements of the original list except itself. \n\n-----Input-----\nThe input consists of a single lis...
from typing import List def neighboring_diff(lst: List[int]) -> List[int]: """ Calculate the absolute differences between each pair of neighboring elements in the list. Args: lst (List[int]): A list of integers. Returns: List[int]: A list containing the absolute differences be...
simplelr_Evol
[ { "content": "Question:\nWrite a function in Python that accepts a list of integers and returns a new list containing the absolute values of the differences between each pair of neighboring elements. Ensure the function handles cases where the input list has fewer than two elements by returning an empty list in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7956, "level": 1, "question": "Write a function in Python that accepts a list of integers and returns a new list containing the absolute values of the differences between each pair of neighboring elements. Ensure the function handles cases where the input list has fewer than two ele...
def create_symmetric_matrix(vec): k = len(vec) discriminant = 1 + 8 * k root = int(discriminant ** 0.5) if root * root != discriminant: raise ValueError("Vector length must be a triangular number") n = (root - 1) // 2 if n * (n + 1) // 2 != k: raise ValueError("Vector length does...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to create a symmetric dense matrix from a vector.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7957, "level": 1, "question": "Write a function to create a symmetric dense matrix from a vector.", "split": "train" }
def reverse_string(s): s_list = list(s) left = 0 right = len(s_list) - 1 while left < right: s_list[left], s_list[right] = s_list[right], s_list[left] left += 1 right -= 1 return ''.join(s_list)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to reverse a string in-place using pointers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7958, "level": 1, "question": "Write a python function to reverse a string in-place using pointers.", "split": "train" }
def add_suffix(lst, suffix): return [str(x) + suffix for x in lst] # Test cases lst_string = ["a", "b", "c"] suffix = "_test" print(add_suffix(lst_string, suffix)) # Output: ['a_test', 'b_test', 'c_test'] lst_mixed = [1, 2.5, True, None] print(add_suffix(lst_mixed, suffix)) # Output: ['1_test', '2.5_test', 'Tru...
simplelr_Filter
[ { "content": "Question:\nHere is a Python function that takes a list of items, and appends a string to each item. I would like the function to also be able to handle integers, floats, and other data types, by converting any non-string data to a string, before appending the suffix string.\n\nHere is the example ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7959, "level": 1, "question": "Here is a Python function that takes a list of items, and appends a string to each item. I would like the function to also be able to handle integers, floats, and other data types, by converting any non-string data to a string, before appending the suf...
def balanced_string_split(s): balance = 0 count = 0 for c in s: if c == 'L': balance += 1 else: balance -= 1 if balance == 0: count += 1 return count
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` consisting of `n` characters, where each character is either 'L' or 'R', divide the string into as many balanced substrings as possible. A balanced substring is defined as a substring that has an equal number of 'L' and 'R' characters. Return the maximum number of bal...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7960, "level": 1, "question": "Given a string `s` consisting of `n` characters, where each character is either 'L' or 'R', divide the string into as many balanced substrings as possible. A balanced substring is defined as a substring that has an equal number of 'L' and 'R' character...
def minAddToMakeValid(s): balance = 0 additions = 0 for c in s: if c == '(': balance += 1 else: balance -= 1 if balance < 0: additions += 1 balance = 0 additions += balance return additions
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` of parentheses `(` and `)`, return the minimum number of parentheses to be added to make the string valid. A string is considered valid if:\n* Open brackets are closed by a corresponding number of close brackets.\n* Open brackets must be closed in the correct order.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7961, "level": 1, "question": "Given a string `s` of parentheses `(` and `)`, return the minimum number of parentheses to be added to make the string valid. A string is considered valid if:\n* Open brackets are closed by a corresponding number of close brackets.\n* Open brackets mus...
def count_unique_elements(nums): if not nums: return 0 count = 1 for i in range(1, len(nums)): if nums[i] != nums[i-1]: count += 1 return count
simplelr_Filter
[ { "content": "Question:\nGiven a sorted array of integers, write a function to return the number of unique elements in the array. Implement this in Python.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7962, "level": 1, "question": "Given a sorted array of integers, write a function to return the number of unique elements in the array. Implement this in Python.", "split": "train" }
from typing import List def trap_water(height: List[int]) -> int: if not height: return 0 left = 0 right = len(height) - 1 max_left = 0 max_right = 0 result = 0 while left < right: if height[left] < height[right]: if height[left] > max_left: ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem: Efficient Water Trap Calculation\n\nYou are given an array `height[]` of non-negative integers where each element represents the height of a column of water. The task is to design an algorithm that computes the maximum amount of water that can be trapped after it rains.\n\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7963, "level": 1, "question": "### Problem: Efficient Water Trap Calculation\n\nYou are given an array `height[]` of non-negative integers where each element represents the height of a column of water. The task is to design an algorithm that computes the maximum amount of water that...
def max_subarray_sum(arr): if not arr: return 0 # Return 0 for an empty array case max_ending_here = max_so_far = arr[0] for num in arr[1:]: max_ending_here = max(num, max_ending_here + num) max_so_far = max(max_so_far, max_ending_here) return max_so_far
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the maximum sum of elements in an array using Kadane's algorithm.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7964, "level": 1, "question": "Write a python function to find the maximum sum of elements in an array using Kadane's algorithm.", "split": "train" }
def bellman_ford(graph, source): # Initialize the distance dictionary distance = {node: float('inf') for node in graph} distance[source] = 0 # Number of nodes n = len(graph) # Relax edges |V| - 1 times for _ in range(n - 1): for u in graph: for v in graph[u]: ...
simplelr_Data_Structure
[ { "content": "Question:\n**Shortest Path Analysis with Bellman-Ford Algorithm**\n\n#### Context:\nYou are a software engineer working on a sophisticated navigation system which requires determining shortest paths on a graph representing a city road network. However, some roads have special conditions resulting ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7965, "level": 1, "question": "**Shortest Path Analysis with Bellman-Ford Algorithm**\n\n#### Context:\nYou are a software engineer working on a sophisticated navigation system which requires determining shortest paths on a graph representing a city road network. However, some roads...
from typing import List def find_common_elements(arr1: List[int], arr2: List[int]) -> List[int]: i = j = 0 result = [] while i < len(arr1) and j < len(arr2): if arr1[i] == arr2[j]: if not result or arr1[i] != result[-1]: result.append(arr1[i]) i += 1 ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement:\n\nYou are given two sorted arrays of integers. Write a function to find the elements that are common in both arrays. The output should be a list of common elements, sorted in ascending order, without duplicates.\n\n#### Input:\n* Two sorted arrays of integers, `a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7966, "level": 1, "question": "### Problem Statement:\n\nYou are given two sorted arrays of integers. Write a function to find the elements that are common in both arrays. The output should be a list of common elements, sorted in ascending order, without duplicates.\n\n#### Input:\n...
def min_distance_optimized(word1, word2): # Handle edge cases where one or both strings are empty if len(word1) == 0: return len(word2) if len(word2) == 0: return len(word1) # Determine the shorter string to optimize space usage if len(word1) < len(word2): shorter, longe...
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario:\nYou are developing a text editor that provides suggestions for correcting and aligning text between two document versions. One crucial feature is to determine how similar two versions are by finding the minimum number of delete operations needed to make them identical.\n\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7967, "level": 1, "question": "### Scenario:\nYou are developing a text editor that provides suggestions for correcting and aligning text between two document versions. One crucial feature is to determine how similar two versions are by finding the minimum number of delete operation...
def min_cost_path(grid: list[list[int]]) -> int: if not grid or not grid[0]: return 0 m = len(grid) n = len(grid[0]) # Create a DP table initialized with zeros dp = [[0 for _ in range(n)] for _ in range(m)] dp[0][0] = grid[0][0] # Fill the first row for j in range(...
simplelr_Algorithm
[ { "content": "Question:\n### Problem\n\nYou are given a grid of dimensions `m x n`, where each cell in the grid contains an integer value representing the cost of stepping on that cell. Your task is to compute the minimum cost path to traverse from the top-left corner of the grid to the bottom-right corner, mov...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7968, "level": 1, "question": "### Problem\n\nYou are given a grid of dimensions `m x n`, where each cell in the grid contains an integer value representing the cost of stepping on that cell. Your task is to compute the minimum cost path to traverse from the top-left corner of the g...
def longest_substring_with_k_distinct(s, k): if not s: return "" left = 0 max_length = 0 max_start = 0 max_end = -1 char_count = {} for right in range(len(s)): char = s[right] char_count[char] = char_count.get(char, 0) + 1 # Shrink the window until we h...
simplelr_Filter
[ { "content": "Question:\nGiven a string of length n, find the longest substring with at most k distinct characters.\n\nExample:\nInput: s = \"eceba\", k = 2\nOutput: \"ece\" \n\nExample:\nInput: s = \"aabbcc\", k = 2\nOutput: \"aab\" \n\nConstraints:\n- The input string will contain only lowercase letters.\n- 1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7969, "level": 1, "question": "Given a string of length n, find the longest substring with at most k distinct characters.\n\nExample:\nInput: s = \"eceba\", k = 2\nOutput: \"ece\" \n\nExample:\nInput: s = \"aabbcc\", k = 2\nOutput: \"aab\" \n\nConstraints:\n- The input string will c...
from collections import defaultdict def find_anagrams(s, p): if not p: return [] p_count = {} for c in p: p_count[c] = p_count.get(c, 0) + 1 len_p = len(p) len_s = len(s) if len_p == 0 or len_s < len_p: return [] unique_p = len(p_count) current_cou...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` consisting of lowercase letters, and you need to select a substring `t` such that the frequency of each character in `t` is exactly the same as in a given string `p`. Return _the starting indices of `t` in `s`, or an empty list if no such substring exists_. Th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7970, "level": 1, "question": "You are given a string `s` consisting of lowercase letters, and you need to select a substring `t` such that the frequency of each character in `t` is exactly the same as in a given string `p`. Return _the starting indices of `t` in `s`, or an empty li...
def calculateSpan(prices): n = len(prices) span = [0] * n stack = [] for i in range(n): while stack and prices[stack[-1]] <= prices[i]: stack.pop() if not stack: span[i] = i + 1 else: span[i] = i - stack[-1] stack.append(i) return s...
simplelr_Taco
[ { "content": "Question:\nYou need to create a function \"calculateSpan\" which takes an input array of daily stock prices and returns an array with the span of each day. The span of a stock’s price on a given day is defined as the maximum number of consecutive days just before the given day for which the price ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7971, "level": 1, "question": "You need to create a function \"calculateSpan\" which takes an input array of daily stock prices and returns an array with the span of each day. The span of a stock’s price on a given day is defined as the maximum number of consecutive days just before...
from datetime import datetime def is_valid_date(date_str): try: datetime.strptime(date_str, "%Y-%m-%d") return True except ValueError: return False
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that checks if a given string is a valid date in the format YYYY-MM-DD?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7972, "level": 1, "question": "How can I create a Python function that checks if a given string is a valid date in the format YYYY-MM-DD?", "split": "train" }
def dot_product(nums1, nums2): return sum(a * b for a, b in zip(nums1, nums2))
simplelr_Filter
[ { "content": "Question:\nGiven two equal-length arrays, `nums1` and `nums2`, return the dot product of two arrays.\n\n Constraints:\n\n `1 <= nums1.length, nums2.length <= 10^4`\n `-10^9 <= nums1[i], nums2[i] <= 10^9`\n\n Example:\n\n ```\n nums1 = [1, 2, 3]\n nums2 = [4, 5, 6]\n\n dotProduct = 1 4 + ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7973, "level": 1, "question": "Given two equal-length arrays, `nums1` and `nums2`, return the dot product of two arrays.\n\n Constraints:\n\n `1 <= nums1.length, nums2.length <= 10^4`\n `-10^9 <= nums1[i], nums2[i] <= 10^9`\n\n Example:\n\n ```\n nums1 = [1, 2, 3]\n nums2 = ...
def find_max_min(array): if not array: return None return (max(array), min(array))
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to find the maximum and minimum elements in an array. The function should return a tuple containing the maximum and minimum values. If the array is empty, the function should return `None`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7974, "level": 1, "question": "Write a Python function to find the maximum and minimum elements in an array. The function should return a tuple containing the maximum and minimum values. If the array is empty, the function should return `None`.", "split": "train" }
import math def catalan_number(n): return math.comb(2 * n, n) // (n + 1)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the number of distinct binary trees that can be formed with `n` nodes such that every non-leaf node has exactly two children. This is a classic problem known as Catalan Numbers. Provide a Python implementation that calculates the nth Catalan number efficien...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7975, "level": 1, "question": "Write a function to calculate the number of distinct binary trees that can be formed with `n` nodes such that every non-leaf node has exactly two children. This is a classic problem known as Catalan Numbers. Provide a Python implementation that calcula...
def is_palindrome(s): # Convert the string to lowercase and filter out non-alphanumeric characters cleaned = [c.lower() for c in s if c.isalnum()] cleaned_str = ''.join(cleaned) # Check if the cleaned string is a palindrome return cleaned_str == cleaned_str[::-1]
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that checks if a given string is a palindrome? I want the function to return `True` if the string is a palindrome and `False` otherwise. Additionally, the function should ignore spaces, punctuation, and capitalization. Can you provide a code snippet fo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7976, "level": 1, "question": "How can I create a Python function that checks if a given string is a palindrome? I want the function to return `True` if the string is a palindrome and `False` otherwise. Additionally, the function should ignore spaces, punctuation, and capitalization...
def minimal_bit_flips(a: int, b: int) -> int: return bin(a ^ b).count('1')
simplelr_Data_Structure
[ { "content": "Question:\n**Bit Flip Counter**\n\nSuppose you are developing a software that deals with data from different systems. Sometimes, data discrepancies happen, and you need to measure how different two pieces of integer data are, bit by bit. To do this, you must count the minimal number of bits that n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7977, "level": 1, "question": "**Bit Flip Counter**\n\nSuppose you are developing a software that deals with data from different systems. Sometimes, data discrepancies happen, and you need to measure how different two pieces of integer data are, bit by bit. To do this, you must coun...
def longest_string(*strings): return max(strings, key=lambda s: len(s), default='')
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a variable number of string arguments and returns the longest string among them.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7978, "level": 1, "question": "Create a function that takes a variable number of string arguments and returns the longest string among them.", "split": "train" }
def extract_weekly_highs(weekly_data): ordered_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] temp_dict = {day: -float('inf') for day in ordered_days} for day, temp in weekly_data: if temp > temp_dict[day]: temp_dict[day] = temp return [temp_dic...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that extracts the weekly high temperatures from a given list of tuples, where each tuple represents a day of the week followed by the temperature for that day. The function should return a list of the highest temperatures recorded for each day of the week.\nAnswer:\nLe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7979, "level": 1, "question": "Create a function that extracts the weekly high temperatures from a given list of tuples, where each tuple represents a day of the week followed by the temperature for that day. The function should return a list of the highest temperatures recorded for...
def count_abc_substring(s): return s.count("abc")
simplelr_Filter
[ { "content": "Question:\nConvert the given text into a Python code snippet. The text describes a function that takes a string `s` and returns the number of times the substring \"abc\" appears in `s`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7980, "level": 1, "question": "Convert the given text into a Python code snippet. The text describes a function that takes a string `s` and returns the number of times the substring \"abc\" appears in `s`.", "split": "train" }
def hex_to_decimal(hex_string): return int(hex_string, 16)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string containing a hexadecimal number and returns its decimal equivalent as an integer.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7981, "level": 1, "question": "Create a function that takes a string containing a hexadecimal number and returns its decimal equivalent as an integer.", "split": "train" }
def remaining_capacity(capacity, reservations): """ Computes the remaining seats for a flight given its total capacity and a list of reservations. :param capacity: An integer representing the total capacity of the flight. :param reservations: A list of integers where each integer represents the num...
simplelr_Taco
[ { "content": "Question:\nYou have been tasked with developing an application that helps airlines to organize flights and determine the remaining capacity of a given flight after all reservations have been processed. Each flight has a maximum capacity, and each reservation specifies the number of seats booked. \...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7982, "level": 1, "question": "You have been tasked with developing an application that helps airlines to organize flights and determine the remaining capacity of a given flight after all reservations have been processed. Each flight has a maximum capacity, and each reservation spec...
def reverse_by_swapping(lst): lst_copy = lst.copy() for i in range(len(lst_copy) // 2): lst_copy[i], lst_copy[-i - 1] = lst_copy[-i - 1], lst_copy[i] return lst_copy
simplelr_Filter
[ { "content": "Question:\nI have a list of numbers in Python, and I want to sort them. However, instead of using the direct sorting method, I want to write a function that changes the order of the numbers based on their index positions such that the number at index 0 is swapped with the number at the last index,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7983, "level": 1, "question": "I have a list of numbers in Python, and I want to sort them. However, instead of using the direct sorting method, I want to write a function that changes the order of the numbers based on their index positions such that the number at index 0 is swapped...
from collections import Counter def least_frequent_chars(s): # Filter out non-alphabetic characters and convert to lowercase processed = [char.lower() for char in s if char.isalpha()] if not processed: return [] # Count the frequency of each character counts = Counter(processed) ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the least frequent character in a string. If multiple characters have the same lowest frequency, return all of them. The function should ignore case and consider only alphabetic characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7984, "level": 1, "question": "Write a python function to find the least frequent character in a string. If multiple characters have the same lowest frequency, return all of them. The function should ignore case and consider only alphabetic characters.", "split": "train" }
def remove_reoccurring_characters(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:\n### Question: Remove Reoccurring Characters\n\n#### Context\nYou work at a company where user input needs to be sanitized to ensure all characters in a string are unique but in the order of their first appearance. Your task is to write a function to address this requirement.\n\n#### Req...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7985, "level": 1, "question": "### Question: Remove Reoccurring Characters\n\n#### Context\nYou work at a company where user input needs to be sanitized to ensure all characters in a string are unique but in the order of their first appearance. Your task is to write a function to ad...
def single_number(nums: list[int]) -> int: result = 0 for i in range(32): count = 0 for num in nums: if (num >> i) & 1: count += 1 if count % 3 != 0: result |= (1 << i) mask = (1 << 32) - 1 result &= mask if (result >> 31) & 1: ...
simplelr_Algorithm
[ { "content": "Question:\n### Bit Manipulation: Single Number II\n\n**Scenario**:\nIn a collection of integers, every integer appears exactly three times except for one, which appears exactly once. You are tasked with finding and returning the single integer that appears only once.\n\n**Problem**:\nDesign a func...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7986, "level": 1, "question": "### Bit Manipulation: Single Number II\n\n**Scenario**:\nIn a collection of integers, every integer appears exactly three times except for one, which appears exactly once. You are tasked with finding and returning the single integer that appears only o...
def sort_strings_by_length_desc(lst): return sorted(lst, key=lambda s: (-len(s), s))
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that sorts a list of strings in descending order based on their lengths. If two strings have the same length, they should be sorted in ascending alphabetical order.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7987, "level": 1, "question": "Create a Python function that sorts a list of strings in descending order based on their lengths. If two strings have the same length, they should be sorted in ascending alphabetical order.", "split": "train" }
def is_project_done(completeness, num_bugs): if completeness >= 100: return True elif completeness < 90: return False else: return num_bugs <= 5
simplelr_Filter
[ { "content": "Question:\nThis challenge involves creating a function that determines whether a given software development project should be considered \"done\" based on its completeness, measured as a percentage. The rules to determine if the project is done are as follows:\n- If the project completeness is gre...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7988, "level": 1, "question": "This challenge involves creating a function that determines whether a given software development project should be considered \"done\" based on its completeness, measured as a percentage. The rules to determine if the project is done are as follows:\n-...
def power(x, y): if y < 0: return 0 else: return x ** y
simplelr_Filter
[ { "content": "Question:\nI need to write a Python function that takes two parameters, `x` and `y`, and returns the result of `x` raised to the power of `y`. However, I want to ensure that if `y` is negative, the function returns 0 instead of a fraction. Can you help me with the code for this, ensuring it's a bi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7989, "level": 1, "question": "I need to write a Python function that takes two parameters, `x` and `y`, and returns the result of `x` raised to the power of `y`. However, I want to ensure that if `y` is negative, the function returns 0 instead of a fraction. Can you help me with th...
def filter_and_square_evens(nums): return [x ** 2 for x in nums if x % 2 == 0]
simplelr_Evol
[ { "content": "Question:\nWrite a Python function that receives a list of integers as input. The function should return a new list that contains the squares of the elements from the input list, but only if the squared value is even. If the input list is empty, the function should return an empty list.\n\n```pyth...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7990, "level": 1, "question": "Write a Python function that receives a list of integers as input. The function should return a new list that contains the squares of the elements from the input list, but only if the squared value is even. If the input list is empty, the function shou...
import re from typing import List, Tuple def extract_and_validate_emails(data: List[str]) -> Tuple[List[str], List[str]]: valid_emails = [] domains = [] # Regex pattern to validate the email format validation_pattern = re.compile(r'^[a-zA-Z0-9+_.-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9-]+$') for s in ...
simplelr_Docs
[ { "content": "Question:\n#### Question:\nYou are given a list of strings where each string contains an email address followed by some metadata in the format:\n```\n<email_address> <rest_of_string>\n```\nYour task is to:\n1. Extract the email addresses using a regular expression.\n2. Validate if the email addres...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7991, "level": 1, "question": "#### Question:\nYou are given a list of strings where each string contains an email address followed by some metadata in the format:\n```\n<email_address> <rest_of_string>\n```\nYour task is to:\n1. Extract the email addresses using a regular expressio...
from urllib.parse import urlparse, parse_qsl, urlencode from typing import Optional, List def strip_url_params(url: str, params_to_strip: Optional[List[str]] = None) -> str: if params_to_strip is None: params_to_strip = [] parsed_url = urlparse(url) query = parsed_url.query parsed_params =...
simplelr_Data_Structure
[ { "content": "Question:\nYou are tasked with writing a function `strip_url_params(url: str, params_to_strip: Optional[List[str]] = None) -> str` that removes any duplicate query string parameters from the URL and removes any query string parameters specified in the second argument (an optional list).\n\nThe fun...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7992, "level": 1, "question": "You are tasked with writing a function `strip_url_params(url: str, params_to_strip: Optional[List[str]] = None) -> str` that removes any duplicate query string parameters from the URL and removes any query string parameters specified in the second argu...
def organize_album(birds): species_dict = {} order = [] for bird in birds: if bird not in species_dict: order.append(bird) species_dict[bird] = [bird] else: species_dict[bird].append(bird) result = [] for b in order: result += species_dict[...
simplelr_Code_Contests
[ { "content": "Question:\nJames is a professional photographer and enjoys spending his free time taking pictures of wildlife. On his latest trip, he captured several images of birds. Upon returning, he decides to organize the images into different albums based on the species of birds he photographed. \n\nGiven a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7993, "level": 1, "question": "James is a professional photographer and enjoys spending his free time taking pictures of wildlife. On his latest trip, he captured several images of birds. Upon returning, he decides to organize the images into different albums based on the species of...
def classify_sequence(sequence: list) -> str: if len(sequence) < 2: return "None" # Check for arithmetic sequence is_arithmetic = True common_diff = sequence[1] - sequence[0] for i in range(2, len(sequence)): if sequence[i] - sequence[i-1] != common_diff: is_arithmet...
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes a list of integers and returns a string representing the type of sequence: \"Arithmetic\", \"Geometric\", or \"None\". An arithmetic sequence has a constant difference between consecutive elements, while a geometric sequence has a constant ratio between conse...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7994, "level": 1, "question": "Write a function that takes a list of integers and returns a string representing the type of sequence: \"Arithmetic\", \"Geometric\", or \"None\". An arithmetic sequence has a constant difference between consecutive elements, while a geometric sequence...
import math def factorial_tuples(tuples_list): result = [] for t in tuples_list: a, b = t fact_a = math.factorial(a) fact_b = math.factorial(b) result.append((fact_a, fact_b)) return result
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of tuples, where each tuple contains two integers, and returns a new list of tuples where each integer in the tuples is replaced by its factorial. You can use the `math` module for calculating the factorial.\nAnswer:\nLet's think step by step.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7995, "level": 1, "question": "Write a Python function that takes a list of tuples, where each tuple contains two integers, and returns a new list of tuples where each integer in the tuples is replaced by its factorial. You can use the `math` module for calculating the factorial.", ...
def find_missing_number(arr): m = len(arr) n = m + 1 expected_sum = n * (n + 1) // 2 actual_sum = sum(arr) return expected_sum - actual_sum
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the missing number in an array of integers. The array contains numbers from 1 to n with one number missing. Do this without using extra space and in O(n) time complexity.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7996, "level": 1, "question": "Write a function to find the missing number in an array of integers. The array contains numbers from 1 to n with one number missing. Do this without using extra space and in O(n) time complexity.", "split": "train" }
import random def roll_die(): return random.randint(1, 6) # Roll the die and print the result roll_result = roll_die() print(f"You rolled a {roll_result}")
simplelr_Filter
[ { "content": "Question:\nI want to create a Python script that simulates rolling a 6-sided die. How can I do that?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7997, "level": 1, "question": "I want to create a Python script that simulates rolling a 6-sided die. How can I do that?", "split": "train" }
from PIL import Image def convert_to_grayscale(input_path, output_path): """ Converts an image to grayscale and saves it as a new JPEG file. Args: input_path (str): Path to the input image file. output_path (str): Path to save the grayscale image. Returns: bool: True if succes...
simplelr_Filter
[ { "content": "Question:\n### Define a function that takes an image file path as input, applies a grayscale conversion to it, and then saves the converted image as a new JPEG file.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7998, "level": 1, "question": "### Define a function that takes an image file path as input, applies a grayscale conversion to it, and then saves the converted image as a new JPEG file.", "split": "train" }
from collections import Counter def most_frequent(strings): """ Returns a list of the most frequent strings in the input list. If two or more strings appear the same number of times, and that number is the highest frequency, the function returns all of the strings that have that highest frequency....
simplelr_Filter
[ { "content": "Question:\nI'm trying to create a function in Python that takes in a list of strings, and returns the string that appears most frequently in the list. If two or more strings appear the same number of times, and that number is the highest frequency, I want the function to return all of the strings ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7999, "level": 1, "question": "I'm trying to create a function in Python that takes in a list of strings, and returns the string that appears most frequently in the list. If two or more strings appear the same number of times, and that number is the highest frequency, I want the fun...