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 is_match(s: str, p: str) -> bool: m = len(s) n = len(p) dp = [[False] * (n + 1) for _ in range(m + 1)] dp[0][0] = True # Empty string matches empty pattern for i in range(m + 1): for j in range(1, n + 1): if p[j-1] == '*': # Handle the case where '*' is pres...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are given a string `s` and a pattern `p`. Your task is to write a function `is_match(s: str, p: str) -> bool` which determines if the string `s` matches the pattern `p`. The pattern `p` may contain characters and special characters:\n- `.` which matches any si...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9700, "level": 1, "question": "### Problem Statement\nYou are given a string `s` and a pattern `p`. Your task is to write a function `is_match(s: str, p: str) -> bool` which determines if the string `s` matches the pattern `p`. The pattern `p` may contain characters and special char...
def sanitize_string(text: str, chars_to_remove: str) -> str: remove_chars = set(chars_to_remove) filtered_text = ''.join([c for c in text if c not in remove_chars]) return ' '.join(filtered_text.split())
simplelr_Algorithm
[ { "content": "Question:\n### Scenario\nYou are required to develop a function that processes a string to sanitize and prepare it for a hypothetical secure transmission. This includes removing specified characters and normalizing spaces.\n\n### Problem Statement\nWrite a function `sanitize_string(text: str, char...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9701, "level": 1, "question": "### Scenario\nYou are required to develop a function that processes a string to sanitize and prepare it for a hypothetical secure transmission. This includes removing specified characters and normalizing spaces.\n\n### Problem Statement\nWrite a functi...
def find_nth_digit(n: int) -> int: digits = 1 count = 9 start = 1 while n > digits * count: n -= digits * count digits += 1 count *= 10 start *= 10 number = start + (n - 1) // digits digit_index = (n - 1) % digits return int(str(number)[digit_index])
simplelr_Data_Structure
[ { "content": "Question:\nYou are given a very large sequence formed by concatenating all natural numbers starting from 1 together (e.g., \"123456789101112...\"). Write a function:\n\n```python\ndef find_nth_digit(n: int) -> int:\n pass\n```\n\nThis function should take an integer `n` and return the nth digit...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9702, "level": 1, "question": "You are given a very large sequence formed by concatenating all natural numbers starting from 1 together (e.g., \"123456789101112...\"). Write a function:\n\n```python\ndef find_nth_digit(n: int) -> int:\n pass\n```\n\nThis function should take an i...
def factorial(n): if n <= 1: return 1 # Base case else: return n * factorial(n-1) # Recursive case
simplelr_Filter
[ { "content": "Question:\nI am learning Python and I'm struggling with the concept of recursion.\n\nCould you please explain it with a simple example?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9703, "level": 1, "question": "I am learning Python and I'm struggling with the concept of recursion.\n\nCould you please explain it with a simple example?", "split": "train" }
def factorial_of_odd(num): if num < 0 or num % 2 == 0: return None factorial = 1 for i in range(1, num + 1): factorial *= i return factorial
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to calculate the factorial of a given number, but only if the number is odd.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9704, "level": 1, "question": "Write a python function to calculate the factorial of a given number, but only if the number is odd.", "split": "train" }
def rotate(nums, k): if not nums: return [] n = len(nums) k = k % n if k == 0: return list(nums) return nums[-k:] + nums[:-k]
simplelr_Taco
[ { "content": "Question:\nGiven a list of integers, rotate the list to the right by k steps, where k is non-negative.\n\nExample 1:\n\nInput: [1,2,3,4,5,6,7], k = 3\nOutput: [5,6,7,1,2,3,4]\n\nExample 2:\n\nInput: [-1,-100,3,99], k = 2\nOutput: [3,99,-1,-100]\n\nNote:\n\nTry to come up with as many solutions as ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9705, "level": 1, "question": "Given a list of integers, rotate the list to the right by k steps, where k is non-negative.\n\nExample 1:\n\nInput: [1,2,3,4,5,6,7], k = 3\nOutput: [5,6,7,1,2,3,4]\n\nExample 2:\n\nInput: [-1,-100,3,99], k = 2\nOutput: [3,99,-1,-100]\n\nNote:\n\nTry to...
from collections import Counter def reorderToPalindrome(s): s_lower = s.lower() counts = Counter(s_lower) odd_counts = sum(1 for cnt in counts.values() if cnt % 2 != 0) return odd_counts <= 1
simplelr_Apps
[ { "content": "Question:\nWrite a function named `reorderToPalindrome(s)` that checks whether any permutation of the input string `s` can form a palindrome. The function should return `True` if it's possible to rearrange the characters of the string into a palindrome; otherwise, it should return `False`. Note th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9706, "level": 1, "question": "Write a function named `reorderToPalindrome(s)` that checks whether any permutation of the input string `s` can form a palindrome. The function should return `True` if it's possible to rearrange the characters of the string into a palindrome; otherwise...
def int_to_roman(num): if not 1 <= num <= 3999: raise ValueError("Number must be between 1 and 3999") thousands = num // 1000 hundreds_digit = (num // 100) % 10 tens_digit = (num // 10) % 10 units_digit = num % 10 thousands_map = ['', 'M', 'MM', 'MMM'] hundreds_map = [ ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that converts an integer to its Roman numeral representation. Can you provide a Python function for this task?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9707, "level": 1, "question": "Create a function that converts an integer to its Roman numeral representation. Can you provide a Python function for this task?", "split": "train" }
def sum_of_odd_numbers(lst): total = 0 for num in lst: if num % 2 != 0: total += num return total
simplelr_Filter
[ { "content": "Question:\nWrite a code that drops all the even numbers in the list and returns the sum of the remaining odd numbers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9708, "level": 1, "question": "Write a code that drops all the even numbers in the list and returns the sum of the remaining odd numbers.", "split": "train" }
def find_min_removals(s: str) -> tuple: stack = [] keep = [False] * len(s) for i, c in enumerate(s): if c == '(': stack.append(i) else: if stack: j = stack.pop() keep[j] = True keep[i] = True else: ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem: Identify and Correct Invalid Parentheses\n\nYou are given a string containing only parentheses: `(` and `)`. Your task is to write a program that modifies the string to make all parentheses pairs valid. Specifically, you need to determine the minimum number of parentheses t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9709, "level": 1, "question": "### Problem: Identify and Correct Invalid Parentheses\n\nYou are given a string containing only parentheses: `(` and `)`. Your task is to write a program that modifies the string to make all parentheses pairs valid. Specifically, you need to determine ...
def merge_sorted_lists(list1, list2): merged = [] i = j = 0 while i < len(list1) and j < len(list2): if list1[i] <= list2[j]: merged.append(list1[i]) i += 1 else: merged.append(list2[j]) j += 1 merged += list1[i:] merged += list2[j:] ...
simplelr_Evol
[ { "content": "Question:\nIn Python, write a function called `merge_sorted_lists` that takes two lists of integers as input, where each list is already sorted in non-decreasing order. The function should merge these two lists into a single list that is also sorted in non-decreasing order, and return this merged ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9710, "level": 1, "question": "In Python, write a function called `merge_sorted_lists` that takes two lists of integers as input, where each list is already sorted in non-decreasing order. The function should merge these two lists into a single list that is also sorted in non-decrea...
def longest_common_subsequence(s1, s2): m = len(s1) n = len(s2) # Create a DP table with (m+1) rows and (n+1) columns initialized to zero dp = [[0] * (n + 1) for _ in range(m + 1)] # Fill the DP table for i in range(1, m + 1): for j in range(1, n + 1): if s1[i-1] ==...
simplelr_Filter
[ { "content": "Question:\nCan you explain how to create a code snippet that finds the longest common subsequence in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9711, "level": 1, "question": "Can you explain how to create a code snippet that finds the longest common subsequence in Python?", "split": "train" }
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: high = mid - 1 else: low = mid + 1 return -1
simplelr_Filter
[ { "content": "Question:\n### Lesson 9: Binary Search\n#### Problem: Implement Binary Search\nImplement a binary search algorithm to find an element in a sorted list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9712, "level": 1, "question": "### Lesson 9: Binary Search\n#### Problem: Implement Binary Search\nImplement a binary search algorithm to find an element in a sorted list.", "split": "train" }
def max_sum_of_subarray(nums, k): if not nums or k == 0: return 0 n = len(nums) if k > n: return 0 current_sum = sum(nums[:k]) max_sum = current_sum for i in range(k, n): current_sum = current_sum - nums[i - k] + nums[i] if current_sum > max_sum: ...
simplelr_Filter
[ { "content": "Question:\nI need help with an algorithm that can solve a problem where I have to find the maximum sum of a subarray of size `k` within a given array `nums`.\n\nHere is a brute force solution that I'm currently using:\n\n```python\ndef max_sum_of_subarray(nums, k):\n if not nums or k == 0:\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9713, "level": 1, "question": "I need help with an algorithm that can solve a problem where I have to find the maximum sum of a subarray of size `k` within a given array `nums`.\n\nHere is a brute force solution that I'm currently using:\n\n```python\ndef max_sum_of_subarray(nums, k...
import os import time def most_recently_modified_file(directory_path): try: max_timestamp = None latest_file = None for entry in os.scandir(directory_path): if entry.is_file(): timestamp = entry.stat().st_mtime if max_timestamp is None or timestam...
simplelr_Filter
[ { "content": "Question:\nI am trying to determine the last time a file has been modified. \nI have the following piece of code which is not working as expected:\n\n```python\nimport heapq\nimport os\nimport time\n\ndef last_modified(file_path):\n try:\n timestamp = os.path.getmtime(file_path)\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9714, "level": 1, "question": "I am trying to determine the last time a file has been modified. \nI have the following piece of code which is not working as expected:\n\n```python\nimport heapq\nimport os\nimport time\n\ndef last_modified(file_path):\n try:\n timestamp = o...
def two_sum(nums, target): seen = {} for index, num in enumerate(nums): complement = target - num if complement in seen: return [seen[complement], index] seen[num] = index return []
simplelr_Apps
[ { "content": "Question:\nWrite a function that takes an array of integers and a target integer as inputs and returns the indices of the two numbers that add up to the target. Assume that each input would have exactly one solution, and you may not use the same element twice.\n\nExample:\n\n```\nInput: [2, 7, 11,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9715, "level": 1, "question": "Write a function that takes an array of integers and a target integer as inputs and returns the indices of the two numbers that add up to the target. Assume that each input would have exactly one solution, and you may not use the same element twice.\n\...
def rotate_matrix_90_degrees(matrix: list[list[int]]) -> list[list[int]]: N = len(matrix) rotated = [] for j in range(N): new_row = [] for i in range(N-1, -1, -1): new_row.append(matrix[i][j]) rotated.append(new_row) return rotated
simplelr_Package
[ { "content": "Question:\nYou are required to implement a function `rotate_matrix_90_degrees` that rotates an NxN matrix by 90 degrees in a clockwise direction. The input is a list of lists representing the matrix, and you need to return a new matrix that is the result of the rotation.\n\n### Constraints:\n1. Th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9716, "level": 1, "question": "You are required to implement a function `rotate_matrix_90_degrees` that rotates an NxN matrix by 90 degrees in a clockwise direction. The input is a list of lists representing the matrix, and you need to return a new matrix that is the result of the r...
def group_continuous_assignments(assignments): s = set(assignments) visited = set() result = [] for num in s: if num not in visited and (num - 1) not in s: group = [] current = num while current in s and current not in visited: group.append(cur...
simplelr_Filter
[ { "content": "Question:\nI've received an array of integers, which I'll call \"assignments\". I'd like to create a new 2D list, where each sub-list represents a range of integers that consists of one or more continuous assignments.\n\nFor example, given the array `[1, 3, 4, 5, 6, 8, 10, 11, 12, 13, 14]`, I'd l...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9717, "level": 1, "question": "I've received an array of integers, which I'll call \"assignments\". I'd like to create a new 2D list, where each sub-list represents a range of integers that consists of one or more continuous assignments.\n\nFor example, given the array `[1, 3, 4, 5...
def max_subarray_sum(nums): n = len(nums) if n == 0: return 0 extended = nums * 2 # Concatenate nums with itself max_total = float('-inf') for i in range(n): current_sum = sum(extended[i:i+n]) if current_sum > max_total: max_total = current_sum return max_tot...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `nums` representing a contiguous subarray of length `n` of an infinite array formed by repeating the elements of `nums` infinitely, return _the maximum sum of any subarray of length `n` of this infinite array_. If the array is empty, return 0. For example, gi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9718, "level": 1, "question": "Given an array of integers `nums` representing a contiguous subarray of length `n` of an infinite array formed by repeating the elements of `nums` infinitely, return _the maximum sum of any subarray of length `n` of this infinite array_. If the array ...
import math from typing import List def jump_search(arr: List[int], target: int) -> int: n = len(arr) if n == 0: return -1 # Though per constraints, arr is non-empty block_size = int(math.sqrt(n)) start = 0 while start < n and arr[start] <= target: if arr[start] == target: ...
simplelr_Data_Structure
[ { "content": "Question:\n### Context\nYou are working on a search engine that needs to quickly look up keywords from a large, sorted list of entries. One of the algorithms considered for this task is Jump Search due to its efficiency with sorted data.\n\n### Task\nImplement the Jump Search algorithm in Python t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9719, "level": 1, "question": "### Context\nYou are working on a search engine that needs to quickly look up keywords from a large, sorted list of entries. One of the algorithms considered for this task is Jump Search due to its efficiency with sorted data.\n\n### Task\nImplement th...
def filter_strings_starting_with_a(lst): return [s for s in lst if s.startswith('a')]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in a list of strings and returns a new list containing only the strings that start with the letter 'a'. How can this be done in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9720, "level": 1, "question": "Create a function that takes in a list of strings and returns a new list containing only the strings that start with the letter 'a'. How can this be done in Python?", "split": "train" }
from collections import deque def min_steps_to_reach_target(grid): m = len(grid) if m == 0: return -1 n = len(grid[0]) if n == 0: return -1 if grid[0][0] != 0 or grid[m-1][n-1] != 0: return -1 if m == 1 and n == 1: return 0 visited = [[False for _ in ran...
simplelr_Apps
[ { "content": "Question:\nA delivery robot is transporting packages in a factory with an obstacle grid. The factory grid is represented by a 2D array where:\n\n- The value `0` represents an empty cell the robot can pass through.\n- The value `1` represents an obstacle that the robot cannot pass through.\n\nThe r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9721, "level": 1, "question": "A delivery robot is transporting packages in a factory with an obstacle grid. The factory grid is represented by a 2D array where:\n\n- The value `0` represents an empty cell the robot can pass through.\n- The value `1` represents an obstacle that the ...
def generate_words(alphabets, MAXLEN): if not alphabets or MAXLEN < 1: return [] words = [] # Initialize with all possible words of length 1 for alpha in alphabets: words.append(alpha) # Generate words for lengths 2 to MAXLEN for length in range(2, MAXLEN + 1): ...
simplelr_Filter
[ { "content": "Question:\nCan you write a code in python to generate all the possible words that can be formed using a set of given alphabets. \n\nFor example, given a list of alphabets: ['a', 'b', 'c'], it should return ['a', 'b', 'c', 'ab', 'ac', 'ba', 'bc', 'ca', 'cb', 'abc', 'acb', 'bac', 'bca', 'cab', 'cba'...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9722, "level": 1, "question": "Can you write a code in python to generate all the possible words that can be formed using a set of given alphabets. \n\nFor example, given a list of alphabets: ['a', 'b', 'c'], it should return ['a', 'b', 'c', 'ab', 'ac', 'ba', 'bc', 'ca', 'cb', 'abc'...
def is_match(s: str, p: str) -> bool: n = len(s) m = len(p) dp = [[False] * (m + 1) for _ in range(n + 1)] dp[0][0] = True # Empty string matches empty pattern for i in range(n + 1): for j in range(m + 1): if j > 0 and p[j-1] == '*': if j >= 2: ...
simplelr_Data_Structure
[ { "content": "Question:\n### Regular Expression Matching\n\nGiven a string `s` and a pattern `p`, implement a function `bool is_match(const char *s, const char *p)` that checks if the pattern `p` matches the entire string `s`. The pattern string `p` may contain the special characters `.` and `*` which are defin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9723, "level": 1, "question": "### Regular Expression Matching\n\nGiven a string `s` and a pattern `p`, implement a function `bool is_match(const char *s, const char *p)` that checks if the pattern `p` matches the entire string `s`. The pattern string `p` may contain the special cha...
import numpy as np import matplotlib.pyplot as plt def linear_regression(x, y): # Compute the mean of x and y x_mean = np.mean(x) y_mean = np.mean(y) # Calculate the numerator and denominator for the slope numerator = np.sum((x - x_mean) * (y - y_mean)) denominator = np.sum((x - x_mean) **...
simplelr_Package
[ { "content": "Question:\nWrite a function to implement a simple linear regression and visualize the regression line along with the data points. The function should take two NumPy arrays as input: one for the x-values and one for the y-values. It should calculate the best fit line using least squares method, plo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9724, "level": 1, "question": "Write a function to implement a simple linear regression and visualize the regression line along with the data points. The function should take two NumPy arrays as input: one for the x-values and one for the y-values. It should calculate the best fit l...
def merge_sorted_arrays(a, b): result = [] i = j = 0 while i < len(a) and j < len(b): if a[i] < b[j]: result.append(a[i]) i += 1 else: result.append(b[j]) j += 1 # Add remaining elements of a while i < len(a): result.append(a[i]...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that implements a generic algorithm to merge two sorted arrays into a single sorted array. Can you write this function in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9725, "level": 1, "question": "Create a function that implements a generic algorithm to merge two sorted arrays into a single sorted array. Can you write this function in Python?", "split": "train" }
def product_of_array(arr): if not arr: return 1 product = 1 for num in arr: product *= num if product > 1000: return arr[-1] else: return product
simplelr_Prefill
[ { "content": "Question:\nCreate a function that accepts an integer array and returns the product of all the elements in the array. If the array is empty, the function should return 1. If the product of all elements is greater than 1000, the function should return the last element of the array.\nAnswer:\nLet's t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9726, "level": 1, "question": "Create a function that accepts an integer array and returns the product of all the elements in the array. If the array is empty, the function should return 1. If the product of all elements is greater than 1000, the function should return the last elem...
def is_valid(s): stack = [] mapping = {')': '(', '}': '{', ']': '['} for char in s: if char in mapping.values(): stack.append(char) else: if not stack: return False top = stack.pop() if mapping[char] != top: retu...
simplelr_Taco
[ { "content": "Question:\n__Definition:__ A valid parentheses string is a string consisting of only the characters '(', ')', '{', '}', '[' and ']', where:\n\n1. An empty string is valid.\n2. Any valid string enclosed in a pair of matching parentheses of the same type is also valid.\n3. Any valid string concatena...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9727, "level": 1, "question": "__Definition:__ A valid parentheses string is a string consisting of only the characters '(', ')', '{', '}', '[' and ']', where:\n\n1. An empty string is valid.\n2. Any valid string enclosed in a pair of matching parentheses of the same type is also va...
def find_repeated_substrings(s): n = len(s) for L in range(n-1, 0, -1): substr_map = {} duplicates = set() for i in range(n - L + 1): substr = s[i:i+L] if substr in substr_map: duplicates.add(substr) else: substr_map[sub...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` consisting of lowercase English letters. You need to find the repeated substrings within `s` that appear more than once and have the **maximum** length. Your task is to return a list of these substrings in order of their first appearance in `s`. \n\n**Note:** ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9728, "level": 1, "question": "You are given a string `s` consisting of lowercase English letters. You need to find the repeated substrings within `s` that appear more than once and have the **maximum** length. Your task is to return a list of these substrings in order of their firs...
def find_nth_digit(n: int) -> int: l = 1 count = 9 start = 1 while n > l * count: n -= l * count l += 1 count *= 10 start *= 10 number = start + (n - 1) // l digit_index = (n - 1) % l return int(str(number)[digit_index])
simplelr_Data_Structure
[ { "content": "Question:\nYou are given an indexed series of natural numbers concatenated as a single sequence (e.g., \"123456789101112...\"). Your task is to implement a function that finds and returns the nth digit of this concatenated sequence.\n\n### Function Signature\n```python\ndef find_nth_digit(n: int) ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9729, "level": 1, "question": "You are given an indexed series of natural numbers concatenated as a single sequence (e.g., \"123456789101112...\"). Your task is to implement a function that finds and returns the nth digit of this concatenated sequence.\n\n### Function Signature\n```...
def findWords(words): row1 = {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'} row2 = {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'} row3 = {'z', 'x', 'c', 'v', 'b', 'n', 'm'} result = [] for word in words: lower_word = word.lower() in_row1 = all(c in row1 for c in lower_word) ...
simplelr_Leetcode
[ { "content": "Question:\nGiven a list of strings `words`, where each word is a combination of lowercase English letters, find and return all the words that can be typed using letters of only one row of an American QWERTY keyboard. Note that the keyboard rows consist of the following letters:\n- First row: \"qwe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9730, "level": 1, "question": "Given a list of strings `words`, where each word is a combination of lowercase English letters, find and return all the words that can be typed using letters of only one row of an American QWERTY keyboard. Note that the keyboard rows consist of the fol...
from typing import List def max_subsequence_sum(nums: List[int]) -> int: sum_positive = sum(x for x in nums if x > 0) return sum_positive if sum_positive > 0 else max(nums)
simplelr_Code_Contests
[ { "content": "Question:\nGiven a list of integers, write a function that returns the maximum possible sum of a non-empty subsequence. A subsequence can include some or all of the elements from the list and must maintain the order of the original list.\n\n\n### Function Signature\n```python\ndef max_subsequence_...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9731, "level": 1, "question": "Given a list of integers, write a function that returns the maximum possible sum of a non-empty subsequence. A subsequence can include some or all of the elements from the list and must maintain the order of the original list.\n\n\n### Function Signatu...
def sum_integers(lst): total = 0 for item in lst: if isinstance(item, int): total += item return total
simplelr_Filter
[ { "content": "Question:\nHow do I modify the code to handle a situation where the input list contains both integers and strings, and I want to sum only the integers while ignoring the strings?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9732, "level": 1, "question": "How do I modify the code to handle a situation where the input list contains both integers and strings, and I want to sum only the integers while ignoring the strings?", "split": "train" }
from collections import Counter def most_frequent(lst): if not lst: return [] counts = Counter(lst) max_count = max(counts.values()) return [k for k, v in counts.items() if v == max_count]
simplelr_Filter
[ { "content": "Question:\nWrite a function in Python to find the most frequent value(s) in a list. If there are multiple values with the same highest frequency, return all of them in a list. If the input list is empty, return an empty list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9733, "level": 1, "question": "Write a function in Python to find the most frequent value(s) in a list. If there are multiple values with the same highest frequency, return all of them in a list. If the input list is empty, return an empty list.", "split": "train" }
import bz2 def compress_and_verify(input_file: str, compressed_file: str, decompressed_file: str) -> bool: try: # Read the original data with open(input_file, 'rb') as f: input_data = f.read() # Compress to bzip2 file with bz2.open(compressed_file, 'wb', compresslevel=9...
simplelr_Docs
[ { "content": "Question:\n**Objective:**\nImplement a Python function that compresses a text file using the bzip2 compression algorithm and then decompresses it to verify the integrity of the original content. This exercise will assess your understanding of handling file I/O operations and working with the `bz2`...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9734, "level": 1, "question": "**Objective:**\nImplement a Python function that compresses a text file using the bzip2 compression algorithm and then decompresses it to verify the integrity of the original content. This exercise will assess your understanding of handling file I/O op...
def max_cookies(grid): if not grid or not grid[0]: return 0 m, n = len(grid), len(grid[0]) prev_row = [0] * n prev_row[0] = grid[0][0] for j in range(1, n): prev_row[j] = prev_row[j-1] + grid[0][j] for i in range(1, m): current_row = [0] * n current_row[0] = ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a `m x n` grid filled with non-negative numbers representing the number of cookies in each cell. Write a function to find a path from the top-left corner to the bottom-right corner that collects the maximum number of cookies. You can only move either down or right at any p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9735, "level": 1, "question": "You are given a `m x n` grid filled with non-negative numbers representing the number of cookies in each cell. Write a function to find a path from the top-left corner to the bottom-right corner that collects the maximum number of cookies. You can only...
def longest_alphabetical_sequence(s: str) -> str: max_seq = "" current_seq = "" for char in s: if char.isalpha(): current_seq += char else: if len(current_seq) > len(max_seq): max_seq = current_seq current_seq = "" # Check the last sequ...
simplelr_Taco
[ { "content": "Question:\nIn a given string, identify all sequences of consecutive alphabetical characters and return the longest sequence. In case of multiple sequences of the same length, return the one which appears first in the string.\n\nFor example, given the string `a2b3c2abc567defg!`, the longest sequenc...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9736, "level": 1, "question": "In a given string, identify all sequences of consecutive alphabetical characters and return the longest sequence. In case of multiple sequences of the same length, return the one which appears first in the string.\n\nFor example, given the string `a2b3...
def sum_of_multiples_of_divisors(num): if num == 1: return 0 return (num - 1) * num // 2
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a positive integer num and returns the sum of all the positive integers less than num that are multiples of its divisors.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9737, "level": 1, "question": "Create a function that takes a positive integer num and returns the sum of all the positive integers less than num that are multiples of its divisors.", "split": "train" }
def product_of_abs_pairs(list1: list[int], list2: list[int]) -> list[int]: """ Calculates the product of pairs of absolute values from two given lists of integers. Parameters: list1 (list[int]): The first input list of integers. list2 (list[int]): The second input list of integers. Ret...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement: Product of Absolute Value Pairs\n\nYou are required to implement a function `product_of_abs_pairs` that calculates the product of pairs of absolute values from two given lists of integers. The function should handle cases where the lists have different lengths by ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9738, "level": 1, "question": "### Problem Statement: Product of Absolute Value Pairs\n\nYou are required to implement a function `product_of_abs_pairs` that calculates the product of pairs of absolute values from two given lists of integers. The function should handle cases where t...
def remove_min_chars_to_unique(s): seen = set() res = [] for char in s: if char not in seen: res.append(char) seen.add(char) return ''.join(res)
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` consisting of lowercase alphabets, remove the minimum number of characters from it so that all the remaining characters in `s` are unique. Return the resulting string with all distinct characters in their original order. If there are multiple possible results, return ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9739, "level": 1, "question": "Given a string `s` consisting of lowercase alphabets, remove the minimum number of characters from it so that all the remaining characters in `s` are unique. Return the resulting string with all distinct characters in their original order. If there are...
from collections import deque def has_path(grid: list[list[int]]) -> bool: if not grid or not grid[0]: return False m = len(grid) n = len(grid[0]) # Check if the starting cell is blocked if grid[0][0] != 0: return False # Check if the ending cell is blocked (though pro...
simplelr_Algorithm
[ { "content": "Question:\n### Scenario\n\nYou are assisting in the development of a robotic system for an automated warehouse. The system uses a grid-based map where each cell can either be open or blocked. The robot can only move up, down, left, or right. You need to determine if there is a valid path from the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9740, "level": 1, "question": "### Scenario\n\nYou are assisting in the development of a robotic system for an automated warehouse. The system uses a grid-based map where each cell can either be open or blocked. The robot can only move up, down, left, or right. You need to determine...
def count_char_occurrences(s): char_count = {} for char in s: if char.isalpha(): lower_char = char.lower() if lower_char in char_count: char_count[lower_char] += 1 else: char_count[lower_char] = 1 return char_count
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to count the occurrences of each character in a string, ignoring case sensitivity and excluding non-alphabetic characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9741, "level": 1, "question": "Write a python function to count the occurrences of each character in a string, ignoring case sensitivity and excluding non-alphabetic characters.", "split": "train" }
def does_follow_pattern(pattern: str, s: str) -> bool: words = s.split() if len(words) != len(pattern): return False pmap = {} wmap = {} for p_char, word in zip(pattern, words): if p_char in pmap: if pmap[p_char] != word: return False els...
simplelr_Data_Structure
[ { "content": "Question:\n### Word Pattern Matching\n\n**Context:** \nYou are tasked with implementing a function that determines if a given string follows a specified pattern. This is a common scenario in text processing, template validation, and sequence verification tasks where pattern compliance is essential...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9742, "level": 1, "question": "### Word Pattern Matching\n\n**Context:** \nYou are tasked with implementing a function that determines if a given string follows a specified pattern. This is a common scenario in text processing, template validation, and sequence verification tasks wh...
def find_duplicates(nums): counts = {} for num in nums: counts[num] = counts.get(num, 0) + 1 duplicates = [num for num in counts if counts[num] >= 2] duplicates.sort() return duplicates
simplelr_Filter
[ { "content": "Question:\nYou are given an array of integers called `nums`. You need to write a function called `find_duplicates` that takes this array as input and returns a list containing all the duplicate elements in the array.\n\nExample:\n\n```\nnums = [1, 2, 3, 2, 4, 5, 1, 6]\nfind_duplicates(nums) == [1,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9743, "level": 1, "question": "You are given an array of integers called `nums`. You need to write a function called `find_duplicates` that takes this array as input and returns a list containing all the duplicate elements in the array.\n\nExample:\n\n```\nnums = [1, 2, 3, 2, 4, 5, ...
def find_min_revision(changes): balance = 0 for change in changes: if change['type'] == 'insert': balance += 1 else: balance -= 1 if balance == 0: return change['revision'] return None
simplelr_Filter
[ { "content": "Question:\nI have an array of JSON objects where each object has a property called \"type\" and a property called \"revision\". The array represents a list of changes to a document. When the type is \"insert\", it means a new piece of text was inserted into the document. When the type is \"delete\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9744, "level": 1, "question": "I have an array of JSON objects where each object has a property called \"type\" and a property called \"revision\". The array represents a list of changes to a document. When the type is \"insert\", it means a new piece of text was inserted into the d...
import string def count_unique_words(file_name): word_count = set() with open(file_name, 'r') as file: for line in file: words = line.split() for word in words: lower_word = word.lower() stripped_word = lower_word.strip(string.punctuation) ...
simplelr_Filter
[ { "content": "Question:\nI have a function which should output the number of unique words in a document. It takes a file name as input and returns the word count. \n\nHere is my function in Python:\n\n```python\ndef count_unique_words(file_name):\n word_count = {}\n with open(file_name, 'r') as file:\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9745, "level": 1, "question": "I have a function which should output the number of unique words in a document. It takes a file name as input and returns the word count. \n\nHere is my function in Python:\n\n```python\ndef count_unique_words(file_name):\n word_count = {}\n with...
def unique_paths(m, n): a = m + n - 2 b = min(m - 1, n - 1) result = 1 for i in range(1, b + 1): result = result * (a - b + i) // i return result
simplelr_Filter
[ { "content": "Question:\nCreate a Python function to calculate the total number of possible paths a robot can take in a grid from the top-left corner to the bottom-right corner, where the robot can only move right or down. The grid is represented as a 2D list with dimensions `m x n`.\nAnswer:\nLet's think step ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9746, "level": 1, "question": "Create a Python function to calculate the total number of possible paths a robot can take in a grid from the top-left corner to the bottom-right corner, where the robot can only move right or down. The grid is represented as a 2D list with dimensions `...
def compute_total_value(x, y): """ This function computes the total value of items given their valuations and quantities. Args: x (list): A list of valuations of different items in ascending order. y (list): A list of quantities of items corresponding to the valuations in x. Returns: ...
simplelr_Filter
[ { "content": "Question:\nHere is a problem:\n\nProblem: Consider a Python data structure consisting of two lists: `x` and `y`. The `x` list represents the valuations of different items, and the `y` list represents the quantities of items corresponding to the valuations in `x`. Suppose the `x` list contains the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9747, "level": 1, "question": "Here is a problem:\n\nProblem: Consider a Python data structure consisting of two lists: `x` and `y`. The `x` list represents the valuations of different items, and the `y` list represents the quantities of items corresponding to the valuations in `x`....
import math from typing import List def generate_primes(n: int) -> List[int]: # Input validation if type(n) is not int or n < 0: raise ValueError("Input must be a non-negative integer") if n < 2: return [] # Sieve of Eratosthenes algorithm sieve = [True] * (n + 1) siev...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are developing a system that needs to process large quantities of numerical data, and part of that processing involves identifying prime numbers efficiently. To aid in this, you have to implement a function that generates a list of all prime numbers up to a ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9748, "level": 1, "question": "### Problem Statement\n\nYou are developing a system that needs to process large quantities of numerical data, and part of that processing involves identifying prime numbers efficiently. To aid in this, you have to implement a function that generates a...
import string from collections import Counter def count_word_frequencies(input_filename, output_filename): with open(input_filename, 'r', encoding='utf-8') as file: text = file.read() # Split the text into words words = text.split() # Prepare the punctuation to be removed punctuat...
simplelr_Filter
[ { "content": "Question:\nCan you write a Python program that reads a text file, counts the frequency of each word, and writes the results to a new file, sorting the words by their frequency in descending order? The program should handle edge cases such as punctuation and case sensitivity.\nAnswer:\nLet's think ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9749, "level": 1, "question": "Can you write a Python program that reads a text file, counts the frequency of each word, and writes the results to a new file, sorting the words by their frequency in descending order? The program should handle edge cases such as punctuation and case ...
def run_length_encode(s: str) -> str: if not s: return "" result = [] current_char = s[0] count = 1 for char in s[1:]: if char == current_char: count += 1 else: result.append(f"{current_char}{count}") current_char = char count =...
simplelr_Taco
[ { "content": "Question:\nMark has recently developed an interest in string compression algorithms. He came across a simple run-length encoding technique and decided to implement it himself. However, Mark is stuck and needs your help to write a function that uses the run-length encoding to compress a given strin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9750, "level": 1, "question": "Mark has recently developed an interest in string compression algorithms. He came across a simple run-length encoding technique and decided to implement it himself. However, Mark is stuck and needs your help to write a function that uses the run-length...
def is_permutation_in_string(s1: str, s2: str) -> bool: len1 = len(s1) len2 = len(s2) if len1 > len2: return False from collections import Counter s1_counts = Counter(s1) window_counts = Counter(s2[:len1]) if window_counts == s1_counts: return True for i in range(1, le...
simplelr_Algorithm
[ { "content": "Question:\n### String Permutation Finder\n\n#### Context:\nYou need to determine if a smaller string is a permutation of a substring within a larger string. A permutation is a rearrangement of letters.\n\n#### Problem Statement:\nWrite a function `is_permutation_in_string` that receives two string...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9751, "level": 1, "question": "### String Permutation Finder\n\n#### Context:\nYou need to determine if a smaller string is a permutation of a substring within a larger string. A permutation is a rearrangement of letters.\n\n#### Problem Statement:\nWrite a function `is_permutation_...
def reverse_integer(n): is_negative = False if n < 0: is_negative = True n = abs(n) reversed_str = str(n)[::-1] reversed_int = int(reversed_str) if is_negative: reversed_int = -reversed_int return reversed_int
simplelr_Codeforces
[ { "content": "Question:\nYou have been tasked with developing a numerical manipulation algorithm for a specific application. The challenge is to reverse the digits in a given integer while maintaining the sign (positive or negative) of the original number.\n\nWrite a function `reverse_integer` that takes an int...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9752, "level": 1, "question": "You have been tasked with developing a numerical manipulation algorithm for a specific application. The challenge is to reverse the digits in a given integer while maintaining the sign (positive or negative) of the original number.\n\nWrite a function ...
def is_valid(s: str) -> bool: stack = [] mapping = { '(': ')', '{': '}', '[': ']' } for char in s: if char in mapping: stack.append(mapping[char]) else: if not stack: return False if stack.pop() != char: return False ret...
simplelr_Taco
[ { "content": "Question:\n## Task\nGiven a string, determine whether it consists of a valid sequence of nested expressions using parentheses, curly braces, and square brackets. A sequence of expressions is valid if:\n- Every opening parenthesis (`(`), curly brace (`{`), and square bracket (`[`), has a correspond...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9753, "level": 1, "question": "## Task\nGiven a string, determine whether it consists of a valid sequence of nested expressions using parentheses, curly braces, and square brackets. A sequence of expressions is valid if:\n- Every opening parenthesis (`(`), curly brace (`{`), and squ...
def unique_char_weight(s: str) -> int: unique_chars = set(s) total = 0 for c in unique_chars: total += (ord(c) - ord('a') + 1) return total
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement:\n\nWrite a function that calculates the total weight of all unique characters in a string. Each character has a weight defined by its position in the English alphabet (1-based index), i.e., 'a' has a weight of 1, 'b' has a weight of 2, ..., and 'z' has a weight of...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9754, "level": 1, "question": "### Problem Statement:\n\nWrite a function that calculates the total weight of all unique characters in a string. Each character has a weight defined by its position in the English alphabet (1-based index), i.e., 'a' has a weight of 1, 'b' has a weight...
def find_pattern_index(text: str, pattern: str) -> int: return text.find(pattern)
simplelr_Data_Structure
[ { "content": "Question:\nYou are given two strings, `text` and `pattern`. Write a function `find_pattern_index(text, pattern)` that returns the 0-based index of the first occurrence of `pattern` in `text`. If `pattern` is not part of `text`, return -1. The function signature should be:\n\n```python\ndef find_pa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9755, "level": 1, "question": "You are given two strings, `text` and `pattern`. Write a function `find_pattern_index(text, pattern)` that returns the 0-based index of the first occurrence of `pattern` in `text`. If `pattern` is not part of `text`, return -1. The function signature s...
def lengthOfLongestSubstring(s: str) -> int: last_seen = {} max_len = 0 left = 0 for right in range(len(s)): current_char = s[right] if current_char in last_seen and last_seen[current_char] >= left: left = last_seen[current_char] + 1 last_seen[current_char] = right ...
simplelr_Taco
[ { "content": "Question:\nGiven a string, find the length of the longest substring without repeating characters.\n\nFor example, for the string `s`\n\n \"abcabcbb\"\n \nThe longest substring without repeating characters is `\"abc\"`, which has a length of `3`.\n\nYour task is to implement the function\n\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9756, "level": 1, "question": "Given a string, find the length of the longest substring without repeating characters.\n\nFor example, for the string `s`\n\n \"abcabcbb\"\n \nThe longest substring without repeating characters is `\"abc\"`, which has a length of `3`.\n\nYour tas...
def analyze_employee_data(employee_data: dict) -> dict: sum_sal = 0 department_counts = {} name_salary = [] for emp in employee_data.values(): sum_sal += emp['salary'] dep = emp['department'] if dep in department_counts: department_counts[dep] += 1 else: ...
simplelr_Algorithm
[ { "content": "Question:\n### Handling and Analyzing Employee Data in a Company\n\nAs a developer, you are tasked with creating a function `analyze_employee_data` that processes a dictionary containing employee information and returns specific analysis. The dictionary represents each employee with their ID as ke...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9757, "level": 1, "question": "### Handling and Analyzing Employee Data in a Company\n\nAs a developer, you are tasked with creating a function `analyze_employee_data` that processes a dictionary containing employee information and returns specific analysis. The dictionary represent...
def filter_duplicate_urls(urls): seen = set() result = [] for url in urls: if url not in seen: seen.add(url) result.append(url) return result
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that filters out duplicate URLs from a list of URLs, ensuring that each URL appears only once in the resulting list?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9758, "level": 1, "question": "How can I create a Python function that filters out duplicate URLs from a list of URLs, ensuring that each URL appears only once in the resulting list?", "split": "train" }
def filter_non_empty_strings(lst): return [s for s in lst if isinstance(s, str) and s != ""]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to filter out non-empty strings from a list and return a new list with only non-empty strings.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9759, "level": 1, "question": "Write a python function to filter out non-empty strings from a list and return a new list with only non-empty strings.", "split": "train" }
def calculate_polygon_area(points): n = len(points) sum_area = 0 for i in range(n): j = (i + 1) % n xi, yi = points[i] xj, yj = points[j] sum_area += (xi * yj) - (xj * yi) return 0.5 * abs(sum_area)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function `calculate_polygon_area` that computes the area of a given polygon. The polygon is represented by a list of points, where each point is a tuple of two integers (x, y) corresponding to the coordinates of the vertices of the polygon in a 2D plane. The function shou...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9760, "level": 1, "question": "Write a Python function `calculate_polygon_area` that computes the area of a given polygon. The polygon is represented by a list of points, where each point is a tuple of two integers (x, y) corresponding to the coordinates of the vertices of the polyg...
from typing import List def find_majority_element(nums: List[int]) -> int: """ Finds the majority element in the array. Args: nums (List[int]): List of integers. Returns: int: The majority element or -1 if no majority element exists. """ if not nums: return -1 # B...
simplelr_Algorithm
[ { "content": "Question:\n### Problem: Majority Element in Array\n\nYou are tasked with implementing a function that finds the majority element in an array of integers. The majority element is the element that appears more than ⌊n / 2⌋ times, where `n` is the length of the array. This task requires understanding...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9761, "level": 1, "question": "### Problem: Majority Element in Array\n\nYou are tasked with implementing a function that finds the majority element in an array of integers. The majority element is the element that appears more than ⌊n / 2⌋ times, where `n` is the length of the arra...
def sum_of_digits(n, k): s = sum(int(c) for c in str(n)) return s * k
simplelr_Apps
[ { "content": "Question:\nWrite a function `sum_of_digits` that takes a positive integer `n` and an integer `k`, and returns the sum of the digits of `n` repeated `k` times.\n\nFor example,\n- When `n = 123` and `k = 3`, the number formed will be `123123123`, and the sum of the digits will be `1 + 2 + 3 + 1 + 2 ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9762, "level": 1, "question": "Write a function `sum_of_digits` that takes a positive integer `n` and an integer `k`, and returns the sum of the digits of `n` repeated `k` times.\n\nFor example,\n- When `n = 123` and `k = 3`, the number formed will be `123123123`, and the sum of the...
def sum_of_list(num_list): return sum(num_list)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the sum of all the numbers in a given list. If the list is empty, return 0. Ensure the function is efficient and handles negative numbers as well.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9763, "level": 1, "question": "Write a function to calculate the sum of all the numbers in a given list. If the list is empty, return 0. Ensure the function is efficient and handles negative numbers as well.", "split": "train" }
from collections import deque def find_task_order(tasks: int, dependencies: list) -> list: """ Determines a possible order of task execution given their dependencies using topological sort. Parameters: tasks (int): The total number of tasks, labeled from 0 to tasks-1. dependencies (list): A li...
simplelr_Algorithm
[ { "content": "Question:\n### Question\n\n#### Problem Statement\nYou have been tasked with developing a tool to manage and schedule tasks using a blocking dependency resolution system. Your goal is to determine if a set of tasks can be completed given their dependencies, and if so, produce one possible order of...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9764, "level": 1, "question": "### Question\n\n#### Problem Statement\nYou have been tasked with developing a tool to manage and schedule tasks using a blocking dependency resolution system. Your goal is to determine if a set of tasks can be completed given their dependencies, and i...
import numpy as np def simulate_population_growth(P0: float, r: float, K: float, t_steps: int) -> np.ndarray: population = np.zeros(t_steps + 1) population[0] = P0 for i in range(1, t_steps + 1): population[i] = population[i-1] + r * population[i-1] * (1 - population[i-1] / K) return population
simplelr_Package
[ { "content": "Question:\nCreate a function called `simulate_population_growth` that models the growth of a population over time according to the logistic growth equation. The function should return a 1D NumPy array representing the population size at each time step, starting from the initial population up to th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9765, "level": 1, "question": "Create a function called `simulate_population_growth` that models the growth of a population over time according to the logistic growth equation. The function should return a 1D NumPy array representing the population size at each time step, starting f...
def remove_duplicates(nums): if not nums: return 0 i = 0 for j in range(1, len(nums)): if nums[j] != nums[i]: i += 1 nums[i] = nums[j] return i + 1
simplelr_Filter
[ { "content": "Question:\nGiven a sorted array of integers, write a function to remove the duplicates in place such that each element appears only once and return the new length. The order of the elements should be kept the same. You must solve this problem without allocating extra space for another array.\nAnsw...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9766, "level": 1, "question": "Given a sorted array of integers, write a function to remove the duplicates in place such that each element appears only once and return the new length. The order of the elements should be kept the same. You must solve this problem without allocating e...
def find_duplicate_numbers(nums): counts = {} for num in nums: if num in counts: counts[num] += 1 else: counts[num] = 1 return [num for num, count in counts.items() if count > 1]
simplelr_Filter
[ { "content": "Question:\nYou are given a list of integers `nums`. Write a Python function `find_duplicate_numbers(nums)` that finds all duplicate numbers in the list.\n\nExample:\n\n```python\nnums = [1, 2, 3, 4, 2, 5, 6, 1, 7]\nfind_duplicate_numbers(nums)\n# Output: [1, 2]\n```\n\nRequirements:\n\n The functi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9767, "level": 1, "question": "You are given a list of integers `nums`. Write a Python function `find_duplicate_numbers(nums)` that finds all duplicate numbers in the list.\n\nExample:\n\n```python\nnums = [1, 2, 3, 4, 2, 5, 6, 1, 7]\nfind_duplicate_numbers(nums)\n# Output: [1, 2]\n...
def convert_temperature(s): parts = s.split() temp = float(parts[0]) unit = parts[1] if unit == 'C': converted = temp * 9/5 + 32 new_unit = 'F' else: converted = (temp - 32) * 5/9 new_unit = 'C' rounded = round(converted) return f"{rounded} {new_unit...
simplelr_Apps
[ { "content": "Question:\n##Overview\n\nCreate a function that converts temperatures from Celsius to Fahrenheit and from Fahrenheit to Celsius, based on the input format. The function should take a string representing the temperature, followed by a space and the letter 'C' for Celsius or 'F' for Fahrenheit, and ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9768, "level": 1, "question": "##Overview\n\nCreate a function that converts temperatures from Celsius to Fahrenheit and from Fahrenheit to Celsius, based on the input format. The function should take a string representing the temperature, followed by a space and the letter 'C' for ...
import heapq def find_directed_knn(n, edges, k, source): # Build the adjacency list graph = [[] for _ in range(n)] for u, v in edges: graph[u].append(v) # Initialize distances and visited array distances = [float('inf')] * n visited = [False] * n distances[source] = 0 # Distan...
simplelr_Filter
[ { "content": "Question:\nimport heapq\n\ndef find_directed_knn(n, edges, k):\n graph = [[] for _ in range(n)]\n for edge in edges:\n graph[edge[0]].append(edge[1])\n visited = [False] * n\n heap = []\n for i in range(n):\n if not visited[i]:\n heapq.heappush(heap, (-1, i)...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9769, "level": 1, "question": "import heapq\n\ndef find_directed_knn(n, edges, k):\n graph = [[] for _ in range(n)]\n for edge in edges:\n graph[edge[0]].append(edge[1])\n visited = [False] * n\n heap = []\n for i in range(n):\n if not visited[i]:\n ...
def wave_sort(arr: list) -> list: # Step 1: Sort the input list arr_sorted = sorted(arr) # Step 2: Swap adjacent elements in pairs for i in range(0, len(arr_sorted) - 1, 2): arr_sorted[i], arr_sorted[i + 1] = arr_sorted[i + 1], arr_sorted[i] return arr_sorted
simplelr_Package
[ { "content": "Question:\nYou are required to create a function that takes a list of integers and returns the list sorted in 'wave' form. In a wave array, elements are arranged such that every second element is greater than its adjacent elements. The resulting array should ensure that for even-indexed \\( i \\) ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9770, "level": 1, "question": "You are required to create a function that takes a list of integers and returns the list sorted in 'wave' form. In a wave array, elements are arranged such that every second element is greater than its adjacent elements. The resulting array should ensu...
def censor_words(text, censor_list): tokens = [] current_word = [] for char in text: if char.isalpha(): current_word.append(char) else: if current_word: tokens.append(''.join(current_word)) current_word = [] tokens.append(ch...
simplelr_Package
[ { "content": "Question:\nYou are tasked with implementing a basic text processing function in Python. Given a paragraph of text and a list of words to censor, your goal is to create a function named `censor_words` that:\n\n1. Takes as input a string `text` representing a paragraph of text.\n2. Takes as input a ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9771, "level": 1, "question": "You are tasked with implementing a basic text processing function in Python. Given a paragraph of text and a list of words to censor, your goal is to create a function named `censor_words` that:\n\n1. Takes as input a string `text` representing a parag...
import string def word_frequency(s): s = s.lower() words = s.split() frequency = {} for word in words: stripped_word = word.strip(string.punctuation) if stripped_word: frequency[stripped_word] = frequency.get(stripped_word, 0) + 1 return frequency
simplelr_Prefill
[ { "content": "Question:\nWrite a function to identify and return the frequency of each word in a given string. The function should ignore case sensitivity and consider words to be separated by spaces.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9772, "level": 1, "question": "Write a function to identify and return the frequency of each word in a given string. The function should ignore case sensitivity and consider words to be separated by spaces.", "split": "train" }
from collections import Counter def sum_unique_elements(nums): counts = Counter(nums) total = 0 for num, count in counts.items(): if count == 1: total += num return total
simplelr_Taco
[ { "content": "Question:\nGiven a list of integers, return the sum of all unique elements in the list. A unique element is one that appears exactly once in the list.\n\nExample:\n\nInput: [1, 2, 3, 2, 4, 3]\nOutput: 5\nExplanation: The elements 1 and 4 are unique, and their sum is 5.\n\nInput: [4, 4, 4, 4]\nOutp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9773, "level": 1, "question": "Given a list of integers, return the sum of all unique elements in the list. A unique element is one that appears exactly once in the list.\n\nExample:\n\nInput: [1, 2, 3, 2, 4, 3]\nOutput: 5\nExplanation: The elements 1 and 4 are unique, and their sum...
def fib(n): if n == 0: return 0 elif n == 1: return 1 else: a, b = 0, 1 for i in range(2, n + 1): c = a + b a = b b = c return b
simplelr_Taco
[ { "content": "Question:\nGiven an integer n, return the nth term of the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1 (i.e., Fib(0) = 0, Fib(1) = 1).\n\nExample 1:\nInput: n = 4\nOutput: 3\nExplanation: The Fibonac...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9774, "level": 1, "question": "Given an integer n, return the nth term of the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1 (i.e., Fib(0) = 0, Fib(1) = 1).\n\nExample 1:\nInput: n = 4\n...
def optimized_dijkstra(vertex_count: int, edges: list[tuple[int, int, int]], src: int) -> list[int]: import heapq # Build the adjacency list adj = [[] for _ in range(vertex_count)] for u, v, w in edges: adj[u].append((v, w)) # Initialize distances INF = float('inf') dist = [INF...
simplelr_Data_Structure
[ { "content": "Question:\n### Problem: Extended Dijkstra's Algorithm\n\n#### Context:\nYou have been hired by a logistics company to enhance their navigation system. Currently, they use Dijkstra's algorithm to find the shortest paths in their road network graph, but they face performance issues due to the large ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9775, "level": 1, "question": "### Problem: Extended Dijkstra's Algorithm\n\n#### Context:\nYou have been hired by a logistics company to enhance their navigation system. Currently, they use Dijkstra's algorithm to find the shortest paths in their road network graph, but they face p...
from collections import Counter def has_equal_char_frequency(s: str) -> bool: """ Determine whether all characters in the string have the same frequency. :param s: str :return: Boolean """ freq = Counter(s) return len(set(freq.values())) == 1 if __name__ == "__main__": print(has_equal_...
simplelr_Algorithm
[ { "content": "Question:\nCheck if All Characters Have Equal Frequency\n\nYou are tasked with implementing a function to verify if all characters in a given string appear with the same frequency. The function should determine whether each character in the string appears the same number of times, and return `True...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9776, "level": 1, "question": "Check if All Characters Have Equal Frequency\n\nYou are tasked with implementing a function to verify if all characters in a given string appear with the same frequency. The function should determine whether each character in the string appears the sam...
from collections import Counter from typing import List def sum_of_unique_elements(arr: List[int]) -> int: counts = Counter(arr) total = 0 for num, count in counts.items(): if count == 1: total += num return total
simplelr_Evol
[ { "content": "Question:\nGiven an array of integers, write a function that returns the sum of the unique elements only. For this question, consider \"unique elements\" to mean numbers that appear exactly once in the array. Your function should have the following signature: `def sum_of_unique_elements(arr: List[...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9777, "level": 1, "question": "Given an array of integers, write a function that returns the sum of the unique elements only. For this question, consider \"unique elements\" to mean numbers that appear exactly once in the array. Your function should have the following signature: `de...
def sum_excluding_divisible_by_3(lst): total = 0 for num in lst: if num % 3 != 0: total += num return total
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in a list of integers and returns the sum of its elements, excluding any numbers that are divisible by 3.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9778, "level": 1, "question": "Create a function that takes in a list of integers and returns the sum of its elements, excluding any numbers that are divisible by 3.", "split": "train" }
def modular_exponentiation(base: int, exponent: int, mod: int) -> int: if mod == 1: return 0 result = 1 base = base % mod while exponent > 0: if exponent % 2 == 1: result = (result * base) % mod exponent = exponent >> 1 base = (base * base) % mod return re...
simplelr_Data_Structure
[ { "content": "Question:\n### Context\nYou are developing a software component for secure communication, which involves repeated use of exponentiation with large numbers. Being aware of the constraints, you are required to implement an efficient algorithm for this purpose.\n\n### Task\nImplement a function `modu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9779, "level": 1, "question": "### Context\nYou are developing a software component for secure communication, which involves repeated use of exponentiation with large numbers. Being aware of the constraints, you are required to implement an efficient algorithm for this purpose.\n\n#...
def city_block_distance(buildings: [(int, int)]) -> (int, int): sums = [] for i in range(len(buildings)): x1, y1 = buildings[i] sum_dist = 0 for j in range(len(buildings)): if i == j: continue x2, y2 = buildings[j] sum_dist += abs(x2 - ...
simplelr_Evol
[ { "content": "Question:\nWrite a function `city_block_distance` that calculates the Manhattan distance between two points in a grid. The Manhattan distance between two points \\((x_1, y_1)\\) and \\((x_2, y_2)\\) is defined as \\(|x_2 - x_1| + |y_2 - y_1|. Given a list of points representing buildings in a city...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9780, "level": 1, "question": "Write a function `city_block_distance` that calculates the Manhattan distance between two points in a grid. The Manhattan distance between two points \\((x_1, y_1)\\) and \\((x_2, y_2)\\) is defined as \\(|x_2 - x_1| + |y_2 - y_1|. Given a list of poin...
from typing import List, Dict, Any, Union from collections import defaultdict def filter_and_aggregate_students(students: List[Dict[str, Union[str, int]]]) -> Dict[str, Any]: department_scores = defaultdict(list) # Filter students with score > 70 and group by department for student in students: ...
simplelr_Docs
[ { "content": "Question:\n#### Objective\n\nImplement a function that extracts specific information from a given list of dictionaries representing a dataset, demonstrating comprehensive knowledge of built-in types, their operations, and string manipulations.\n\n#### Problem Statement\n\nWrite a function `filter_...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9781, "level": 1, "question": "#### Objective\n\nImplement a function that extracts specific information from a given list of dictionaries representing a dataset, demonstrating comprehensive knowledge of built-in types, their operations, and string manipulations.\n\n#### Problem Sta...
from typing import List def calculate_visibility(heights: List[int]) -> List[int]: n = len(heights) stack = [] previous_greater = [-1] * n for i in range(n): while stack and heights[stack[-1]] <= heights[i]: stack.pop() if stack: previous_greater[i] = stack[-1] ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou have been given an array representing the heights of buildings in a city skyline, where each height is a positive integer. Each building is viewed from the left side, and your task is to calculate the \"visibility score\" for each building. The visibility scor...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9782, "level": 1, "question": "### Problem Statement\nYou have been given an array representing the heights of buildings in a city skyline, where each height is a positive integer. Each building is viewed from the left side, and your task is to calculate the \"visibility score\" for...
from typing import List def increment_array(digits: List[int]) -> List[int]: carry = 1 i = len(digits) - 1 new_digits = [] while i >= 0 and carry > 0: sum_digit = digits[i] + carry carry = sum_digit // 10 new_digit = sum_digit % 10 new_digits.append(new_digit) ...
simplelr_Data_Structure
[ { "content": "Question:\n#### Problem Statement\n\nYou are given a non-negative integer presented as an array of digits. Each element in the array represents a single digit in a big-endian order (most significant digit first). Write a function that takes this array of digits and returns a new array that represe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9783, "level": 1, "question": "#### Problem Statement\n\nYou are given a non-negative integer presented as an array of digits. Each element in the array represents a single digit in a big-endian order (most significant digit first). Write a function that takes this array of digits a...
def spiral_order(matrix): if not matrix: return [] result = [] top = 0 bottom = len(matrix) - 1 left = 0 right = len(matrix[0]) - 1 while top <= bottom and left <= right: # Traverse from left to right on the top row for i in range(left, right + 1): ...
simplelr_Evol
[ { "content": "Question:\nDesign a function that takes a 2D matrix (list of lists) and returns its \"spiral order\". The matrix consists of M rows and N columns. Spiral order starts at the top-left corner of the matrix and proceeds towards the right, then moves down the right-most column, then moves left across ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9784, "level": 1, "question": "Design a function that takes a 2D matrix (list of lists) and returns its \"spiral order\". The matrix consists of M rows and N columns. Spiral order starts at the top-left corner of the matrix and proceeds towards the right, then moves down the right-m...
def reverse_string(s): return s[::-1]
simplelr_Filter
[ { "content": "Question:\nIn Python, define a function called \"reverse_string\" that takes a string as input and returns the reversed string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9785, "level": 1, "question": "In Python, define a function called \"reverse_string\" that takes a string as input and returns the reversed string.", "split": "train" }
def multiply_by_two(numbers): return [x * 2 for x in numbers]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of numbers as input and returns a new list with each element multiplied by two. Use **list comprehension** to achieve this.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9786, "level": 1, "question": "Create a function that takes a list of numbers as input and returns a new list with each element multiplied by two. Use **list comprehension** to achieve this.", "split": "train" }
def print_right_aligned_pyramid(height): for i in range(1, height + 1): spaces = ' ' * (height - i) stars = '*' * i print(spaces + stars) # Example usage: print_right_aligned_pyramid(5)
simplelr_Filter
[ { "content": "Question:\nIn Python, how can I create a function that prints a right-aligned pyramid with a given height, using asterisks (*) and spaces? The pyramid should have its base at the bottom and its top at the number of spaces equal to the height minus one. How can I approach this problem?\nAnswer:\nLe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9787, "level": 1, "question": "In Python, how can I create a function that prints a right-aligned pyramid with a given height, using asterisks (*) and spaces? The pyramid should have its base at the bottom and its top at the number of spaces equal to the height minus one. How can I ...
from typing import Sequence, List, Tuple def run_length_encode(data: Sequence[int]) -> List[Tuple[int, int]]: if not data: return [] result = [] current_value = data[0] count = 1 for num in data[1:]: if num == current_value: count += 1 else: result.ap...
simplelr_Algorithm
[ { "content": "Question:\n### Efficient Data Compression Function\n\n**Context:**\n\nYou are working on a system that needs to compress data efficiently before transmitting it over a network. One simple method of compression is run-length encoding (RLE), which compresses sequences of the same value in a list by ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9788, "level": 1, "question": "### Efficient Data Compression Function\n\n**Context:**\n\nYou are working on a system that needs to compress data efficiently before transmitting it over a network. One simple method of compression is run-length encoding (RLE), which compresses sequen...
from typing import List def optimized_cocktail_shaker_sort(arr: List[int]) -> List[int]: n = len(arr) if n <= 1: return arr up = n - 1 down = 0 while down < up: swapped = False last_swap = -1 # Left to Right pass for i in range(down, up): if arr[...
simplelr_Data_Structure
[ { "content": "Question:\n### Cocktail Shaker Sort Implementation and Improvement\nYou are tasked with writing a function to sort a given list of integers using the Cocktail Shaker Sort algorithm. Additionally, you should modify the algorithm to keep track of the last swap position to potentially reduce the numb...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9789, "level": 1, "question": "### Cocktail Shaker Sort Implementation and Improvement\nYou are tasked with writing a function to sort a given list of integers using the Cocktail Shaker Sort algorithm. Additionally, you should modify the algorithm to keep track of the last swap posi...
def longest_ap_length(nums): if not nums: return 0 n = len(nums) if n == 1: return 1 max_length = 2 current_length = 2 for i in range(2, n): current_diff = nums[i] - nums[i-1] prev_diff = nums[i-1] - nums[i-2] if current_diff == prev_diff: curr...
simplelr_Evol
[ { "content": "Question:\nDevelop a Python function that takes a list of integers and returns the length of the longest contiguous subsequence where the numbers form an arithmetic progression (AP). An arithmetic progression is defined as a sequence of numbers with a constant difference between consecutive terms....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9790, "level": 1, "question": "Develop a Python function that takes a list of integers and returns the length of the longest contiguous subsequence where the numbers form an arithmetic progression (AP). An arithmetic progression is defined as a sequence of numbers with a constant di...
def calculateDaysToWarmerTemperature(temperatures): n = len(temperatures) res = [0] * n stack = [] for i in range(n): while stack and temperatures[i] > temperatures[stack[-1]]: idx = stack.pop() res[idx] = i - idx stack.append(i) return res
simplelr_Leetcode
[ { "content": "Question:\nGiven a list of integers representing the daily temperature in Celsius, you need to calculate how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, return `0` for that day.\n\nFor example, given the list `temperatures = [7...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9791, "level": 1, "question": "Given a list of integers representing the daily temperature in Celsius, you need to calculate how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, return `0` for that day.\n\nFor example...
def longest_subarray(nums, target): # Initialize variables window_start = 0 current_sum = 0 max_length = 0 max_subarray = [] # Iterate over the list of numbers with window_end for window_end in range(len(nums)): # Add the current number to the window sum current_sum += n...
simplelr_Filter
[ { "content": "Question:\nWe are given a list of integers `nums` and a target integer `target`. Our goal is to find the longest contiguous subarray of `nums` that sums up to `target`.\n\nHere's an example to illustrate the concept:\n```\nInput: nums = [1, 2, 3, 4, 5], target = 5\nOutput: [2, 3]\n```\nIn this exa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9792, "level": 1, "question": "We are given a list of integers `nums` and a target integer `target`. Our goal is to find the longest contiguous subarray of `nums` that sums up to `target`.\n\nHere's an example to illustrate the concept:\n```\nInput: nums = [1, 2, 3, 4, 5], target = ...
def validate_robot_movements(moves: str) -> bool: x = 0 y = 0 for move in moves: if move == 'R': x += 1 elif move == 'L': x -= 1 elif move == 'U': y += 1 elif move == 'D': y -= 1 return x == 0 and y == 0
simplelr_Data_Structure
[ { "content": "Question:\n### Question: Validate Robot Movements to Return to Origin\n\nYou are given a sequence of moves for a robot starting at position (0, 0) on a 2D plane. The moves are represented as a string of characters, where:\n* 'R' means the robot moves one unit right,\n* 'L' means the robot moves on...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9793, "level": 1, "question": "### Question: Validate Robot Movements to Return to Origin\n\nYou are given a sequence of moves for a robot starting at position (0, 0) on a 2D plane. The moves are represented as a string of characters, where:\n* 'R' means the robot moves one unit rig...
def is_permutation(str1: str, str2: str) -> bool: if len(str1) != len(str2): return False freq1 = {} for c in str1: if c in freq1: freq1[c] += 1 else: freq1[c] = 1 freq2 = {} for c in str2: if c in freq2: freq2[c] += 1 ...
simplelr_Evol
[ { "content": "Question:\nWrite a function in Python that takes two strings as input and returns `True` if one of the strings is a permutation of the other. Otherwise, return `False`. A permutation is a rearrangement of letters. The comparison should be case-sensitive and spaces should be counted as characters.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9794, "level": 1, "question": "Write a function in Python that takes two strings as input and returns `True` if one of the strings is a permutation of the other. Otherwise, return `False`. A permutation is a rearrangement of letters. The comparison should be case-sensitive and space...
def next_bigger(num: int) -> int: digits = list(map(int, str(num))) n = len(digits) # Step 1: Find the pivot pivot = -1 for i in range(n - 2, -1, -1): if digits[i] < digits[i + 1]: pivot = i break if pivot == -1: return -1 # No such permutation exist...
simplelr_Data_Structure
[ { "content": "Question:\n### Problem Description\n\nYou are tasked with creating a function that determines the next higher number formed from the same set of digits as the given number. Your function should be designed to handle non-negative integers efficiently and correctly identify when no such permutation ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9795, "level": 1, "question": "### Problem Description\n\nYou are tasked with creating a function that determines the next higher number formed from the same set of digits as the given number. Your function should be designed to handle non-negative integers efficiently and correctly...
def removeVowels(s): vowels = {'a', 'e', 'i', 'o', 'u'} result = [] for char in s: if char.lower() not in vowels: result.append(char) return ''.join(result)
simplelr_Apps
[ { "content": "Question:\nWrite a function, removeVowels, that takes a string as input and returns a new string with all the vowels removed. In this context, vowels are 'a', 'e', 'i', 'o', 'u' (both uppercase and lowercase). \n\nFor example:\nInput: \"Hello World\"\nOutput: \"Hll Wrld\"\n\nAssume that the input ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9796, "level": 1, "question": "Write a function, removeVowels, that takes a string as input and returns a new string with all the vowels removed. In this context, vowels are 'a', 'e', 'i', 'o', 'u' (both uppercase and lowercase). \n\nFor example:\nInput: \"Hello World\"\nOutput: \"H...
def group_consecutive(nums: list) -> list: if not nums: return [] result = [] current_group = [nums[0]] for num in nums[1:]: if num == current_group[-1] + 1: current_group.append(num) else: result.append(current_group) current_group = [num] ...
simplelr_Package
[ { "content": "Question:\nYou need to write a Python function named `group_consecutive` that takes an input list of integers and groups the consecutive numbers together as sublists within a list. Consecutive numbers are those numbers which follow each other directly, without any gaps, in ascending order. If the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9797, "level": 1, "question": "You need to write a Python function named `group_consecutive` that takes an input list of integers and groups the consecutive numbers together as sublists within a list. Consecutive numbers are those numbers which follow each other directly, without an...
def create_zero_matrix(m, n): return [[0 for _ in range(n)] for _ in range(m)]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to create a 2D list (matrix) of size m x n filled with zeros.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9798, "level": 1, "question": "Write a python function to create a 2D list (matrix) of size m x n filled with zeros.", "split": "train" }
from typing import List def product_of_unique_numbers(nums: List[int]) -> int: if not nums: return 1 unique_nums = set(nums) product = 1 for num in unique_nums: product *= num return product
simplelr_Code_Contests
[ { "content": "Question:\nWrite a Python function that takes a list of integers and returns the product of all the unique numbers in it. If the list is empty, return 1.\n\n#### Function Signature\n\n```python\ndef product_of_unique_numbers(nums: List[int]) -> int:\n pass\n```\n\n#### Input\n\n- `nums` (List[i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9799, "level": 1, "question": "Write a Python function that takes a list of integers and returns the product of all the unique numbers in it. If the list is empty, return 1.\n\n#### Function Signature\n\n```python\ndef product_of_unique_numbers(nums: List[int]) -> int:\n pass\n``...