target
stringlengths
29
3.65k
data_source
stringclasses
12 values
prompt
listlengths
1
1
ability
stringclasses
1 value
reward_model
dict
extra_info
dict
def find_max(numbers): if not numbers: return None return max(numbers)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the maximum number in a given list of integers. If the list is empty, the function should return `None`. This function is crucial for data analysis tasks where identifying the highest value is necessary.\nAnswer:\nLet's think step by step.\n", "role": "user"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2300, "level": 1, "question": "Write a function to find the maximum number in a given list of integers. If the list is empty, the function should return `None`. This function is crucial for data analysis tasks where identifying the highest value is necessary.", "split": "train" }
from typing import List def max_subarray(arr: List[int]) -> int: current_max = max_sum = arr[0] for num in arr[1:]: current_max = max(num, current_max + num) max_sum = max(max_sum, current_max) return max_sum
simplelr_Data_Structure
[ { "content": "Question:\n### Coding Challenge: Maximum Sum Subarray Finder\n\n#### Problem Statement\nYou are given an integer array `arr`. Your task is to implement a function `max_subarray(arr)` that computes the maximum sum of a contiguous subarray in the given array.\n\n#### Function Signature\n```python\nd...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2301, "level": 1, "question": "### Coding Challenge: Maximum Sum Subarray Finder\n\n#### Problem Statement\nYou are given an integer array `arr`. Your task is to implement a function `max_subarray(arr)` that computes the maximum sum of a contiguous subarray in the given array.\n\n##...
def filter_list_by_threshold(nums, threshold): return [num for num in nums if num >= threshold]
simplelr_Filter
[ { "content": "Question:\nCreate a function in Python that takes two parameters: a list of integers and an integer threshold. The function should return a new list with only the elements from the original list that are greater than or equal to the threshold.\nAnswer:\nLet's think step by step.\n", "role": "u...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2302, "level": 1, "question": "Create a function in Python that takes two parameters: a list of integers and an integer threshold. The function should return a new list with only the elements from the original list that are greater than or equal to the threshold.", "split": "train...
from typing import List def smallest_derangement(n: int) -> List[int]: arr = list(range(1, n + 1)) for i in range(0, n - 1, 2): arr[i], arr[i + 1] = arr[i + 1], arr[i] if n % 2 != 0: if arr[-1] == n: arr[-2], arr[-1] = arr[-1], arr[-2] return arr
simplelr_Algorithm
[ { "content": "Question:\n### Coding Problem: Find the Lexicographically Smallest Permutation\n\n#### Context\nGiven a positive integer `n`, you are required to find the lexicographically smallest permutation of an array containing the elements `[1, 2, 3, ..., n]` such that no element remains in its initial posi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2303, "level": 1, "question": "### Coding Problem: Find the Lexicographically Smallest Permutation\n\n#### Context\nGiven a positive integer `n`, you are required to find the lexicographically smallest permutation of an array containing the elements `[1, 2, 3, ..., n]` such that no ...
def has_pair_with_sum(arr: list, target_sum: int) -> bool: seen = set() for num in arr: complement = target_sum - num if complement in seen: return True seen.add(num) return False
simplelr_Algorithm
[ { "content": "Question:\n### Array Pair Sum\n\nYou need to write a function that checks if a given array contains two distinct elements that add up to a specified target sum. The function should be efficient and handle large inputs gracefully.\n\n#### Implementation Details:\n\nImplement a function `has_pair_wi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2304, "level": 1, "question": "### Array Pair Sum\n\nYou need to write a function that checks if a given array contains two distinct elements that add up to a specified target sum. The function should be efficient and handle large inputs gracefully.\n\n#### Implementation Details:\n...
def find_max(grid): max_val = -float('inf') row = 0 col = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] > max_val: max_val = grid[i][j] row = i col = j return (row, col)
simplelr_Taco
[ { "content": "Question:\n# Task\nYou have a grid of size `m x n` consisting of non-negative integers. The task is to find the grid cell with the maximum value and return its coordinates in the form (row, col). If there are multiple cells with the same maximum value, return the coordinates of the one which comes...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2305, "level": 1, "question": "# Task\nYou have a grid of size `m x n` consisting of non-negative integers. The task is to find the grid cell with the maximum value and return its coordinates in the form (row, col). If there are multiple cells with the same maximum value, return the...
def is_ascending_order(numbers_str): numbers = [int(x) for x in numbers_str.split()] for i in range(len(numbers) - 1): if numbers[i] > numbers[i + 1]: return False return True
simplelr_Filter
[ { "content": "Question:\nI provide a series of numbers separated by space. Write a Python function that takes the input line, splits it into numbers and checks if they are in ascending order. If they are, function returns True, otherwise False.\n\nExample:\nInput: \"1 2 3 4 5\"\nOutput: True\n\nInput: \"1 2 4 3...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2306, "level": 1, "question": "I provide a series of numbers separated by space. Write a Python function that takes the input line, splits it into numbers and checks if they are in ascending order. If they are, function returns True, otherwise False.\n\nExample:\nInput: \"1 2 3 4 5\...
import itertools def generate_palindromes(n): k = (n + 1) // 2 letters = 'abcdefghijklmnopqrstuvwxyz' palindromes = [] for prefix in itertools.product(letters, repeat=k): s = ''.join(prefix) if n % 2 == 0: palindrome = s + s[::-1] else: palindrome = s + s...
simplelr_Leetcode
[ { "content": "Question:\nA palindrome is a string that reads the same forward and backward. Given an integer `n`, generate all possible strings of length `n` that are palindromes using lowercase English letters. Return the list of these palindromic strings in lexicographical order.\nAnswer:\nLet's think step by...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2307, "level": 1, "question": "A palindrome is a string that reads the same forward and backward. Given an integer `n`, generate all possible strings of length `n` that are palindromes using lowercase English letters. Return the list of these palindromic strings in lexicographical o...
def count_pairs(nums, target): seen = {} count = 0 for num in nums: complement = target - num if complement in seen: count += seen[complement] if num in seen: seen[num] += 1 else: seen[num] = 1 return count
simplelr_Leetcode
[ { "content": "Question:\nYou are given an integer array `nums` and an integer `target`. Return _the number of different pairs_ `(i, j)` _such that_ `nums[i] + nums[j] == target` _and_ `i` _is less than_ `j`. Each pair should be counted only once, and the order in which they are counted does not matter.\nAnswer:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2308, "level": 1, "question": "You are given an integer array `nums` and an integer `target`. Return _the number of different pairs_ `(i, j)` _such that_ `nums[i] + nums[j] == target` _and_ `i` _is less than_ `j`. Each pair should be counted only once, and the order in which they ar...
def findPairsWithSum(arr, target): pairs = set() n = len(arr) for i in range(n): for j in range(i + 1, n): if arr[i] + arr[j] == target: pair = tuple(sorted((arr[i], arr[j]))) pairs.add(pair) sorted_pairs = sorted(pairs) return sorted_pairs
simplelr_Apps
[ { "content": "Question:\nYou are given an array of integers. Your task is to find all unique pairs in the array that add up to a given target sum. Complete the function `findPairsWithSum(arr, target)`, where `arr` is the input array and `target` is the target sum. Each pair should be sorted in ascending order, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2309, "level": 1, "question": "You are given an array of integers. Your task is to find all unique pairs in the array that add up to a given target sum. Complete the function `findPairsWithSum(arr, target)`, where `arr` is the input array and `target` is the target sum. Each pair sh...
def can_be_equal(target, arr): if len(target) != len(arr): return False return sorted(target) == sorted(arr)
simplelr_Leetcode
[ { "content": "Question:\nYou are given two arrays `target` and `arr`, both of which consist of distinct integers. You can rearrange the elements of `arr` in any order. For each operation, you can select any subarray of `arr` and reverse it. _Return_ `true` _if you can transform `arr` into `target` using any num...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2310, "level": 1, "question": "You are given two arrays `target` and `arr`, both of which consist of distinct integers. You can rearrange the elements of `arr` in any order. For each operation, you can select any subarray of `arr` and reverse it. _Return_ `true` _if you can transfor...
def evaluate_expression(s): # Tokenize the input string into numbers and operators s = s.replace(' ', '') tokens = [] current_token = '' for char in s: if char.isdigit(): current_token += char else: if current_token: tokens.append(int(current_t...
simplelr_Apps
[ { "content": "Question:\nYou are given a string representing a simple mathematical expression containing non-negative integers and the operators `+`, `-`, and `*`. Write a function to evaluate this expression and return the result as an integer. The input string is guaranteed to be a valid expression.\n\n## Exa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2311, "level": 1, "question": "You are given a string representing a simple mathematical expression containing non-negative integers and the operators `+`, `-`, and `*`. Write a function to evaluate this expression and return the result as an integer. The input string is guaranteed ...
import heapq def dijkstra(graph, start, end): if start not in graph or end not in graph: return float('infinity'), [] distances = {node: float('infinity') for node in graph} distances[start] = 0 heap = [] heapq.heappush(heap, (0, start)) predecessors = {} while heap: ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the shortest path between two nodes in a graph using Dijkstra's algorithm.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2312, "level": 1, "question": "Write a python function to find the shortest path between two nodes in a graph using Dijkstra's algorithm.", "split": "train" }
import re def extract_com_urls(text): # Extract all URLs from the text all_urls = re.findall(r'"(https?://[^\s]+)"', text) # Filter URLs that end with .com com_urls = [url for url in all_urls if url.endswith('.com')] return com_urls # Example usage text = """ ( "http://google.com", "https://fa...
simplelr_Filter
[ { "content": "Question:\nI'll provide you with some text, and I'd like you to write a Python script to extract specific information from it. \n\nThe text is as follows:\n\n```\n(\n \"http://google.com\",\n \"https://facebook.com\",\n \"https://twitter.com\",\n \"https://instagram.com\",\n \"https://pintere...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2313, "level": 1, "question": "I'll provide you with some text, and I'd like you to write a Python script to extract specific information from it. \n\nThe text is as follows:\n\n```\n(\n \"http://google.com\",\n \"https://facebook.com\",\n \"https://twitter.com\",\n \"https://in...
def fibonacci(n): if type(n) is not int: raise TypeError("Undefined for non-integers") if n < 0: raise ValueError("Undefined for negative numbers") if n == 0: return 0 elif n == 1: return 1 a, b = 0, 1 for i in range(2, n + 1): a, b = b, a + b return b
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nWrite a function to compute the Fibonacci numbers using dynamic programming to improve performance. The function needs to handle both small and large inputs efficiently.\n\n### Requirements\n\n* The function should be named `fibonacci` and take a single integer ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2314, "level": 1, "question": "### Problem Statement\n\nWrite a function to compute the Fibonacci numbers using dynamic programming to improve performance. The function needs to handle both small and large inputs efficiently.\n\n### Requirements\n\n* The function should be named `fi...
import bisect def length_of_lis(nums): tails = [] for num in nums: index = bisect.bisect_left(tails, num) if index == len(tails): tails.append(num) else: tails[index] = num return len(tails)
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python code snippet to calculate the length of the longest increasing subsequence in a given list of integers?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2315, "level": 1, "question": "Can you provide a Python code snippet to calculate the length of the longest increasing subsequence in a given list of integers?", "split": "train" }
def rotate_matrix_90(matrix: list[list[int]]) -> list[list[int]]: n = len(matrix) # Transpose the matrix transposed = [] for i in range(n): transposed.append([matrix[j][i] for j in range(n)]) # Reverse each row of the transposed matrix to get the 90-degree rotation rotated = [row[::-1] f...
simplelr_Algorithm
[ { "content": "Question:\n## Image Rotation by 90 Degrees\n\nYou are required to implement a function to rotate a given NxN matrix by 90 degrees clockwise. This is a common task in image processing, particularly in the manipulation of bitmap images.\n\n### Function Specification\n\n**Function**: `rotate_matrix_9...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2316, "level": 1, "question": "## Image Rotation by 90 Degrees\n\nYou are required to implement a function to rotate a given NxN matrix by 90 degrees clockwise. This is a common task in image processing, particularly in the manipulation of bitmap images.\n\n### Function Specificatio...
def merge_sorted_arrays(arr1: list[int], arr2: list[int]) -> list[int]: # Validate input types if not isinstance(arr1, list) or not isinstance(arr2, list): raise TypeError("Both inputs must be lists.") # Validate all elements are integers for x in arr1: if type(x) is not int: ...
simplelr_Algorithm
[ { "content": "Question:\n### Merge Two Sorted Arrays\n\nAs a software developer, you are tasked with creating a functionality to merge two sorted arrays into one sorted array. This is a common problem in sorting algorithms and data manipulation.\n\nGiven two sorted arrays, write a function `merge_sorted_arrays`...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2317, "level": 1, "question": "### Merge Two Sorted Arrays\n\nAs a software developer, you are tasked with creating a functionality to merge two sorted arrays into one sorted array. This is a common problem in sorting algorithms and data manipulation.\n\nGiven two sorted arrays, wri...
def reverse_string_using_stack(s): stack = [] for char in s: stack.append(char) reversed_s = [] while stack: reversed_s.append(stack.pop()) return ''.join(reversed_s)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to reverse a string. But this time, you need to do it using a stack data structure in Python.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2318, "level": 1, "question": "Write a function to reverse a string. But this time, you need to do it using a stack data structure in Python.", "split": "train" }
def find_first_pair_with_same_value(arr): for i in range(len(arr) - 1): if arr[i] == arr[i + 1]: return (arr[i], arr[i + 1]) return None
simplelr_Filter
[ { "content": "Question:\nI have an array of integers and I want to find the first pair of adjacent elements that have the same value. Can you provide a code example in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2319, "level": 1, "question": "I have an array of integers and I want to find the first pair of adjacent elements that have the same value. Can you provide a code example in Python?", "split": "train" }
def max_challenges(time, T): sorted_time = sorted(time) sum_time = 0 count = 0 for t in sorted_time: if sum_time + t > T: break sum_time += t count += 1 return count
simplelr_Leetcode
[ { "content": "Question:\nA company organizes a hackathon where teams of developers solve various coding problems. Each team is given a set of `N` different challenges to solve. Teams are scored based on the number of challenges they solve and the total time they take to solve them. Each challenge `i` takes `tim...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2320, "level": 1, "question": "A company organizes a hackathon where teams of developers solve various coding problems. Each team is given a set of `N` different challenges to solve. Teams are scored based on the number of challenges they solve and the total time they take to solve ...
def find_single_number(nums): result = 0 for num in nums: result ^= num return result
simplelr_Evol
[ { "content": "Question:\nYou are given a list of numbers where each value appears twice except for one value which appears only once. Write a program to find that unique number. Explain the process and logic used to identify the single element.\n\nExample:\nInput: [4, 1, 2, 1, 2]\nOutput: 4\nAnswer:\nLet's thin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2321, "level": 1, "question": "You are given a list of numbers where each value appears twice except for one value which appears only once. Write a program to find that unique number. Explain the process and logic used to identify the single element.\n\nExample:\nInput: [4, 1, 2, 1,...
import matplotlib.pyplot as plt import numpy as np def plot_linear_regression(x, y, line_color, scatter_color): # Compute the coefficients for the linear regression line coeff = np.polyfit(x, y, 1) # Create the x values for the regression line x_line = np.linspace(x.min(), x.max(), 100) # Calculate...
simplelr_Package
[ { "content": "Question:\nYou are required to create a function `plot_linear_regression` which visualizes a dataset and fits a linear regression line using the `matplotlib.pyplot` and `numpy` libraries. The specific requirements for this function are as follows:\n\n1. **Function Name**: `plot_linear_regression`\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2322, "level": 1, "question": "You are required to create a function `plot_linear_regression` which visualizes a dataset and fits a linear regression line using the `matplotlib.pyplot` and `numpy` libraries. The specific requirements for this function are as follows:\n\n1. **Functio...
def largest_increasing_subsequence_sum(arr: list) -> int: if not arr: return 0 n = len(arr) dp = [0] * n for i in range(n): dp[i] = arr[i] for j in range(i): if arr[j] < arr[i]: dp[i] = max(dp[i], dp[j] + arr[i]) return max(dp) if n > 0 else 0
simplelr_Algorithm
[ { "content": "Question:\n### Largest Increasing Subsequence Sum\n\n#### Problem\nYou are given an array of integers. Your task is to find the sum of the largest increasing subsequence in the array. An increasing subsequence is a sequence of values derived from the array by deleting some or no elements without c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2323, "level": 1, "question": "### Largest Increasing Subsequence Sum\n\n#### Problem\nYou are given an array of integers. Your task is to find the sum of the largest increasing subsequence in the array. An increasing subsequence is a sequence of values derived from the array by del...
def generate_sequence(n): if n > 0: nums = range(1, n + 1) elif n < 0: nums = range(n, 1) else: return "0" return ' '.join(map(str, nums))
simplelr_Prefill
[ { "content": "Question:\nCreate a function that generates a sequence of numbers based on then argument passed. If the parameter n is negative, the function should generate a sequence of numbers from n to 0. If n is a positive integer, it should generate a sequence of numbers from 1 to n. The function should ret...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2324, "level": 1, "question": "Create a function that generates a sequence of numbers based on then argument passed. If the parameter n is negative, the function should generate a sequence of numbers from n to 0. If n is a positive integer, it should generate a sequence of numbers f...
def binary_search(arr, target): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1
simplelr_Filter
[ { "content": "Question:\nYou are given a sorted array of integers and a target value. Write a function that returns the index of the target value if it exists in the array, or -1 if it does not. Use binary search to achieve a time complexity of O(log n).\nAnswer:\nLet's think step by step.\n", "role": "user...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2325, "level": 1, "question": "You are given a sorted array of integers and a target value. Write a function that returns the index of the target value if it exists in the array, or -1 if it does not. Use binary search to achieve a time complexity of O(log n).", "split": "train" }
from typing import List, Tuple def autocomplete(suggestions: List[Tuple[str, int]], k: int, typed: str) -> List[str]: # Filter the suggestions to include only words starting with 'typed' filtered = [] for word, freq in suggestions: if word.startswith(typed): filtered.append((word, freq)...
simplelr_Code_Contests
[ { "content": "Question:\nYou are working on a text-messaging application that involves autocomplete suggestions. As the user types, you want to provide the most relevant words that start with the user's current input. You'll be given a list of suggested words and an integer k, the maximum number of suggestions ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2326, "level": 1, "question": "You are working on a text-messaging application that involves autocomplete suggestions. As the user types, you want to provide the most relevant words that start with the user's current input. You'll be given a list of suggested words and an integer k,...
from typing import List def max_view_height(tree_heights: List[int]) -> int: return max((h for h in tree_heights if h > 0), default=0)
simplelr_Codeforces
[ { "content": "Question:\nYou are given an array of integers representing the heights of trees in a forest. After a powerful storm, some trees were blown down completely, reducing their heights to 0. You are tasked with determining the highest possible view from the forest by considering only the intact trees. \...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2327, "level": 1, "question": "You are given an array of integers representing the heights of trees in a forest. After a powerful storm, some trees were blown down completely, reducing their heights to 0. You are tasked with determining the highest possible view from the forest by c...
from typing import List def pigeonhole_sort(arr: List[int]) -> List[int]: if not arr: return [] min_val = min(arr) max_val = max(arr) size = max_val - min_val + 1 pigeonholes = [0] * size for num in arr: shifted = num - min_val pigeonholes[shifted] += 1 ...
simplelr_Data_Structure
[ { "content": "Question:\n### Pigeonhole Sort Implementation\n\n#### Scenario:\nYou are tasked with organizing a list of scores from a school's grading system. The list contains the scores of students from multiple classes. You aim to sort these scores using an efficient algorithm.\n\n#### Problem Statement:\nIm...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2328, "level": 1, "question": "### Pigeonhole Sort Implementation\n\n#### Scenario:\nYou are tasked with organizing a list of scores from a school's grading system. The list contains the scores of students from multiple classes. You aim to sort these scores using an efficient algori...
def reverse_every_n(lst, n): result = [] for i in range(0, len(lst), n): chunk = lst[i:i+n] result += chunk[::-1] return result
simplelr_Filter
[ { "content": "Question:\nGiven a list of integers and an integer `n`, write a function to reverse every `n` nodes of the linked list. \n\nExample:\n\nGiven a list of integers: `1, 2, 3, 4, 5, 6, 7`\n`n = 3`\n\nThe function should return: `3, 2, 1, 6, 5, 4, 7`\n\nNote: If the remaining nodes are less than `n`, i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2329, "level": 1, "question": "Given a list of integers and an integer `n`, write a function to reverse every `n` nodes of the linked list. \n\nExample:\n\nGiven a list of integers: `1, 2, 3, 4, 5, 6, 7`\n`n = 3`\n\nThe function should return: `3, 2, 1, 6, 5, 4, 7`\n\nNote: If the r...
from typing import List, Optional def max_product_of_three(arr: List[int]) -> Optional[int]: if len(arr) < 3: return None sorted_arr = sorted(arr) option1 = sorted_arr[-1] * sorted_arr[-2] * sorted_arr[-3] option2 = sorted_arr[0] * sorted_arr[1] * sorted_arr[-1] return max(option1, option2)
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement:\nGive an integer array `arr`, find the maximum product of any three numbers in the array.\n\n### Input:\nAn integer array `arr` of length `n`.\n\n### Output:\nReturn the maximum product of any three numbers in the array, or `None` if the array has less than three ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2330, "level": 1, "question": "### Problem Statement:\nGive an integer array `arr`, find the maximum product of any three numbers in the array.\n\n### Input:\nAn integer array `arr` of length `n`.\n\n### Output:\nReturn the maximum product of any three numbers in the array, or `None...
import os def get_all_filenames(directory): filenames = [] for root, dirs, files in os.walk(directory): for file in files: filenames.append(file) return filenames
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a directory path as an argument and returns all the filenames in the directory and its subdirectories in a list. The function should not return the directory names themselves, only the filenames.\nAnswer:\nLet's think step by step.\n", "role": "user" }...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2331, "level": 1, "question": "Create a function that takes a directory path as an argument and returns all the filenames in the directory and its subdirectories in a list. The function should not return the directory names themselves, only the filenames.", "split": "train" }
import pandas as pd def count_unique_items(df: pd.DataFrame) -> pd.DataFrame: # Group by 'Date' and count unique 'Item_ID's for each date unique_counts = df.groupby('Date')['Item_ID'].nunique() # Reset the index to create a DataFrame and rename the columns result = unique_counts.reset_index() resul...
simplelr_Package
[ { "content": "Question:\nYou are tasked with writing a function named `count_unique_items` to determine the number of unique items sold in a store on specific dates. This function should take a pandas DataFrame containing three columns: \"Date\" (representing the sale date), \"Item_ID\" (representing the unique...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2332, "level": 1, "question": "You are tasked with writing a function named `count_unique_items` to determine the number of unique items sold in a store on specific dates. This function should take a pandas DataFrame containing three columns: \"Date\" (representing the sale date), \...
def current_occupants(events): # Sort the events by timestamp sorted_events = sorted(events, key=lambda x: x[0]) inside = {} for event in sorted_events: timestamp, pid, etype = event if etype == 'enter': if pid not in inside or not inside.get(pid, False): ...
simplelr_Taco
[ { "content": "Question:\nA security system logs entries and exits through a gate in order to track the people currently inside a building. Each entry or exit is recorded as an event with a timestamp and a person ID. To keep the logs consistent, an entry should only be followed by an exit for the same person ID ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2333, "level": 1, "question": "A security system logs entries and exits through a gate in order to track the people currently inside a building. Each entry or exit is recorded as an event with a timestamp and a person ID. To keep the logs consistent, an entry should only be followed...
import numpy as np def inverse_matrix(matrix): """Compute the inverse of a matrix if it is invertible.""" try: inverse = np.linalg.inv(matrix) return inverse except np.linalg.LinAlgError: print("The matrix is not invertible.") return None # Example usage with an invertible ...
simplelr_Filter
[ { "content": "Question:\nWrite a code snippet that demonstrates how to compute the inverse of a 3x3 matrix in Python. Make sure your solution handles cases where the matrix is not invertible. It should use the numpy library for the computation.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2334, "level": 1, "question": "Write a code snippet that demonstrates how to compute the inverse of a 3x3 matrix in Python. Make sure your solution handles cases where the matrix is not invertible. It should use the numpy library for the computation.", "split": "train" }
def get_permutations(string): # Base case: if the string is empty or contains only one character, return a set with an empty string or the string itself if len(string) <= 1: return {string} # Sort the string to handle duplicates sorted_str = ''.join(sorted(string)) all_permutations = set() ...
simplelr_Filter
[ { "content": "Question:\nTo generate all permutations of the characters in a string, we can use a recursive algorithm that has a base case that stops the recursion, and a recursive case that breaks the problem down into smaller sub-problems. A correct implementation uses a set to remove duplicate permutations.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2335, "level": 1, "question": "To generate all permutations of the characters in a string, we can use a recursive algorithm that has a base case that stops the recursion, and a recursive case that breaks the problem down into smaller sub-problems. A correct implementation uses a set...
def reverse_string(s): return s[::-1]
simplelr_Apps
[ { "content": "Question:\nWrite a function that takes a string as input and returns a new string with the characters in reverse order, preserving the case of each character. For example, given the input string \"Hello, World!\", the function should return \"!dlroW ,olleH\".\nAnswer:\nLet's think step by step.\n"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2336, "level": 1, "question": "Write a function that takes a string as input and returns a new string with the characters in reverse order, preserving the case of each character. For example, given the input string \"Hello, World!\", the function should return \"!dlroW ,olleH\".", ...
def sum_range(a, b): start = min(a, b) end = max(a, b) n = end - start + 1 return (n * (start + end)) // 2
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes two arguments a and b, and returns the sum of all numbers in the range between a and b (inclusive). Use Python.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2337, "level": 1, "question": "Create a function that takes two arguments a and b, and returns the sum of all numbers in the range between a and b (inclusive). Use Python.", "split": "train" }
def shift_string(s, shift): result = [] for c in s: original_position = ord(c) - ord('a') new_position = (original_position + shift) % 26 new_char = chr(new_position + ord('a')) result.append(new_char) return ''.join(result)
simplelr_Apps
[ { "content": "Question:\nWrite a function that takes a string consisting of lowercase alphabets ('a' to 'z') and returns a new string with each character shifted by a given number of places in the alphabet. The shift should wrap around the end of the alphabet.\n\nFor example, with a shift of 1, 'a' would become...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2338, "level": 1, "question": "Write a function that takes a string consisting of lowercase alphabets ('a' to 'z') and returns a new string with each character shifted by a given number of places in the alphabet. The shift should wrap around the end of the alphabet.\n\nFor example, ...
def rotateMatrix(matrix): N = len(matrix) # Transpose the matrix for i in range(N): for j in range(i + 1, N): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # Reverse each row for row in matrix: row.reverse()
simplelr_Apps
[ { "content": "Question:\nWrite a function **rotateMatrix** that takes a two-dimensional square matrix (list of lists) and rotates it 90 degrees clockwise in-place. The input matrix will have N rows and N columns, where N is an integer greater than 1. The rotation must be done without using any extra space for a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2339, "level": 1, "question": "Write a function **rotateMatrix** that takes a two-dimensional square matrix (list of lists) and rotates it 90 degrees clockwise in-place. The input matrix will have N rows and N columns, where N is an integer greater than 1. The rotation must be done ...
from typing import List import math def bucket_sort(arr: List[int]) -> List[int]: if not arr: return [] n = len(arr) if n == 1: return arr.copy() min_val = min(arr) max_val = max(arr) if min_val == max_val: return arr.copy() k = int(math.sqrt(n)) ...
simplelr_Data_Structure
[ { "content": "Question:\n### Bucket Sort Implementation Challenge\n\nYou are provided with a partially implemented Bucket Sort function in Python. Your task is to complete and optimize this function while considering the edge cases and potential performance bottlenecks.\n\n**Task**:\n1. Implement the `bucket_so...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2340, "level": 1, "question": "### Bucket Sort Implementation Challenge\n\nYou are provided with a partially implemented Bucket Sort function in Python. Your task is to complete and optimize this function while considering the edge cases and potential performance bottlenecks.\n\n**T...
def average_of_three(a, b, c): return round((a + b + c) / 3, 2)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that accepts three numbers as arguments and returns their average, rounded to two decimal places.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2341, "level": 1, "question": "Create a function that accepts three numbers as arguments and returns their average, rounded to two decimal places.", "split": "train" }
def words_to_chars_list(s): if not s.strip(): return "input must contain at least one word" words = s.split() return [list(word) for word in words]
simplelr_Apps
[ { "content": "Question:\nWrite a function that takes a string consisting of several words separated by spaces and converts it into a list of lists, where each inner list contains the characters of each word. If the input string is empty or contains only spaces, return `\"input must contain at least one word\"`....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2342, "level": 1, "question": "Write a function that takes a string consisting of several words separated by spaces and converts it into a list of lists, where each inner list contains the characters of each word. If the input string is empty or contains only spaces, return `\"input...
def word_line_numbers(text): word_lines = {} lines = text.splitlines() for line_number, line in enumerate(lines, 1): words = line.split() for word in words: if word in word_lines: word_lines[word].append(line_number) else: word_lines[wo...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to create a dictionary where the key is the word and the value is the list of line numbers where the word appears in a given text.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2343, "level": 1, "question": "Write a python function to create a dictionary where the key is the word and the value is the list of line numbers where the word appears in a given text.", "split": "train" }
import heapq from typing import List def shortest_paths(matrix: List[List[int]], source: int) -> List[int]: n = len(matrix) if n == 0: return [] # Initialize distances with infinity, except the source which is 0 distances = [float('inf')] * n distances[source] = 0 # Priority q...
simplelr_Data_Structure
[ { "content": "Question:\n**Shortest Path Finder**\n\nAs an engineer for a logistics company, you are tasked with implementing an optimized shortest path finder for delivery routes among warehouses. Consider a weighted, directed graph where nodes represent warehouses and edges represent the available routes with...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2344, "level": 1, "question": "**Shortest Path Finder**\n\nAs an engineer for a logistics company, you are tasked with implementing an optimized shortest path finder for delivery routes among warehouses. Consider a weighted, directed graph where nodes represent warehouses and edges ...
import numpy as np import pandas as pd def evaluate_function(function_str, x_start, x_end, step_size): if step_size == 0: raise ValueError("step_size cannot be zero") if (step_size > 0 and x_start > x_end) or (step_size < 0 and x_start < x_end): raise ValueError("step_size and x_start, x_e...
simplelr_Package
[ { "content": "Question:\nWrite a function that takes a string representing a mathematical function `f(x)` as input and generates a DataFrame that evaluates this function over a specified range of `x` values. The DataFrame should have two columns: 'x' and 'f(x)', which contain the values of `x` and the correspon...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2345, "level": 1, "question": "Write a function that takes a string representing a mathematical function `f(x)` as input and generates a DataFrame that evaluates this function over a specified range of `x` values. The DataFrame should have two columns: 'x' and 'f(x)', which contain ...
def find_missing_number(arr): n = len(arr) + 1 expected_sum = n * (n + 1) // 2 actual_sum = sum(arr) return expected_sum - actual_sum
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the missing number in an array of numbers containing N elements. The array is an unsorted sequence of integers from 1 to N, with exactly one number missing.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2346, "level": 1, "question": "Write a python function to find the missing number in an array of numbers containing N elements. The array is an unsorted sequence of integers from 1 to N, with exactly one number missing.", "split": "train" }
def subarray_sum(nums: list[int], k: int) -> int: prefix_counts = {0: 1} current_sum = 0 result = 0 for num in nums: current_sum += num if (current_sum - k) in prefix_counts: result += prefix_counts[current_sum - k] prefix_counts[current_sum] = prefix_counts.get(curre...
simplelr_Algorithm
[ { "content": "Question:\n### Subarray Sum Equals k\n\n#### Problem Statement\nGiven an array of integers `nums` and an integer `k`, you need to find the total number of continuous subarrays whose sum equals to `k`.\n\nYour task is to implement a function that efficiently counts all such subarrays. You are requi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2347, "level": 1, "question": "### Subarray Sum Equals k\n\n#### Problem Statement\nGiven an array of integers `nums` and an integer `k`, you need to find the total number of continuous subarrays whose sum equals to `k`.\n\nYour task is to implement a function that efficiently count...
def longest_binary_gap(N: int) -> int: binary_str = bin(N)[2:] # Convert to binary without '0b' prefix if len(binary_str) < 2: return 0 # No binary gap possible with less than two digits # Generate run-length encoding of the binary string run_list = [] current = binary_str[0] coun...
simplelr_Taco
[ { "content": "Question:\nImplement a function to determine the length of the longest binary gap within a given positive integer $N$. A binary gap within a positive integer $N$ is defined as a maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of $N$.\n\nWr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2348, "level": 1, "question": "Implement a function to determine the length of the longest binary gap within a given positive integer $N$. A binary gap within a positive integer $N$ is defined as a maximal sequence of consecutive zeros that is surrounded by ones at both ends in the ...
def generate_even_numbers(start, end): even_numbers = [num for num in range(start, end + 1) if num % 2 == 0] divisible_by_four = [num for num in even_numbers if num % 4 == 0] return divisible_by_four
simplelr_Evol
[ { "content": "Question:\nDevise a procedural method, utilizing Python's list comprehension technique, to generate a list of all the even numbers within a specified range, and subsequently filter this list to include only those values that are divisible by 4. Start and end values of the range are provided as inp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2349, "level": 1, "question": "Devise a procedural method, utilizing Python's list comprehension technique, to generate a list of all the even numbers within a specified range, and subsequently filter this list to include only those values that are divisible by 4. Start and end valu...
import numpy as np import matplotlib.pyplot as plt import seaborn as sns def demonstrate_plotting_context(): print("Current default context:") print(sns.plotting_context()) # Save the default context to restore later default_context = sns.plotting_context().copy() x = np.linspace(0, 10, 2...
simplelr_Docs
[ { "content": "Question:\n<|Analysis Begin|>\n\nThe provided documentation highlights the `sns.plotting_context()` function in the seaborn library. The documentation explains how to:\n- Retrieve the current default values for the plotting context parameters.\n- View the values of predefined styles using the func...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2350, "level": 1, "question": "<|Analysis Begin|>\n\nThe provided documentation highlights the `sns.plotting_context()` function in the seaborn library. The documentation explains how to:\n- Retrieve the current default values for the plotting context parameters.\n- View the values ...
def grade_exam(answer_key: list[str], student_answers: list[str]) -> int: score = 0 for correct, student in zip(answer_key, student_answers): if correct == student: score += 1 return score
simplelr_Algorithm
[ { "content": "Question:\n### Context\nYou are tasked with developing a system to automate the grading of multiple-choice exam answers. Students' answers will be compared against a provided answer key to compute their scores.\n\n### Task\nWrite a function to grade the multiple-choice exams based on the given ans...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2351, "level": 1, "question": "### Context\nYou are tasked with developing a system to automate the grading of multiple-choice exam answers. Students' answers will be compared against a provided answer key to compute their scores.\n\n### Task\nWrite a function to grade the multiple-...
def is_power_of_two(num): if num == 0: return False return (num & (num - 1)) == 0
simplelr_Data_Structure
[ { "content": "Question:\nOptimized Power-of-Two Calculator\n\n#### Context\nDevelop an efficient function to determine if a given non-negative integer is a power of two. This understanding is crucial in fields like computer graphics, memory management, and digital signal processing. Powers of two often represen...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2352, "level": 1, "question": "Optimized Power-of-Two Calculator\n\n#### Context\nDevelop an efficient function to determine if a given non-negative integer is a power of two. This understanding is crucial in fields like computer graphics, memory management, and digital signal proce...
def calculate_triangle_area(base, height): """ Calculates the area of a triangle. Args: base (int): The base of the triangle. height (int): The height of the triangle. Returns: float: The area of the triangle. Raises: ValueError: If either the base or height is not...
simplelr_Filter
[ { "content": "Question:\nYou have been tasked with creating a function that calculates the area of a triangle given its base and height. However, there are some additional requirements that need to be considered. The function should only work for triangles where the base and height are both positive integers. T...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2353, "level": 1, "question": "You have been tasked with creating a function that calculates the area of a triangle given its base and height. However, there are some additional requirements that need to be considered. The function should only work for triangles where the base and h...
import heapq def minMeetingRooms(intervals): if not intervals: return 0 # Sort intervals based on start time intervals.sort(key=lambda x: x[0]) heap = [] for start, end in intervals: if heap and heap[0] <= start: heapq.heappop(heap) heapq.heappush(heap, end) ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a series of `n` events represented by a list of `intervals`, where each interval is a tuple of two integers `(start, end)` representing the start and end times of the event. Your task is to determine the minimum number of conference rooms required to host all the events. T...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2354, "level": 1, "question": "You are given a series of `n` events represented by a list of `intervals`, where each interval is a tuple of two integers `(start, end)` representing the start and end times of the event. Your task is to determine the minimum number of conference rooms...
from typing import List def longest_subarray_with_divisible_sum(arr: List[int], k: int) -> int: mod_map = {0: -1} current_mod = 0 max_length = 0 for i, num in enumerate(arr): current_mod = (current_mod + num) % k if current_mod in mod_map: current_length = i - mod_map[curren...
simplelr_Apps
[ { "content": "Question:\nYou are given an integer `N` and an array of `N` integers. Find the longest subarray whose sum is divisible by `k`. \n\nFunction Signature: `def longest_subarray_with_divisible_sum(arr: List[int], k: int) -> int:`\n\n### Input\n- `arr` which is a list of `N` integers (1 <= N <= 10^5, -1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2355, "level": 1, "question": "You are given an integer `N` and an array of `N` integers. Find the longest subarray whose sum is divisible by `k`. \n\nFunction Signature: `def longest_subarray_with_divisible_sum(arr: List[int], k: int) -> int:`\n\n### Input\n- `arr` which is a list ...
from typing import List, Dict def paginate_ranked_users(scores: List[int], page_number: int, users_per_page: int) -> List[Dict[str, int]]: sorted_scores = sorted(scores, reverse=True) first_occurrence = {} for index, score in enumerate(sorted_scores): if score not in first_occurrence: f...
simplelr_Package
[ { "content": "Question:\nYou are given the task to implement a rank-based pagination system for a list of user scores. The ranking should be determined by the user's scores, where a higher score receives a higher rank, and users with the same score should share the same rank.\n\nSpecifically, you need to create...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2356, "level": 1, "question": "You are given the task to implement a rank-based pagination system for a list of user scores. The ranking should be determined by the user's scores, where a higher score receives a higher rank, and users with the same score should share the same rank.\...
from typing import List, Tuple def quickest_responder(times: List[Tuple[int, int]]) -> int: """ Finds the employee ID with the fastest average email response time. Parameters: times (List[Tuple[int, int]]): A list where each element is a tuple containing an employee ID and their email response tim...
simplelr_Algorithm
[ { "content": "Question:\n### Question\nA company wants to evaluate its employees' efficiency based on their email response times. You are tasked with writing a function that organizes the email response times and identifies the employee with the quickest average response time over a given period.\n\n**Function ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2357, "level": 1, "question": "### Question\nA company wants to evaluate its employees' efficiency based on their email response times. You are tasked with writing a function that organizes the email response times and identifies the employee with the quickest average response time ...
import math def shortest_distance(point: tuple[float, float], segment_start: tuple[float, float], segment_end: tuple[float, float]) -> float: Ax, Ay = segment_start Bx, By = segment_end Px, Py = point ABx = Bx - Ax ABy = By - Ay APx = Px - Ax APy = Py - Ay dot_ap_ab = ABx * APx + ABy...
simplelr_Algorithm
[ { "content": "Question:\n### Background\nIn computer graphics, a common problem is to determine the shortest distance from a point to a line segment. This is useful in various applications such as collision detection, object alignment, and more. Given a line segment defined by two endpoints and a point in 2D sp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2358, "level": 1, "question": "### Background\nIn computer graphics, a common problem is to determine the shortest distance from a point to a line segment. This is useful in various applications such as collision detection, object alignment, and more. Given a line segment defined by...
def char_frequency(s): freq = {} for c in s: freq[c] = freq.get(c, 0) + 1 return freq
simplelr_Apps
[ { "content": "Question:\nImplement a function that takes a string and returns a dictionary with the frequency count of each character (case-sensitive) in the string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2359, "level": 1, "question": "Implement a function that takes a string and returns a dictionary with the frequency count of each character (case-sensitive) in the string.", "split": "train" }
def add(a, b): a_val = a if a is not None else 0 b_val = b if b is not None else 0 return a_val + b_val
simplelr_Prefill
[ { "content": "Question:\nWrite a function to compute the sum of two numbers and return the result. The function should handle the case where either or both of the inputs are `None`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2360, "level": 1, "question": "Write a function to compute the sum of two numbers and return the result. The function should handle the case where either or both of the inputs are `None`.", "split": "train" }
import re from collections import defaultdict def word_count(word_list): word_counts = defaultdict(int) for string in word_list: words = string.split() for word in words: lower_word = word.lower() processed = re.sub(r'^[^a-zA-Z]+|[^a-zA-Z]+$', '', lower_word) ...
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that takes a list of strings and returns a dictionary where each key is a unique word and the value is the count of how many times that word appears in the list. The function should ignore case sensitivity and handle punctuation.\nAnswer:\nLet's think step by st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2361, "level": 1, "question": "Create a Python function that takes a list of strings and returns a dictionary where each key is a unique word and the value is the count of how many times that word appears in the list. The function should ignore case sensitivity and handle punctuatio...
def convert(s, n): if n == 1 or n >= len(s): return s rows = [''] * n current_row = 0 direction = 1 # 1 for down, -1 for up for char in s: rows[current_row] += char if current_row == 0: direction = 1 elif current_row == n - 1: direction = -1 ...
simplelr_Filter
[ { "content": "Question:\n[Problem description] You have to write a python code to solve this problem: The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows. Then it is read out row by row.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2362, "level": 1, "question": "[Problem description] You have to write a python code to solve this problem: The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows. Then it is read out row by row.", "split": "train" }
import math def is_perfect_square(n): if n < 0: return False if isinstance(n, float): if not n.is_integer(): return False n = int(n) root = math.isqrt(n) return root * root == n
simplelr_Prefill
[ { "content": "Question:\nWrite a function to check if a given number is a perfect square. The function should return True if the number is a perfect square, and False otherwise. For example, 16 is a perfect square because its square root is 4, and 9 is also a perfect square because its square root is 3. However...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2363, "level": 1, "question": "Write a function to check if a given number is a perfect square. The function should return True if the number is a perfect square, and False otherwise. For example, 16 is a perfect square because its square root is 4, and 9 is also a perfect square be...
def restore_and_check_sorted(stack: list) -> bool: for i in range(len(stack) - 1): if stack[i] > stack[i + 1]: return False return True
simplelr_Data_Structure
[ { "content": "Question:\n### Question\n\nYou are provided with a stack of integers implemented using a list. Your task is to implement a `restore_and_check_sorted` function that:\n1. Checks if the elements in the stack are sorted in ascending order from bottom to top.\n2. Ensures that the original stack is rest...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2364, "level": 1, "question": "### Question\n\nYou are provided with a stack of integers implemented using a list. Your task is to implement a `restore_and_check_sorted` function that:\n1. Checks if the elements in the stack are sorted in ascending order from bottom to top.\n2. Ensu...
def minAbsDifference(arr): arr.sort() min_diff = float('inf') for i in range(len(arr) - 1): diff = arr[i+1] - arr[i] if diff < min_diff: min_diff = diff return min_diff
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers, write a function to find the minimum absolute difference between any two elements in the array. You should return the minimum absolute difference.\nExample 1:\nInput: [3, 8, 15, 17]\nOutput: 2\nExplanation: The minimum absolute difference is between 15 and 17...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2365, "level": 1, "question": "Given an array of integers, write a function to find the minimum absolute difference between any two elements in the array. You should return the minimum absolute difference.\nExample 1:\nInput: [3, 8, 15, 17]\nOutput: 2\nExplanation: The minimum absol...
def sum_of_sublist(numbers, start, end): if start > end: return None return sum(numbers[start:end+1])
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the sum of a sublist of numbers in a list. The function should accept three parameters: the list of numbers, the starting index, and the ending index of the sublist. If the starting index is greater than the ending index, the function should return `None`...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2366, "level": 1, "question": "Write a python function to find the sum of a sublist of numbers in a list. The function should accept three parameters: the list of numbers, the starting index, and the ending index of the sublist. If the starting index is greater than the ending index...
def update_nested_dict(d, path, value): if not path: raise ValueError("Path must not be empty") current = d for key in path[:-1]: if key not in current or not isinstance(current[key], dict): current[key] = {} current = current[key] current[path[-1]] = value
simplelr_Filter
[ { "content": "Question:\nHow can I solve the problem of updating the value of a key in a nested dictionary in Python, ensuring that all keys in the path exist or creating them if they don't?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2367, "level": 1, "question": "How can I solve the problem of updating the value of a key in a nested dictionary in Python, ensuring that all keys in the path exist or creating them if they don't?", "split": "train" }
def is_balanced(s): stack = [] bracket_map = {')': '(', '}': '{', ']': '['} opening = {'(', '{', '['} for c in s: if c in opening: stack.append(c) elif c in bracket_map: if not stack: return False top = stack.pop() if b...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check if a given string contains a balanced set of brackets.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2368, "level": 1, "question": "Write a python function to check if a given string contains a balanced set of brackets.", "split": "train" }
def bit_manipulation(num: int, i: int, action: str, bit: int = None) -> int: if action == 'get': return 1 if (num & (1 << i)) else 0 elif action == 'set': return num | (1 << i) elif action == 'clear': return num & ~(1 << i) elif action == 'update': return (num & ~(1 << i)...
simplelr_Data_Structure
[ { "content": "Question:\n#### Context\nYou are working on a low-level embedded system project. The project involves manipulating specific bits within integers to set flags or achieve efficient state management. To perform these operations effectively, you need to write functions that handle bit manipulation rel...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2369, "level": 1, "question": "#### Context\nYou are working on a low-level embedded system project. The project involves manipulating specific bits within integers to set flags or achieve efficient state management. To perform these operations effectively, you need to write functio...
def count_above_median(salaries): if not salaries: return 0 sorted_sal = sorted(salaries) n = len(sorted_sal) if n % 2 == 1: median = sorted_sal[n // 2] else: median = (sorted_sal[n // 2 - 1] + sorted_sal[n // 2]) / 2 count = 0 for sal in salaries: if sal > me...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a 0-indexed integer array `salaries` where each element represents the salary of an employee. Calculate the total number of employees whose salary is above the median salary of the array. Note that the median is the middle element when the array is sorted in non-decreasing...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2370, "level": 1, "question": "You are given a 0-indexed integer array `salaries` where each element represents the salary of an employee. Calculate the total number of employees whose salary is above the median salary of the array. Note that the median is the middle element when th...
from typing import List def find_vowels(ascii_list: List[str]) -> List[str]: vowels = {'a', 'e', 'i', 'o', 'u'} result = [] for s in ascii_list: code = int(s) c = chr(code) if c in vowels: result.append(c) else: result.append('not vowel') return r...
simplelr_Code_Contests
[ { "content": "Question:\nCreate a function that takes a list of digit strings and returns a list of vowels based on a specific rule. \nEach digit string represents an ASCII value. The function should first convert each digit string to its respective ASCII character and then return whether the character is a vow...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2371, "level": 1, "question": "Create a function that takes a list of digit strings and returns a list of vowels based on a specific rule. \nEach digit string represents an ASCII value. The function should first convert each digit string to its respective ASCII character and then re...
def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n - 1)
simplelr_Filter
[ { "content": "Question:\nWrite a function to find the factorial of a number using recursion. Explain each part of your code as you go.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2372, "level": 1, "question": "Write a function to find the factorial of a number using recursion. Explain each part of your code as you go.", "split": "train" }
import numpy as np import seaborn as sns import matplotlib.pyplot as plt def visualize_error_bars(): # Step 1: Create a synthetic dataset with 150 data points np.random.seed(42) data = np.random.normal(0, 1, 150) # Create a group variable for categorical plotting group = np.repeat('A', 150) ...
simplelr_Docs
[ { "content": "Question:\nYou are given a dataset containing continuous numeric data. Your task is to visualize this dataset using seaborn while demonstrating your understanding of different types of error bars. Follow the instructions below to implement the required functionality:\n\n#### Dataset\nCreate a synt...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2373, "level": 1, "question": "You are given a dataset containing continuous numeric data. Your task is to visualize this dataset using seaborn while demonstrating your understanding of different types of error bars. Follow the instructions below to implement the required functional...
def coin_change(coins, amount): if amount == 0: return 0 # Filter out non-positive coin values coins = [c for c in coins if c > 0] if not coins: return -1 # No coins available to make a positive amount max_amount = amount dp = [float('inf')] * (max_amount + 1) dp[0] = 0 # B...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to solve the coin change problem. The function should return the minimum number of coins required to make up the amount. If that amount of money cannot be made up by any combination of the coins, the function should return `-1`. The function should use dynamic programmi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2374, "level": 1, "question": "Write a function to solve the coin change problem. The function should return the minimum number of coins required to make up the amount. If that amount of money cannot be made up by any combination of the coins, the function should return `-1`. The fu...
def count_even_sum_subarrays(arr): MOD = 10**9 + 7 current_parity = 0 # 0 for even, 1 for odd even_count = 1 # Initially accounts for the 0 prefix sum odd_count = 0 result = 0 for num in arr: current_parity = (current_parity + num) % 2 if current_parity == 0: ...
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `arr`, a **subarray** is a contiguous part of an array. A **subarray sum** is the sum of all elements in that subarray. Return the number of subarrays that have an even sum. Since the number can be large, return the result **modulo** `10^9 + 7`.\nAnswer:\nLet's th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2375, "level": 1, "question": "Given an integer array `arr`, a **subarray** is a contiguous part of an array. A **subarray sum** is the sum of all elements in that subarray. Return the number of subarrays that have an even sum. Since the number can be large, return the result **modu...
def find_largest_integer(s): return max(map(int, s.split()))
simplelr_Taco
[ { "content": "Question:\nWrite a function `find_largest_integer` that takes a string containing a list of space-separated integers and returns the largest integer in the list. Your task is to identify the largest number among the provided integers.\n\n**Constraints:**\n- The string will contain at least one int...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2376, "level": 1, "question": "Write a function `find_largest_integer` that takes a string containing a list of space-separated integers and returns the largest integer in the list. Your task is to identify the largest number among the provided integers.\n\n**Constraints:**\n- The s...
def find_kth_largest(arr, k): n = len(arr) if k < 1 or k > n: return -1 sorted_arr = sorted(arr) return sorted_arr[-k]
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes an integer array and an integer k, and returns the k-th largest element in the array.\n\nFor instance, given the array [3,2,1,5,6,4] and k = 2, the second largest element is 5. If k is greater than the length of the array, the function returns -1.\n\nExamples...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2377, "level": 1, "question": "Write a function that takes an integer array and an integer k, and returns the k-th largest element in the array.\n\nFor instance, given the array [3,2,1,5,6,4] and k = 2, the second largest element is 5. If k is greater than the length of the array, t...
import heapq def prims_minimum_spanning(graph_used: dict) -> int: if not graph_used: return 0 # Select a starting node (choosing the first key in the graph) start_node = next(iter(graph_used.keys())) visited = set() visited.add(start_node) heap = [] total_weight = 0 # Push...
simplelr_Data_Structure
[ { "content": "Question:\nPrim's MST Implementation\n\n#### Context\nYou work as a network engineer, tasked with designing an optimal local area network (LAN) for an office. To minimize costs, you need to ensure that the network uses the least amount of cable while still ensuring all computers are connected. Giv...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2378, "level": 1, "question": "Prim's MST Implementation\n\n#### Context\nYou work as a network engineer, tasked with designing an optimal local area network (LAN) for an office. To minimize costs, you need to ensure that the network uses the least amount of cable while still ensuri...
def reverse_integer(n): is_negative = False if n < 0: is_negative = True n = -n reversed_n = int(str(n)[::-1]) return -reversed_n if is_negative else reversed_n
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to reverse the digits of a given integer. The function should handle both positive and negative integers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2379, "level": 1, "question": "Write a Python function to reverse the digits of a given integer. The function should handle both positive and negative integers.", "split": "train" }
def isMatch(s, p): n = len(s) m = len(p) dp = [[False] * (m + 1) for _ in range(n + 1)] dp[0][0] = True # Empty string matches empty pattern # Initialize the first row where the string is empty for j in range(1, m + 1): dp[0][j] = dp[0][j-1] and (p[j-1] == '*') # Fill the ...
simplelr_Code_Contests
[ { "content": "Question:\nDesign a function that can determine if an input string matches a simple pattern. The pattern can include characters in the string and special wildcard characters: '?' and '*'. The '?' character matches any single character while the '*' character matches any sequence of characters (inc...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2380, "level": 1, "question": "Design a function that can determine if an input string matches a simple pattern. The pattern can include characters in the string and special wildcard characters: '?' and '*'. The '?' character matches any single character while the '*' character matc...
def min_teams_to_advance(scores): if not scores: return 0 current_max = scores[0] count = 1 for score in scores[1:]: if score > current_max: count += 1 current_max = score return count
simplelr_Leetcode
[ { "content": "Question:\nYou are organizing a game tournament for several teams. Each team can have a score between 1 and 100. You are given an array `scores` where `scores[i]` represents the score of the `i-th` team. A team can only advance to the next round if its score is greater than the scores of all the t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2381, "level": 1, "question": "You are organizing a game tournament for several teams. Each team can have a score between 1 and 100. You are given an array `scores` where `scores[i]` represents the score of the `i-th` team. A team can only advance to the next round if its score is g...
def find_earliest_transaction(transactions): sorted_transactions = sorted(transactions, key=lambda x: (x[1], x[0])) return sorted_transactions[0]
simplelr_Evol
[ { "content": "Question:\n### Coding Assessment Question\n\nYou are working on a program that processes a list of transaction records. Each transaction is represented by a tuple containing a transaction ID, a timestamp, and an amount. Given a list of such transactions, you need to write a function that returns t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2382, "level": 1, "question": "### Coding Assessment Question\n\nYou are working on a program that processes a list of transaction records. Each transaction is represented by a tuple containing a transaction ID, a timestamp, and an amount. Given a list of such transactions, you need...
def sorted_squares(numbers): squared = [num ** 2 for num in numbers] squared.sort() return squared
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers and returns a list of their squares. The function should also handle negative numbers and ensure that the output list is sorted in ascending order.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2383, "level": 1, "question": "Create a function that takes a list of integers and returns a list of their squares. The function should also handle negative numbers and ensure that the output list is sorted in ascending order.", "split": "train" }
def is_triple_increasing_subsequence(sequence): n = len(sequence) if n < 3: return False min1 = sequence[0] min2 = None for num in sequence[1:]: if num < min1: min1 = num elif num > min1: if min2 is None: min2 = num ...
simplelr_Taco
[ { "content": "Question:\nGiven a sequence of $N$ integers, determine if it contains an increasing subsequence of length 3. An increasing subsequence is a sequence of numbers such that each number is greater than the one before it.\n\nConcept\n\nA subsequence is a sequence derived by removing some or none of the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2384, "level": 1, "question": "Given a sequence of $N$ integers, determine if it contains an increasing subsequence of length 3. An increasing subsequence is a sequence of numbers such that each number is greater than the one before it.\n\nConcept\n\nA subsequence is a sequence deri...
import numpy as np from scipy.spatial.distance import cdist def FindNearestNeighbors(X, k): # Compute the pairwise distance matrix D = cdist(X, X) # Set the diagonal elements (self-distances) to infinity N = X.shape[0] for i in range(N): D[i, i] = np.inf # Find the indices of ...
simplelr_Package
[ { "content": "Question:\nIn machine learning and data science, understanding how to efficiently manipulate and process large datasets is crucial. One such frequent operation is finding the nearest neighbors for each sample in a dataset. Given the challenge of computing the Euclidean distance between points in h...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2385, "level": 1, "question": "In machine learning and data science, understanding how to efficiently manipulate and process large datasets is crucial. One such frequent operation is finding the nearest neighbors for each sample in a dataset. Given the challenge of computing the Euc...
def largest_rectangle_area(height): stack = [-1] # Initialize stack with -1 to handle the boundary case max_area = 0 for i in range(len(height)): # While the current height is smaller than the top of the stack, pop and calculate area while stack[-1] != -1 and height[i] < height[stack[-1]]: ...
simplelr_Codeforces
[ { "content": "Question:\nSuppose you have an array of integers where each element represents the height of a bar in a histogram. The width of each bar is 1. Write a function in your preferred programming language to find the maximum rectangular area that can be formed within the histogram. For example, given th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2386, "level": 1, "question": "Suppose you have an array of integers where each element represents the height of a bar in a histogram. The width of each bar is 1. Write a function in your preferred programming language to find the maximum rectangular area that can be formed within t...
def fibonacci(n): if n <= 0: return 0 elif n == 1: return 1 fib = [0, 1] for i in range(2, n + 1): next_num = fib[1] + fib[0] fib[0] = fib[1] fib[1] = next_num return fib[1]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the nth Fibonacci number using dynamic programming. The function should optimize performance for large values of n by storing previously calculated Fibonacci numbers in a memory-efficient data structure.\nAnswer:\nLet's think step by step.\n", "role":...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2387, "level": 1, "question": "Write a python function to find the nth Fibonacci number using dynamic programming. The function should optimize performance for large values of n by storing previously calculated Fibonacci numbers in a memory-efficient data structure.", "split": "tr...
import torch def special_operations(input_tensor: torch.Tensor) -> torch.Tensor: step1 = torch.exp(input_tensor) step2 = torch.log(1 + step1) step3 = torch.sigmoid(step2) step4 = torch.special.erf(step3) step5 = torch.special.bessel_j0(step4) return step5
simplelr_Docs
[ { "content": "Question:\n### PyTorch Special Functions Coding Assessment\n\n#### Objective\nImplement a function that computes a combination of special mathematical functions from the `torch.special` module on given tensor inputs.\n\n#### Description\nYou are tasked with implementing a function in PyTorch that ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2388, "level": 1, "question": "### PyTorch Special Functions Coding Assessment\n\n#### Objective\nImplement a function that computes a combination of special mathematical functions from the `torch.special` module on given tensor inputs.\n\n#### Description\nYou are tasked with imple...
def manage_inventory(transactions: list) -> dict: inventory = {} for transaction in transactions: op, item, qty = transaction if op == 'restock': inventory[item] = inventory.get(item, 0) + qty else: current = inventory.get(item, 0) new_qty = max(curren...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Question: Inventory Management System\n\n#### Scenario\nYou are tasked with developing an inventory management system for a small store. The system keeps track of the items in stock, the quantity of each item, and allows for restocking and selling of items. Your task is to im...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2389, "level": 1, "question": "### Coding Question: Inventory Management System\n\n#### Scenario\nYou are tasked with developing an inventory management system for a small store. The system keeps track of the items in stock, the quantity of each item, and allows for restocking and s...
def group_by_first_letter(words): result = {} for word in words: key = word[0].lower() if key in result: result[key].append(word) else: result[key] = [word] return result
simplelr_Package
[ { "content": "Question:\nYou are tasked with writing a function called `group_by_first_letter` that takes in a list of strings and groups them by their starting letter. The function should return a dictionary where the keys are the starting letters, and the values are lists of strings that start with the respec...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2390, "level": 1, "question": "You are tasked with writing a function called `group_by_first_letter` that takes in a list of strings and groups them by their starting letter. The function should return a dictionary where the keys are the starting letters, and the values are lists of...
def find_anagrams(s, word_list): s_sorted = sorted(s) anagrams = [] for word in word_list: if len(word) != len(s): continue if sorted(word) == s_sorted: anagrams.append(word) return anagrams
simplelr_Filter
[ { "content": "Question:\nGiven a non-empty list of strings, write a function that returns all possible anagrams of a given string. The function should take a string and a list of strings as input and return a list of strings that are anagrams of the given string.\nAnswer:\nLet's think step by step.\n", "rol...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2391, "level": 1, "question": "Given a non-empty list of strings, write a function that returns all possible anagrams of a given string. The function should take a string and a list of strings as input and return a list of strings that are anagrams of the given string.", "split": ...
def longest_unique_substring(s): if not s: return ("", 0) char_index = {} left = 0 max_len = 0 start = 0 for right in range(len(s)): char = s[right] if char in char_index and char_index[char] >= left: left = char_index[char] + 1 char_index[ch...
simplelr_Evol
[ { "content": "Question:\nDesign a function in Python that processes a given string to identify the longest substring without repeating characters. The function should return both the longest substring and its length. You must also handle edge cases such as an empty string or a string with all identical characte...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2392, "level": 1, "question": "Design a function in Python that processes a given string to identify the longest substring without repeating characters. The function should return both the longest substring and its length. You must also handle edge cases such as an empty string or a...
def tuples_to_dict(tuple_list): return dict(tuple_list)
simplelr_Filter
[ { "content": "Question:\nPlease provide a Python function to convert a list of tuples to a dictionary, where each tuple contains a key and a value.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2393, "level": 1, "question": "Please provide a Python function to convert a list of tuples to a dictionary, where each tuple contains a key and a value.", "split": "train" }
import re from typing import List def extract_emails(file_path: str) -> List[str]: with open(file_path, 'r') as f: content = f.read() pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+' emails = re.findall(pattern, content) return emails
simplelr_Package
[ { "content": "Question:\nIn this task, you need to develop a function named `extract_emails(file_path: str) -> List[str]` that reads a text file and extracts all valid email addresses. The emails can be scattered throughout the text and may appear in different formats, mixed with other text. You should use regu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2394, "level": 1, "question": "In this task, you need to develop a function named `extract_emails(file_path: str) -> List[str]` that reads a text file and extracts all valid email addresses. The emails can be scattered throughout the text and may appear in different formats, mixed w...
def largestPerimeter(nums): nums.sort(reverse=True) n = len(nums) for i in range(n - 2): a, b, c = nums[i], nums[i+1], nums[i+2] if b + c > a: return a + b + c return 0
simplelr_Taco
[ { "content": "Question:\nGiven an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.\n\nExample 1:\nInput:\nnums = [2, 1, 2]\nOutput: 5\nExplanation: You can form a triang...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2395, "level": 1, "question": "Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.\n\nExample 1:\nInput:\nnums = [2, 1, 2]\nOutput: 5\...
def remove_duplicates(lst): seen = set() result = [] for num in lst: if num not in seen: seen.add(num) result.append(num) return result
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers and returns the same list with all duplicate values removed. You should preserve the order in which the elements appeared in the original list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2396, "level": 1, "question": "Create a function that takes a list of integers and returns the same list with all duplicate values removed. You should preserve the order in which the elements appeared in the original list.", "split": "train" }
def decimal_to_twos_complement(decimal, bit_length): if decimal >= 0: binary_str = bin(decimal)[2:] # Convert to binary and remove '0b' prefix if len(binary_str) > bit_length: # Truncate to the last 'bit_length' bits binary_str = binary_str[-bit_length:] else: ...
simplelr_Filter
[ { "content": "Question:\nImplement a function in Python that converts a given decimal number to its 2's complement binary representation. The function should take two parameters: the decimal number and the bit length of the binary representation. Ensure the function returns a string with the appropriate binary ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2397, "level": 1, "question": "Implement a function in Python that converts a given decimal number to its 2's complement binary representation. The function should take two parameters: the decimal number and the bit length of the binary representation. Ensure the function returns a ...
import seaborn.objects as so import seaborn as sns def create_customized_barplot(): # Load the tips dataset tips = sns.load_dataset("tips").astype({"time": str}) # Create the plot with x as day, y as total_bill, and color based on time p = so.Plot(tips, "day", "total_bill", color="time") ...
simplelr_Docs
[ { "content": "Question:\n### Advanced Plot Manipulation with Seaborn\n\n#### Objective\nIn this coding assessment, you will create a customized bar plot using the Seaborn `so.Plot` interface. Your task is to leverage the Dodge transformation and additional parameters to modify the plot. This will test your abil...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2398, "level": 1, "question": "### Advanced Plot Manipulation with Seaborn\n\n#### Objective\nIn this coding assessment, you will create a customized bar plot using the Seaborn `so.Plot` interface. Your task is to leverage the Dodge transformation and additional parameters to modify...
def group_anagrams(strs): anagrams = {} for word in strs: key = ''.join(sorted(word)) if key in anagrams: anagrams[key].append(word) else: anagrams[key] = [word] return list(anagrams.values())
simplelr_Filter
[ { "content": "Question:\n### Group Anagrams\n\nGiven an array of strings, group anagrams together.\n\nExample:\n```\nInput: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]\nOutput:\n[\n [\"eat\",\"tea\",\"ate\"],\n [\"tan\",\"nat\"],\n [\"bat\"]\n]\n```\n\nNote:\n* All inputs will be in lowercase.\n* ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 2399, "level": 1, "question": "### Group Anagrams\n\nGiven an array of strings, group anagrams together.\n\nExample:\n```\nInput: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]\nOutput:\n[\n [\"eat\",\"tea\",\"ate\"],\n [\"tan\",\"nat\"],\n [\"bat\"]\n]\n```\n\nNote:\n* A...