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 smallest_k_elements(lst, k): if not lst or k <= 0: return [] n = len(lst) if k >= n: return sorted(lst) return sorted(lst)[:k]
simplelr_Filter
[ { "content": "Question:\nYou have been tasked with writing a function `smallest_k_elements` that takes a list of integers and an integer k as input, and returns the k smallest elements from the list in ascending order.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4100, "level": 1, "question": "You have been tasked with writing a function `smallest_k_elements` that takes a list of integers and an integer k as input, and returns the k smallest elements from the list in ascending order.", "split": "train" }
def can_form_palindrome(s): char_count = {} for char in s: if char in char_count: char_count[char] += 1 else: char_count[char] = 1 odd_count = 0 for count in char_count.values(): if count % 2 != 0: odd_count += 1 n = len(s) if n % 2 =...
simplelr_Evol
[ { "content": "Question:\nWrite a function that checks if a given string can be rearranged to form a palindrome. A palindrome is a string that reads the same forward and backward. If the string can be rearranged to form at least one palindrome, return `True`; otherwise, return `False`.\n\nTo illustrate, the word...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4101, "level": 1, "question": "Write a function that checks if a given string can be rearranged to form a palindrome. A palindrome is a string that reads the same forward and backward. If the string can be rearranged to form at least one palindrome, return `True`; otherwise, return ...
def max_subarray_sum(nums): if not nums: return 0 # Return 0 for an empty list as per problem constraints current_sum = max_sum = nums[0] for num in nums[1:]: current_sum = max(current_sum + num, num) if current_sum > max_sum: max_sum = current_sum return max_sum
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers and returns the maximum sum of any contiguous subarray. This is known as Kadane's algorithm. For example, given [1, -3, 2, 1, -1], the contiguous subarray with the largest sum is [2, 1] with a sum of 3.\nAnswer:\nLet's think step by step.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4102, "level": 1, "question": "Create a function that takes a list of integers and returns the maximum sum of any contiguous subarray. This is known as Kadane's algorithm. For example, given [1, -3, 2, 1, -1], the contiguous subarray with the largest sum is [2, 1] with a sum of 3.",...
def rob_houses(houses: list) -> int: if not houses: return 0 n = len(houses) if n == 1: return houses[0] if n == 2: return max(houses[0], houses[1]) prev_prev = houses[0] prev = max(houses[0], houses[1]) for i in range(2, n): current = max(prev, prev...
simplelr_Taco
[ { "content": "Question:\nYou are given a list of houses lined up in a row, each with a certain amount of money stashed. A robber cannot rob two adjacent houses, as it would alert the police. Your task is to design a function that determines the maximum amount of money the robber can steal without alerting the p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4103, "level": 1, "question": "You are given a list of houses lined up in a row, each with a certain amount of money stashed. A robber cannot rob two adjacent houses, as it would alert the police. Your task is to design a function that determines the maximum amount of money the robb...
def add_strings(s1, s2): num1 = int(s1) num2 = int(s2) return str(num1 + num2)
simplelr_Filter
[ { "content": "Question:\nThis problem is from an upcoming programming competition. I'm trying to familiarize myself with the type of problems I might encounter.\n\n**Problem:**\n\nYou are given two strings, `s1` and `s2`, containing only digits. Your task is to add them as integers and return the result as a st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4104, "level": 1, "question": "This problem is from an upcoming programming competition. I'm trying to familiarize myself with the type of problems I might encounter.\n\n**Problem:**\n\nYou are given two strings, `s1` and `s2`, containing only digits. Your task is to add them as int...
def remove_consecutive_duplicates(s): prev_dp = { '': (0, "") } # key: last_char, value: (deletions, string) for c in s: current_dp = {} for prev_char in prev_dp: prev_del, prev_str = prev_dp[prev_char] # Option 1: exclude current character ...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` consisting of lowercase English letters, you need to remove the minimum number of characters to make any two consecutive characters in the string different. Return the resulting string after these removals. For example, for `s = \"aabcc\"`, removing one 'a' and one 'c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4105, "level": 1, "question": "Given a string `s` consisting of lowercase English letters, you need to remove the minimum number of characters to make any two consecutive characters in the string different. Return the resulting string after these removals. For example, for `s = \"aa...
def rotate_list(lst: list, n: int) -> list: if not lst: return [] n = n % len(lst) return lst[-n:] + lst[:-n]
simplelr_Package
[ { "content": "Question:\nYou are asked to write a function that shifts the elements of a given list of integers to the right by `n` positions. The function should be named `rotate_list`.\n\nBelow are the detailed requirements for the function:\n\n1. **Function Name:** `rotate_list`\n2. **Input:** A list of inte...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4106, "level": 1, "question": "You are asked to write a function that shifts the elements of a given list of integers to the right by `n` positions. The function should be named `rotate_list`.\n\nBelow are the detailed requirements for the function:\n\n1. **Function Name:** `rotate_...
def find_missing_positive(arr): m = len(arr) for i in range(m): x = arr[i] while 1 <= x <= m: if arr[x-1] == x: break # Swap the elements arr[i], arr[x-1] = arr[x-1], arr[i] x = arr[i] # Update x after the swap # Find the small...
simplelr_Evol
[ { "content": "Question:\nWrite a function to find the smallest positive integer that is missing from an unsorted array of integers. The function should handle both positive and negative integers as well as duplicates.\n\n**Example:**\nInput: [3, 4, -1, 1]\nOutput: 2\n\nInput: [1, 2, 0]\nOutput: 3\n\n**Requireme...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4107, "level": 1, "question": "Write a function to find the smallest positive integer that is missing from an unsorted array of integers. The function should handle both positive and negative integers as well as duplicates.\n\n**Example:**\nInput: [3, 4, -1, 1]\nOutput: 2\n\nInput: ...
from typing import List def can_satisfy_demands(demands: List[int], inventory: int) -> bool: """ Determines if all customer demands can be satisfied with the given inventory. Parameters: demands (List[int]): List of integers representing customer demands. inventory (int): The total inventory a...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are given a list of integers which represent the number of items required by customers in a store. Additionally, you are given an integer that represents the total inventory available. Your task is to determine whether it is possible to satisfy all customers' ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4108, "level": 1, "question": "### Problem Statement\nYou are given a list of integers which represent the number of items required by customers in a store. Additionally, you are given an integer that represents the total inventory available. Your task is to determine whether it is ...
def split_into_batches(numbers, batch_size): batches = [] for i in range(0, len(numbers), batch_size): batch = numbers[i:i+batch_size] batches.append(batch) return batches
simplelr_Filter
[ { "content": "Question:\nIn this problem, we'll implement a function `split_into_batches` to split a list of integers into batches of a specified size. The function should take two parameters: a list of integers and a batch size. It should return a list of lists, where each sublist is a batch of integers.\nAnsw...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4109, "level": 1, "question": "In this problem, we'll implement a function `split_into_batches` to split a list of integers into batches of a specified size. The function should take two parameters: a list of integers and a batch size. It should return a list of lists, where each su...
from typing import List def generate_twisted_pascals_triangle(n: int, start_value: int) -> List[List[int]]: if n <= 0: return [] triangle = [[start_value]] for _ in range(1, n): previous_row = triangle[-1] new_row = [start_value] for j in range(len(previous_row) - 1): ...
simplelr_Package
[ { "content": "Question:\n### Problem: Generate Pascal's Triangle with a Twist\n\nYou are required to generate Pascal's Triangle with a modification such that the triangle is integer-valued but the starting element can be any integer.\n\n### Context:\n- Pascal's Triangle is a triangular array of the binomial coe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4110, "level": 1, "question": "### Problem: Generate Pascal's Triangle with a Twist\n\nYou are required to generate Pascal's Triangle with a modification such that the triangle is integer-valued but the starting element can be any integer.\n\n### Context:\n- Pascal's Triangle is a t...
import math def unique_paths(m: int, n: int) -> int: a = m + n - 2 b = min(m - 1, n - 1) return math.comb(a, b)
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nImplement a function `unique_paths(m: int, n: int) -> int` that determines the number of unique paths from the top-left corner to the bottom-right corner of an `m x n` grid. You can only move either down or right at any point in time.\n\n### Context\n\nThis prob...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4111, "level": 1, "question": "### Problem Statement\n\nImplement a function `unique_paths(m: int, n: int) -> int` that determines the number of unique paths from the top-left corner to the bottom-right corner of an `m x n` grid. You can only move either down or right at any point i...
def countConsecutiveChar(s, c): max_count = 0 current = 0 for char in s: if char == c: current += 1 if current > max_count: max_count = current else: current = 0 return max_count
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a string and a character as input and returns the number of times the character appears consecutively in the string. If the character does not appear consecutively, return 0.\n\nExample 1:\nInput: s = \"aaabbbaaaccc\", c = 'a'\nOutput: 3\nExplanation:\nThe ch...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4112, "level": 1, "question": "Write a function that takes a string and a character as input and returns the number of times the character appears consecutively in the string. If the character does not appear consecutively, return 0.\n\nExample 1:\nInput: s = \"aaabbbaaaccc\", c = '...
def is_rotation(list1, list2): if len(list1) != len(list2): return False if not list1: return True str1 = ', '.join(map(str, list1)) str2 = ', '.join(map(str, list2)) return str2 in str1 + ', ' + str1
simplelr_Filter
[ { "content": "Question:\nI have two lists of integers, and I want to check if one is a rotation of the other. For example, [1, 2, 3] is a rotation of [3, 1, 2]. How can I do that in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4113, "level": 1, "question": "I have two lists of integers, and I want to check if one is a rotation of the other. For example, [1, 2, 3] is a rotation of [3, 1, 2]. How can I do that in Python?", "split": "train" }
def create_2d_array(m, n): return [[0 for _ in range(n)] for _ in range(m)]
simplelr_Filter
[ { "content": "Question:\n### Creating a 2D Array with Conditions\nYou are given a function `create_2d_array` that takes in two parameters: `m` and `n`. `m` is the number of rows and `n` is the number of columns. The goal is to create a 2D array with `m` rows and `n` columns where each cell is initialized with a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4114, "level": 1, "question": "### Creating a 2D Array with Conditions\nYou are given a function `create_2d_array` that takes in two parameters: `m` and `n`. `m` is the number of rows and `n` is the number of columns. The goal is to create a 2D array with `m` rows and `n` columns wh...
def hex_to_decimal(hex_str: str) -> int: return int(hex_str[2:], 16)
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou need to implement a function `hex_to_decimal` that converts a given hexadecimal (base-16) string (prefixed with \"0x\") to its corresponding non-negative integer representation.\n\n### Function Signature\n\n```python\ndef hex_to_decimal(hex_str: str) -> int:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4115, "level": 1, "question": "### Problem Statement\n\nYou need to implement a function `hex_to_decimal` that converts a given hexadecimal (base-16) string (prefixed with \"0x\") to its corresponding non-negative integer representation.\n\n### Function Signature\n\n```python\ndef h...
def create_list(): """Creates a list of numbers with a specific pattern.""" number_list = [] for i in range(1, 11): if i % 2 == 0: number_list.append(i * 10) else: number_list.append(i) return number_list
simplelr_Filter
[ { "content": "Question:\ndef create_list():\n \"\"\"Creates a list of numbers with a specific pattern.\"\"\"\n number_list = []\n for i in range(1, 11):\n if i % 2 == 0:\n number_list.append(i * 10)\n else:\n number_list.append(i)\n return number_list\nAnswer:\nLe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4116, "level": 1, "question": "def create_list():\n \"\"\"Creates a list of numbers with a specific pattern.\"\"\"\n number_list = []\n for i in range(1, 11):\n if i % 2 == 0:\n number_list.append(i * 10)\n else:\n number_list.append(i)\n...
def longest_balanced_substring(s): stack = [-1] # Initialize stack with base index max_len = 0 for i, char in enumerate(s): if char == '(': stack.append(i) else: stack.pop() if not stack: stack.append(i) else: c...
simplelr_Apps
[ { "content": "Question:\nImplement a function `longest_balanced_substring` that takes a string consisting of parentheses '(' and ')' and returns the length of the longest balanced (well-formed) substring. A balanced parenthesis string is a string that can be properly opened and closed without mismatching.\n\nEx...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4117, "level": 1, "question": "Implement a function `longest_balanced_substring` that takes a string consisting of parentheses '(' and ')' and returns the length of the longest balanced (well-formed) substring. A balanced parenthesis string is a string that can be properly opened an...
def binary_search_insert_position(nums: list[int], target: int) -> int: low = 0 high = len(nums) - 1 while low <= high: mid = (low + high) // 2 if nums[mid] == target: return mid elif nums[mid] > target: high = mid - 1 else: low = mid + 1 ...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Context\nIn many algorithmic problems, it's crucial to quickly determine the presence of a value within a collection. One efficient way to handle such queries is by using binary search, which significantly reduces the search time compared to linear...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4118, "level": 1, "question": "### Coding Assessment Question\n\n#### Context\nIn many algorithmic problems, it's crucial to quickly determine the presence of a value within a collection. One efficient way to handle such queries is by using binary search, which significantly reduces...
def is_palindrome(seq): i = 0 j = len(seq) - 1 while i < j: if seq[i] != seq[j]: return False i += 1 j -= 1 return True
simplelr_Prefill
[ { "content": "Question:\nCreate a function that checks if a given sequence is a palindrome. A palindrome is a sequence that reads the same backward as forward. For example, the sequence \"racecar\" is a palindrome since reading it backward gives the same sequence.\nAnswer:\nLet's think step by step.\n", "ro...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4119, "level": 1, "question": "Create a function that checks if a given sequence is a palindrome. A palindrome is a sequence that reads the same backward as forward. For example, the sequence \"racecar\" is a palindrome since reading it backward gives the same sequence.", "split":...
def generate_empty_lists(n): return tuple([] for _ in range(n))
simplelr_Filter
[ { "content": "Question:\nCreate a Python function to generate a tuple of n empty lists.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4120, "level": 1, "question": "Create a Python function to generate a tuple of n empty lists.", "split": "train" }
from collections import deque def min_steps_to_one(x): if x == 1: return 0 visited = set() queue = deque() queue.append((x, 0)) while queue: current, steps = queue.popleft() if current == 1: return steps if current in visited: continue ...
simplelr_Apps
[ { "content": "Question:\nWrite a program to calculate the minimum number of steps required to reduce a given integer x to 1. You can perform any of the following operations:\n\n1. If x is even, divide it by 2.\n2. If x is odd, you can either subtract 1 or add 1.\n\nExample 1:\nInput: x = 8\nOutput: 3\nExplanati...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4121, "level": 1, "question": "Write a program to calculate the minimum number of steps required to reduce a given integer x to 1. You can perform any of the following operations:\n\n1. If x is even, divide it by 2.\n2. If x is odd, you can either subtract 1 or add 1.\n\nExample 1:\...
def find_repeated_elements(lst): counts = {} for num in lst: counts[num] = counts.get(num, 0) + 1 return [num for num, cnt in counts.items() if cnt > 1]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers as an argument. The function will return a new list that contains only the elements that appear more than once in the input list. If an element appears only once, it should not be included in the output list.\nAnswer:\nLet's think step by ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4122, "level": 1, "question": "Create a function that takes a list of integers as an argument. The function will return a new list that contains only the elements that appear more than once in the input list. If an element appears only once, it should not be included in the output l...
from collections import Counter def create_histogram(input_list: list) -> dict: return dict(Counter(input_list))
simplelr_Data_Structure
[ { "content": "Question:\n### Histogram Function Challenge\n\nGiven an unsorted list of elements, your task is to implement a function that returns its histogram. A histogram is a representation of the frequency distribution of the elements in the list.\n\n#### Function Signature\n```python\ndef create_histogram...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4123, "level": 1, "question": "### Histogram Function Challenge\n\nGiven an unsorted list of elements, your task is to implement a function that returns its histogram. A histogram is a representation of the frequency distribution of the elements in the list.\n\n#### Function Signatu...
def char_indices(s): char_indices = {} for index, char in enumerate(s): if char in char_indices: char_indices[char].append(index) else: char_indices[char] = [index] return char_indices
simplelr_Filter
[ { "content": "Question:\nPlease provide a Python code snippet that creates a dictionary of lists, where the keys are characters from a given string, and the values are lists of indices where each character appears in the string. For example, for the string \"test\", the dictionary would look like `{'t': [0, 3],...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4124, "level": 1, "question": "Please provide a Python code snippet that creates a dictionary of lists, where the keys are characters from a given string, and the values are lists of indices where each character appears in the string. For example, for the string \"test\", the dictio...
from typing import List def find_duplicate_number(numbers: List[int]) -> int: m = len(numbers) expected_sum = m * (m - 1) // 2 actual_sum = sum(numbers) return actual_sum - expected_sum
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are given an input list of integers where each element is in the range from 1 to n (inclusive) and each number appears exactly once except one number which appears twice. Your task is to write a function `find_duplicate_number` that finds and returns the dupli...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4125, "level": 1, "question": "### Problem Statement\nYou are given an input list of integers where each element is in the range from 1 to n (inclusive) and each number appears exactly once except one number which appears twice. Your task is to write a function `find_duplicate_numbe...
import csv def read_csv_file(file_path): with open(file_path, 'r') as file: csv_reader = csv.DictReader(file) rows = list(csv_reader) return rows
simplelr_Filter
[ { "content": "Question:\nCan you generate a code snippet in Python for a function that reads a CSV file and returns a list of dictionaries, where each dictionary represents a row in the CSV file?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4126, "level": 1, "question": "Can you generate a code snippet in Python for a function that reads a CSV file and returns a list of dictionaries, where each dictionary represents a row in the CSV file?", "split": "train" }
def kth_smallest(nums, k): sorted_nums = sorted(nums) return sorted_nums[k-1]
simplelr_Apps
[ { "content": "Question:\nGiven an integer array nums and an integer k, find the k-th smallest element in the array.\n\nExample:\n\nInput: nums = [7, 10, 4, 3, 20, 15], k = 3\nOutput: 7\nExplanation: The 3rd smallest element in the array is 7.\n\nNote:\n\nYou may assume k is always valid, 1 ≤ k ≤ array's length....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4127, "level": 1, "question": "Given an integer array nums and an integer k, find the k-th smallest element in the array.\n\nExample:\n\nInput: nums = [7, 10, 4, 3, 20, 15], k = 3\nOutput: 7\nExplanation: The 3rd smallest element in the array is 7.\n\nNote:\n\nYou may assume k is al...
from typing import List, Tuple def compress_binary_image(image: List[List[int]]) -> List[Tuple[int, int]]: result = [] for row in image: if not row: continue # though per problem statement, row is non-empty current_val = row[0] count = 1 for i in range(1, len(row)):...
simplelr_Algorithm
[ { "content": "Question:\n### Binary Image Compression\n\nYou are given a binary image represented as a 2D list of integers, where each integer is either 0 (representing a white pixel) or 1 (representing a black pixel). The task is to compress this image using Run-Length Encoding (RLE). RLE is a simple form of d...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4128, "level": 1, "question": "### Binary Image Compression\n\nYou are given a binary image represented as a 2D list of integers, where each integer is either 0 (representing a white pixel) or 1 (representing a black pixel). The task is to compress this image using Run-Length Encodi...
def decimal_to_binary(n): return bin(n).replace('0b', '')
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to return the Binary Equivalent of a given decimal number. The function should accept an integer value and return a string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4129, "level": 1, "question": "Write a python function to return the Binary Equivalent of a given decimal number. The function should accept an integer value and return a string.", "split": "train" }
def find_longest_subarray_with_sum(arr, target): sum_indices = {0: -1} current_sum = 0 max_length = 0 for i, num in enumerate(arr): current_sum += num if (current_sum - target) in sum_indices: length = i - sum_indices[current_sum - target] if length > max_length: ...
simplelr_Package
[ { "content": "Question:\nCreate a function to find the longest subarray with sum equal to a given target in an array of integers.\nNote that: The function should iterate through the array, using a hash map to store the cumulative sum at each index. If the difference between the current cumulative sum and the ta...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4130, "level": 1, "question": "Create a function to find the longest subarray with sum equal to a given target in an array of integers.\nNote that: The function should iterate through the array, using a hash map to store the cumulative sum at each index. If the difference between th...
def sift_and_remove_short_elements(array): return [element for element in array if len(element) >= 4]
simplelr_Filter
[ { "content": "Question:\nFormulate a Python-coded proposition that operates in a manner to sift through a given array, driven by a goal to isolate and eliminate elements whose length manifests as less than four characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4131, "level": 1, "question": "Formulate a Python-coded proposition that operates in a manner to sift through a given array, driven by a goal to isolate and eliminate elements whose length manifests as less than four characters.", "split": "train" }
def max_subarray_sum(array): if not array: return 0 # Assuming the function should return 0 for an empty array max_ending_here = max_so_far = array[0] for num in array[1:]: max_ending_here = max(num, max_ending_here + num) max_so_far = max(max_so_far, max_ending_here) return max...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the maximum subarray sum using Kadane's Algorithm. Implement the function in Python and ensure it returns the maximum sum found. If the array contains only negative numbers, return the maximum single element in the array.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4132, "level": 1, "question": "Write a function to find the maximum subarray sum using Kadane's Algorithm. Implement the function in Python and ensure it returns the maximum sum found. If the array contains only negative numbers, return the maximum single element in the array.", "...
def is_perfect_square(x): if x < 0: return False if x == 0: return True low = 1 high = x while low <= high: mid = (low + high) // 2 square = mid * mid if square == x: return True elif square < x: low = mid + 1 else: ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nA perfect square is an integer that is the square of some integer. For example, 1, 4, 9, and 16 are perfect squares because:\n- 1 = 1 * 1\n- 4 = 2 * 2\n- 9 = 3 * 3\n- 16 = 4 * 4\n\nWrite a function `is_perfect_square` that takes an integer `x` as input and returns...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4133, "level": 1, "question": "### Problem Statement\nA perfect square is an integer that is the square of some integer. For example, 1, 4, 9, and 16 are perfect squares because:\n- 1 = 1 * 1\n- 4 = 2 * 2\n- 9 = 3 * 3\n- 16 = 4 * 4\n\nWrite a function `is_perfect_square` that takes ...
def longestSunnyStreak(forecast): max_streak = 0 current_streak = 0 for char in forecast: if char == 'S': current_streak += 1 if current_streak > max_streak: max_streak = current_streak else: current_streak = 0 return max_streak
simplelr_Taco
[ { "content": "Question:\nGiven a string representing the forecast for the next N days. Each character in the string is either 'S' (Sunny), 'C' (Cloudy), or 'R' (Rainy). You need to determine the longest consecutive sequence of sunny days.\n\nExample 1:\nInput:\nforecast = \"SRSSC\"\nOutput: 2\nExplanation: The ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4134, "level": 1, "question": "Given a string representing the forecast for the next N days. Each character in the string is either 'S' (Sunny), 'C' (Cloudy), or 'R' (Rainy). You need to determine the longest consecutive sequence of sunny days.\n\nExample 1:\nInput:\nforecast = \"SR...
def find_first_duplicate(arr): seen = {} for i, num in enumerate(arr): if num in seen: return num seen[num] = i return -1
simplelr_Filter
[ { "content": "Question:\nGiven an array of integers, find the first duplicate in the array. A duplicate is an element that appears more than once in the array. If no duplicates are found, return -1.\n\nExample:\nInput: [1, 2, 3, 4, 2]\nOutput: 2\n\nExample:\nInput: [1, 2, 3, 4, 5]\nOutput: -1\n```\ndef find_fir...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4135, "level": 1, "question": "Given an array of integers, find the first duplicate in the array. A duplicate is an element that appears more than once in the array. If no duplicates are found, return -1.\n\nExample:\nInput: [1, 2, 3, 4, 2]\nOutput: 2\n\nExample:\nInput: [1, 2, 3, 4...
def insert_string_at_index(lst, s, index): lst.insert(index, s) return lst
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to insert a given string to be inserted at a specified index in a list. The function should take three parameters: the list to be modified, the string to be inserted, and the index at which the string should be inserted.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4136, "level": 1, "question": "Write a python function to insert a given string to be inserted at a specified index in a list. The function should take three parameters: the list to be modified, the string to be inserted, and the index at which the string should be inserted.", "sp...
import heapq from typing import List def find_kth_largest(nums: List[int], k: int) -> int: heap = [] for num in nums: if len(heap) < k: heapq.heappush(heap, num) else: if num > heap[0]: heapq.heappop(heap) heapq.heappush(heap, num) ret...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Question\n**Title: Finding the K-th Largest Element in an Array**\n\n**Background**: Often in array manipulation, it is necessary to determine the position of a specific element relative to the order of the array. One common task is finding the k-th largest element within an ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4137, "level": 1, "question": "### Coding Question\n**Title: Finding the K-th Largest Element in an Array**\n\n**Background**: Often in array manipulation, it is necessary to determine the position of a specific element relative to the order of the array. One common task is finding ...
def max_product_subarray(arr): if not arr: return 0 # Assuming the function should return 0 for an empty array, but the problem states it's non-empty. max_so_far = arr[0] min_so_far = arr[0] overall_max = arr[0] for i in range(1, len(arr)): current = arr[i] temp = max_s...
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `arr`, find the contiguous subarray (containing at least one number) which has the largest product and return its product. A contiguous subarray is a subarray within an array that is continuous, meaning that the subarray elements are consecutive elements in the or...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4138, "level": 1, "question": "Given an integer array `arr`, find the contiguous subarray (containing at least one number) which has the largest product and return its product. A contiguous subarray is a subarray within an array that is continuous, meaning that the subarray elements...
import re def simple_sentiment_analysis(text: str, positive_words: list, negative_words: list) -> str: """ Determines the sentiment of the given text based on predefined positive and negative words. Parameters: - text (str): The input text to analyze. - positive_words (list): A list of words c...
simplelr_Algorithm
[ { "content": "Question:\n**Task**: Implement a function that performs sentiment analysis on a string of text using a simple rule-based approach.\n\n### Scenario\nYou are tasked with developing a rudimentary sentiment analysis tool that can classify pieces of text as \"positive\", \"negative\", or \"neutral\" ba...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4139, "level": 1, "question": "**Task**: Implement a function that performs sentiment analysis on a string of text using a simple rule-based approach.\n\n### Scenario\nYou are tasked with developing a rudimentary sentiment analysis tool that can classify pieces of text as \"positive...
def min_absolute_difference_indices(arr, x, y): if x == y: if x in arr: return 0 else: return -1 else: x_indices = [i for i, num in enumerate(arr) if num == x] y_indices = [i for i, num in enumerate(arr) if num == y] if not x_indices or not y_indic...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an integer array `arr` of length `n` and two integers `x` and `y`. Your task is to find the minimum absolute difference between the indices of the elements `x` and `y` in the array. If either `x` or `y` is not present in the array, return `-1`. The array can contain duplic...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4140, "level": 1, "question": "You are given an integer array `arr` of length `n` and two integers `x` and `y`. Your task is to find the minimum absolute difference between the indices of the elements `x` and `y` in the array. If either `x` or `y` is not present in the array, return...
def mergeSortedLists(list1, list2): result = [] i = j = 0 while i < len(list1) and j < len(list2): if list1[i] <= list2[j]: result.append(list1[i]) i += 1 else: result.append(list2[j]) j += 1 result += list1[i:] result += list2[j:] ...
simplelr_Taco
[ { "content": "Question:\nWrite a function called `mergeSortedLists` that takes two sorted lists of integers, `list1` and `list2`, and merges them into one sorted list without using any built-in sort methods. \n\nExample 1:\n```python\nlist1 = [1, 3, 5]\nlist2 = [2, 4, 6]\nmergeSortedLists(list1, list2) # return...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4141, "level": 1, "question": "Write a function called `mergeSortedLists` that takes two sorted lists of integers, `list1` and `list2`, and merges them into one sorted list without using any built-in sort methods. \n\nExample 1:\n```python\nlist1 = [1, 3, 5]\nlist2 = [2, 4, 6]\nmerg...
def advanced_reverse(s: str) -> str: chars = list(s) left = 0 right = len(chars) - 1 while left < right: chars[left], chars[right] = chars[right], chars[left] left += 1 right -= 1 return ''.join(chars)
simplelr_Data_Structure
[ { "content": "Question:\n### Question: Advanced String Reversal\n\nYou are required to implement a function `advanced_reverse` that efficiently reverses a string. The function should utilize an iterative method that is both time and space efficient without using Python built-in slicing or `reversed` functions.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4142, "level": 1, "question": "### Question: Advanced String Reversal\n\nYou are required to implement a function `advanced_reverse` that efficiently reverses a string. The function should utilize an iterative method that is both time and space efficient without using Python built-i...
def most_frequent_integer(lst): if not lst: return None freq = {} first_occurrence = {} for index, num in enumerate(lst): if num not in freq: freq[num] = 1 first_occurrence[num] = index else: freq[num] += 1 max_count = 0 ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the most frequent integer in a given list while maintaining the order of their first appearance. If there are multiple integers with the same frequency, return the one that appears first. If the list is empty, return `None`.\nAnswer:\nLet's think step by ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4143, "level": 1, "question": "Write a python function to find the most frequent integer in a given list while maintaining the order of their first appearance. If there are multiple integers with the same frequency, return the one that appears first. If the list is empty, return `No...
def length_of_longest_substring(s: str) -> int: n = len(s) longest_length = 0 start = 0 char_index_map = {} for i in range(n): if s[i] in char_index_map and char_index_map[s[i]] >= start: start = char_index_map[s[i]] + 1 char_index_map[s[i]] = i longest_length = ...
simplelr_Filter
[ { "content": "Question:\nWe are given a string and we want to find the length of the longest substring without repeating characters.\n\nFor example:\n- Input: \"abcabcbb\"\n- Output: 3\n\nExplanation: The longest substring without repeating characters is \"abc\", which has a length of 3.\n\nHere's my Python cod...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4144, "level": 1, "question": "We are given a string and we want to find the length of the longest substring without repeating characters.\n\nFor example:\n- Input: \"abcabcbb\"\n- Output: 3\n\nExplanation: The longest substring without repeating characters is \"abc\", which has a l...
def binary_search(collection: list, target: int) -> int: low = 0 high = len(collection) - 1 while low <= high: mid = (low + high) // 2 if collection[mid] == target: return mid elif target < collection[mid]: high = mid - 1 else: low = mid + ...
simplelr_Algorithm
[ { "content": "Question:\n### Binary Search Implementation\n\n#### Context\nYou need to implement the Binary Search algorithm to find the position of a target value within a sorted list of integers. Binary Search is efficient for searching in large datasets due to its logarithmic time complexity.\n\n#### Task\nW...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4145, "level": 1, "question": "### Binary Search Implementation\n\n#### Context\nYou need to implement the Binary Search algorithm to find the position of a target value within a sorted list of integers. Binary Search is efficient for searching in large datasets due to its logarithm...
def longest_substring_with_replacements(s: str, c: str, x: int) -> int: left = 0 max_len = 0 current_count = 0 for right in range(len(s)): if s[right] != c: current_count += 1 # If current_count exceeds x, move left pointer to reduce the window while current_count > x...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s`, a character `c`, and an integer `x`, return the length of the longest substring of `s` where you are allowed to replace at most `x` characters with the character `c`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4146, "level": 1, "question": "Given a string `s`, a character `c`, and an integer `x`, return the length of the longest substring of `s` where you are allowed to replace at most `x` characters with the character `c`.", "split": "train" }
def length_of_longest_substring(s): if not s: return 0 char_index = {} max_length = 0 start = 0 for end in range(len(s)): char = s[end] if char in char_index and char_index[char] >= start: start = char_index[char] + 1 char_index[char] = end current...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s`, return the length of the longest substring where all the characters are unique. If a character repeats, the substring ends before the repeating character. Write the code that finds this length, ensuring the solution is efficient.\nAnswer:\nLet's think step by step.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4147, "level": 1, "question": "Given a string `s`, return the length of the longest substring where all the characters are unique. If a character repeats, the substring ends before the repeating character. Write the code that finds this length, ensuring the solution is efficient.", ...
def positive_divisors(n): if n < 1: raise ValueError("Number must be greater than or equal to 1.") if n == 1: return [] divisors = [1] for i in range(2, int(n**0.5) + 1): if n % i == 0: divisors.append(i) if i != n // i: divisors.append(n /...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes an integer and returns a list of all its positive divisors, excluding the number itself. The divisors should be returned in ascending order. If the input number is less than 1, the function should raise a ValueError. For example, if the input is 28, th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4148, "level": 1, "question": "Write a Python function that takes an integer and returns a list of all its positive divisors, excluding the number itself. The divisors should be returned in ascending order. If the input number is less than 1, the function should raise a ValueError. ...
import time from typing import Tuple def merge_strings_unique(str1: str, str2: str) -> Tuple[str, float]: start_time = time.time() seen = set() result = [] for char in str1: if char not in seen: result.append(char) seen.add(char) for char in str2: i...
simplelr_Package
[ { "content": "Question:\nYou are tasked with writing a function named `merge_strings_unique` that merges two strings such that the resulting string contains all unique characters from both strings in the order they first appear. Additionally, the function should measure the time taken to perform the merge opera...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4149, "level": 1, "question": "You are tasked with writing a function named `merge_strings_unique` that merges two strings such that the resulting string contains all unique characters from both strings in the order they first appear. Additionally, the function should measure the ti...
def can_assign_soldiers(soldiers, positions): soldiers_sorted = sorted(soldiers) positions_sorted = sorted(positions) j = 0 for pos in positions_sorted: while j < len(soldiers_sorted) and soldiers_sorted[j] < pos: j += 1 if j >= len(soldiers_sorted): return F...
simplelr_Apps
[ { "content": "Question:\nGiven an array of integers representing the strengths of different soldiers, and an array representing the strengths required to hold various defense positions on a battlefield, determine if there is a way to assign soldiers to positions such that each position is held by a soldier whos...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4150, "level": 1, "question": "Given an array of integers representing the strengths of different soldiers, and an array representing the strengths required to hold various defense positions on a battlefield, determine if there is a way to assign soldiers to positions such that each...
def find_unique_pairs(arr, target): n = len(arr) result = [] left = 0 right = n - 1 while left < right: current_sum = arr[left] + arr[right] if current_sum == target: result.append((arr[left], arr[right])) a = arr[left] # Skip duplicates for l...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a sorted array of integers `arr` and a target integer `target`. Your task is to find the number of unique pairs of elements in the array such that their sum is equal to `target`. Each pair should be reported in lexicographical order, and each element of the pair should be ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4151, "level": 1, "question": "You are given a sorted array of integers `arr` and a target integer `target`. Your task is to find the number of unique pairs of elements in the array such that their sum is equal to `target`. Each pair should be reported in lexicographical order, and ...
def factorial_recursive(n: int) -> int: if n == 0 or n == 1: return 1 else: return n * factorial_recursive(n - 1)
simplelr_Algorithm
[ { "content": "Question:\n### Problem: Implementing Factorial using Recursion\n\nFactorial of a non-negative integer \\( n \\) is the product of all positive integers less than or equal to \\( n \\). Your task is to implement a recursive function to calculate the factorial of a given non-negative integer.\n\n###...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4152, "level": 1, "question": "### Problem: Implementing Factorial using Recursion\n\nFactorial of a non-negative integer \\( n \\) is the product of all positive integers less than or equal to \\( n \\). Your task is to implement a recursive function to calculate the factorial of a...
def caesar_cipher(message, shift): encrypted = [] for char in message: if 'A' <= char <= 'Z': # Handle uppercase letters shifted = chr((ord(char) - ord('A') + shift) % 26 + ord('A')) encrypted.append(shifted) elif 'a' <= char <= 'z': # Handle lower...
simplelr_Filter
[ { "content": "Question:\nI'm looking for a way to encrypt a message using a simple cipher in Python. Can you provide an example of how to do this using a Caesar cipher?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4153, "level": 1, "question": "I'm looking for a way to encrypt a message using a simple cipher in Python. Can you provide an example of how to do this using a Caesar cipher?", "split": "train" }
def longest_subarray(nums): max_len = 0 freq = {} left = 0 for right in range(len(nums)): current = nums[right] if current in freq: freq[current] += 1 else: freq[current] = 1 # When the window has more than two distinct elements, move left...
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a list of integers and returns the length of the longest contiguous subarray containing at most two distinct integers.\n\n```python\nlongest_subarray([1, 2, 1]) => returns 3\nlongest_subarray([1, 2, 2, 3, 3, 4, 4, 4]) => returns 5\n```\n\nExplanation:\n\nIn t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4154, "level": 1, "question": "Write a function that takes a list of integers and returns the length of the longest contiguous subarray containing at most two distinct integers.\n\n```python\nlongest_subarray([1, 2, 1]) => returns 3\nlongest_subarray([1, 2, 2, 3, 3, 4, 4, 4]) => ret...
def convert_to_int(s): if not s: return None try: return int(s) except ValueError: return None
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to convert a string to its corresponding integer and handle missing values. If the string represents a number and can be converted without error, the function should convert it to an integer and return it. If the string is empty or cannot be converted to an integ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4155, "level": 1, "question": "Write a Python function to convert a string to its corresponding integer and handle missing values. If the string represents a number and can be converted without error, the function should convert it to an integer and return it. If the string is empty...
from typing import List def largest_rectangle_area(histogram: List[int]) -> int: stack = [] max_area = 0 n = len(histogram) for i in range(n): while stack and histogram[i] < histogram[stack[-1]]: height = histogram[stack.pop()] if stack: width = i - ...
simplelr_Package
[ { "content": "Question:\nConsider a list of integers where each integer represents the height of a bar in a histogram. Write a function to find the largest rectangle that can be formed in the histogram, given that the width of each bar is 1.\n\nYour task is to implement the function `largest_rectangle_area(hist...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4156, "level": 1, "question": "Consider a list of integers where each integer represents the height of a bar in a histogram. Write a function to find the largest rectangle that can be formed in the histogram, given that the width of each bar is 1.\n\nYour task is to implement the fu...
def longest_subarray_with_k_distinct(s: str, k: int) -> int: char_count = {} left = 0 max_length = 0 unique = 0 for right in range(len(s)): char = s[right] # Add current character to count if char in char_count: char_count[char] += 1 else: cha...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` consisting of lowercase English letters and an integer `k`. A **subarray** is a contiguous segment of a string. Consider finding the longest subarray in which there are at most `k` different characters. Write a function that returns the length of such a subarr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4157, "level": 1, "question": "You are given a string `s` consisting of lowercase English letters and an integer `k`. A **subarray** is a contiguous segment of a string. Consider finding the longest subarray in which there are at most `k` different characters. Write a function that ...
def sum_2d_matrix(matrix): return sum(num for row in matrix for num in row)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to calculate the sum of all elements in a 2D list (also known as a matrix).\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4158, "level": 1, "question": "Write a python function to calculate the sum of all elements in a 2D list (also known as a matrix).", "split": "train" }
from typing import List, Tuple, Dict def calculate_student_averages(records: List[Tuple[str, List[float]]]) -> Dict[str, float]: result = {} for record in records: student_name = record[0] scores = record[1] average = sum(scores) / len(scores) result[student_name] = average ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are given a list of student records where each record contains the student's name and their respective scores in multiple subjects. Your task is to implement a function that calculates the average score for each student and returns a dictionary with the stud...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4159, "level": 1, "question": "### Problem Statement\n\nYou are given a list of student records where each record contains the student's name and their respective scores in multiple subjects. Your task is to implement a function that calculates the average score for each student and...
def length_of_longest_substring(s): last_seen = {} max_length = 0 start = 0 for end in range(len(s)): c = s[end] if c in last_seen and last_seen[c] >= start: start = last_seen[c] + 1 last_seen[c] = end current_length = end - start + 1 if current_length...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `str` consisting of lowercase alphabets, find the length of the longest substring with all unique characters. A substring is defined as a contiguous sequence of characters within a string. Use an efficient approach to accomplish this task.\nAnswer:\nLet's think step by st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4160, "level": 1, "question": "Given a string `str` consisting of lowercase alphabets, find the length of the longest substring with all unique characters. A substring is defined as a contiguous sequence of characters within a string. Use an efficient approach to accomplish this tas...
def find_substring(s, sub): len_s = len(s) len_sub = len(sub) if len_sub == 0: return 0 if len_sub > len_s: return -1 for i in range(len_s - len_sub + 1): if s[i:i+len_sub] == sub: return i return -1
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string and a substring as input. The function should return the index of the first occurrence of the substring in the string. If the substring is not found, the function should return -1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4161, "level": 1, "question": "Create a function that takes a string and a substring as input. The function should return the index of the first occurrence of the substring in the string. If the substring is not found, the function should return -1.", "split": "train" }
def factorial(n): if n < 0: raise ValueError("n must be a non-negative integer") if n == 0 or n == 1: return 1 else: return n * factorial(n - 1)
simplelr_Filter
[ { "content": "Question:\nHow can I efficiently calculate the factorial of a number using recursion in Python, and what are the limitations of using recursion for this purpose?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4162, "level": 1, "question": "How can I efficiently calculate the factorial of a number using recursion in Python, and what are the limitations of using recursion for this purpose?", "split": "train" }
from typing import List def max_product_subarray(nums: List[int]) -> int: """ Given a list of integers, returns the maximum product of a contiguous subarray. Args: nums: List[int] - A list of integers (both positive and negative). Returns: int - The maximum product of a contiguous sub...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Challenge: Finding Subarray with Maximum Product\n\n#### Scenario\nYou are tasked as a software developer to enhance the performance of a financial analytics tool. One of the features that need optimization is a function that determines the subarray with the highest product f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4163, "level": 1, "question": "### Coding Challenge: Finding Subarray with Maximum Product\n\n#### Scenario\nYou are tasked as a software developer to enhance the performance of a financial analytics tool. One of the features that need optimization is a function that determines the ...
def sum_of_squares(arr): n = len(arr) for num in arr: if num < 1 or num > n: return -1 return sum(num ** 2 for num in arr)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the sum of squares of the elements in an array where elements are between 1 and n, where n is the size of the array. The function should return the sum if it exists, otherwise return -1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4164, "level": 1, "question": "Write a function to calculate the sum of squares of the elements in an array where elements are between 1 and n, where n is the size of the array. The function should return the sum if it exists, otherwise return -1.", "split": "train" }
def filter_people(people, min_age): return [person for person in people if person['age'] >= min_age]
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to filter a list of dictionaries, where each dictionary represents a person with the following keys: \"name\", \"age\", and \"city\". The function should take two arguments: the list of dictionaries and a minimum age. It should return a new list containing only t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4165, "level": 1, "question": "Write a Python function to filter a list of dictionaries, where each dictionary represents a person with the following keys: \"name\", \"age\", and \"city\". The function should take two arguments: the list of dictionaries and a minimum age. It should ...
def final_robot_position(commands: str) -> tuple[int, int]: x, y = 0, 0 for c in commands: if c == 'U': y += 1 elif c == 'D': y -= 1 elif c == 'R': x += 1 elif c == 'L': x -= 1 return (x, y)
simplelr_Codeforces
[ { "content": "Question:\nWrite a program to simulate a robot moving in a 2D grid. The robot starts at the coordinates (0, 0) and can move in one of four directions ('U' for up, 'D' for down, 'L' for left, 'R' for right). The robot will move according to a given sequence of commands. Your task is to determine th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4166, "level": 1, "question": "Write a program to simulate a robot moving in a 2D grid. The robot starts at the coordinates (0, 0) and can move in one of four directions ('U' for up, 'D' for down, 'L' for left, 'R' for right). The robot will move according to a given sequence of com...
def find_missing_number(nums): n = len(nums) expected_sum = (n + 1) * (n + 2) // 2 actual_sum = sum(nums) return expected_sum - actual_sum
simplelr_Evol
[ { "content": "Question:\nImplement a function `find_missing_number` that takes in a list of numbers `nums`, which contains `n` unique integers ranging from 1 to `n+1` inclusive, with one number missing. The function should return the missing number. Your solution should be efficient, aiming for linear time comp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4167, "level": 1, "question": "Implement a function `find_missing_number` that takes in a list of numbers `nums`, which contains `n` unique integers ranging from 1 to `n+1` inclusive, with one number missing. The function should return the missing number. Your solution should be eff...
def calculate_tax_credits(s): total = 0 for c in s: if c == 'A': total += 5 elif c == 'B': total += 3 else: # 'C' total += 1 divisor = 10 full_groups = total // divisor remainder = total % divisor tax_credits = full_groups * 2 tax_...
simplelr_Taco
[ { "content": "Question:\nThe kingdom of Utopia has introduced a new tax system where certain sectors receive tax credits based on their performance. Each sector's performance is gauged using points, and these tax credits are calculated based on specific rules. The kingdom's financial administrator, Eve, needs t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4168, "level": 1, "question": "The kingdom of Utopia has introduced a new tax system where certain sectors receive tax credits based on their performance. Each sector's performance is gauged using points, and these tax credits are calculated based on specific rules. The kingdom's fi...
def visualize_titanic_data(): import seaborn.objects as so from seaborn import load_dataset import matplotlib.pyplot as plt # Load the Titanic dataset and sort by 'alive' status titanic = load_dataset("titanic").sort_values("alive", ascending=False) # Create the faceted histogram hist_plot...
simplelr_Docs
[ { "content": "Question:\n**Question: Visualizing the Titanic Dataset Using Seaborn**\n\nYou are given the Titanic dataset, and your task is to create two distinct visualizations using seaborn's `objects` interface. These visualizations should capture the relationship between different variables in the dataset.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4169, "level": 1, "question": "**Question: Visualizing the Titanic Dataset Using Seaborn**\n\nYou are given the Titanic dataset, and your task is to create two distinct visualizations using seaborn's `objects` interface. These visualizations should capture the relationship between d...
def count_uppercase(s): """ Counts the number of uppercase letters in a given string. Args: s (str): The input string to be analyzed. Returns: int: The number of uppercase letters present in the string. Example: >>> count_uppercase("Hello World") 2 >>> coun...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a string as input and returns the number of uppercase letters present in the string. The function should be named `count_uppercase` and should be thoroughly documented with a docstring.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4170, "level": 1, "question": "Write a Python function that takes a string as input and returns the number of uppercase letters present in the string. The function should be named `count_uppercase` and should be thoroughly documented with a docstring.", "split": "train" }
import pandas as pd def analyze_sales(data1_path: str, data2_path: str) -> (pd.DataFrame, pd.DataFrame): # Load the data from JSON files df1 = pd.read_json(data1_path) df2 = pd.read_json(data2_path) # Convert date columns to datetime df1['date'] = pd.to_datetime(df1['date']) df2['date'] = ...
simplelr_Docs
[ { "content": "Question:\n**Coding Assessment Question**\n\n### Objective\nEvaluate the students' knowledge of pandas functionality, covering data creation, manipulation, merging, and a series of calculations using the apply and aggregation methods.\n\n### Problem Statement\nImagine you have two datasets represe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4171, "level": 1, "question": "**Coding Assessment Question**\n\n### Objective\nEvaluate the students' knowledge of pandas functionality, covering data creation, manipulation, merging, and a series of calculations using the apply and aggregation methods.\n\n### Problem Statement\nIm...
def max_profit(prices): buy1 = -float('inf') sell1 = 0 buy2 = -float('inf') sell2 = 0 for price in prices: buy1 = max(buy1, -price) sell1 = max(sell1, buy1 + price) buy2 = max(buy2, sell1 - price) sell2 = max(sell2, buy2 + price) return sell2
simplelr_Taco
[ { "content": "Question:\nYou are given a sequence of integers representing stock prices recorded at different times during a single day. You want to buy and sell the stock at two different times, but the sale must occur after the purchase. The goal is to maximize the profit from one transaction (i.e., buy one a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4172, "level": 1, "question": "You are given a sequence of integers representing stock prices recorded at different times during a single day. You want to buy and sell the stock at two different times, but the sale must occur after the purchase. The goal is to maximize the profit fr...
def summarize_purchases(purchases): customer_spending = {} for customer, amount in purchases: customer_spending[customer] = customer_spending.get(customer, 0) + amount return customer_spending
simplelr_Code_Contests
[ { "content": "Question:\nAn online store wants to analyze the purchasing behavior of its customers. They want a function that takes a list of tuples, each representing a purchase record, and returns a summary of total spending by each unique customer. Each purchase record contains the customer ID and the amount...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4173, "level": 1, "question": "An online store wants to analyze the purchasing behavior of its customers. They want a function that takes a list of tuples, each representing a purchase record, and returns a summary of total spending by each unique customer. Each purchase record cont...
def max_product_of_three(arr): arr.sort() product1 = arr[-1] * arr[-2] * arr[-3] product2 = arr[0] * arr[1] * arr[-1] return max(product1, product2)
simplelr_Code_Contests
[ { "content": "Question:\nGiven an array of integers, determine the maximum product of any three distinct elements in the array. Your task is to write a function that takes an array of integers and returns the maximum product of any three distinct elements.\n\nInput\n\nAn array of integers `arr` (3 ≤ len(arr) ≤ ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4174, "level": 1, "question": "Given an array of integers, determine the maximum product of any three distinct elements in the array. Your task is to write a function that takes an array of integers and returns the maximum product of any three distinct elements.\n\nInput\n\nAn array...
def product_except_self(nums): n = len(nums) if n == 0: return [] prefix = [1] * (n + 1) for i in range(1, n + 1): prefix[i] = prefix[i-1] * nums[i-1] suffix = [1] * (n + 1) for i in range(n-1, -1, -1): suffix[i] = suffix[i+1] * nums[i] output = [] for i in range(...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an integer array `nums` of length `n` and returns an array `output` of length `n` where `output[i]` is the product of all elements in `nums` except `nums[i]` itself without using division.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4175, "level": 1, "question": "Create a function that takes an integer array `nums` of length `n` and returns an array `output` of length `n` where `output[i]` is the product of all elements in `nums` except `nums[i]` itself without using division.", "split": "train" }
def categorize_messages(messages): """ Categorize messages based on their content into greeting, farewell, question, or unknown. Args: messages (list): A list of dictionaries, each containing a 'text' key. Returns: dict: A dictionary with categories as keys and lists of corresp...
simplelr_Filter
[ { "content": "Question:\nYou have been tasked with writing a Python function `categorize_messages` that takes in a list of messages where each message is a dictionary with a 'text' key. The function should categorize these messages based on their content and return a dictionary with categories as keys and a lis...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4176, "level": 1, "question": "You have been tasked with writing a Python function `categorize_messages` that takes in a list of messages where each message is a dictionary with a 'text' key. The function should categorize these messages based on their content and return a dictionar...
import bisect from collections import defaultdict def len_longest_fib_subseq(nums): index_map = defaultdict(list) for idx, num in enumerate(nums): index_map[num].append(idx) max_length = 0 n = len(nums) for i in range(n): for j in range(i + 1, n): a, b = nums[i], nu...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `nums`, return _the length of the longest subsequence that is a valid Fibonacci-like sequence_. A **Fibonacci-like sequence** is defined as a sequence that starts with two integers, and each subsequent integer is the sum of the previous two. Note that the sequ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4177, "level": 1, "question": "Given an array of integers `nums`, return _the length of the longest subsequence that is a valid Fibonacci-like sequence_. A **Fibonacci-like sequence** is defined as a sequence that starts with two integers, and each subsequent integer is the sum of t...
def find_longest_word(word_list): if not word_list: return '' longest_word = word_list[0] max_length = len(longest_word) for word in word_list[1:]: current_length = len(word) if current_length > max_length: longest_word = word max_length = current_length ...
simplelr_Evol
[ { "content": "Question:\nCraft a Python function named `find_longest_word` that takes a single argument, a list of strings. This function should return the longest word in the list. In case of a tie (multiple words having the same maximum length), return the word that appears first in the list. Ensure your func...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4178, "level": 1, "question": "Craft a Python function named `find_longest_word` that takes a single argument, a list of strings. This function should return the longest word in the list. In case of a tie (multiple words having the same maximum length), return the word that appears ...
def pair_and_sort(employees, scores): if len(employees) != len(scores): raise ValueError("The number of employees and scores must match.") paired_list = list(zip(employees, scores)) paired_list.sort(key=lambda x: x[1], reverse=True) return paired_list # Example usage: employees = ["Alice", "Bob...
simplelr_Filter
[ { "content": "Question:\nHere's a simple Python task: Write a script that accepts a list of strings, where each string is an employee's name, and a list of integers, where each integer represents a score. The script should pair each employee with their corresponding score and sort the list in descending order o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4179, "level": 1, "question": "Here's a simple Python task: Write a script that accepts a list of strings, where each string is an employee's name, and a list of integers, where each integer represents a score. The script should pair each employee with their corresponding score and ...
def find_modes(arr: list[int]) -> list[int]: if not arr: return [] freq = {} order = [] for num in arr: if num not in freq: freq[num] = 1 order.append(num) else: freq[num] += 1 max_freq = max(freq.values()) modes = [num for num in order...
simplelr_Data_Structure
[ { "content": "Question:\n**Context**:\nYou are working on data analysis for customer reviews. To understand customer preferences, you need to find out which products are mentioned most frequently in an array of product IDs. However, reviews might have multiple most frequently mentioned products (modes).\n\n**Qu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4180, "level": 1, "question": "**Context**:\nYou are working on data analysis for customer reviews. To understand customer preferences, you need to find out which products are mentioned most frequently in an array of product IDs. However, reviews might have multiple most frequently ...
import getpass def authenticate_user(users_db: dict) -> bool: try: # Prompt the user for their login name username = input("Enter your login name: ") # Get the system's login name system_user = getpass.getuser() # Check if the input login name matches the system's login name...
simplelr_Docs
[ { "content": "Question:\n### Secure User Authentication System\n\n**Objective:**\nImplement a Python function that leverages the `getpass` module to create a secure user authentication system.\n\n**Task:**\nWrite a function `authenticate_user(users_db: dict) -> bool` that:\n\n1. Prompts the user to input their ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4181, "level": 1, "question": "### Secure User Authentication System\n\n**Objective:**\nImplement a Python function that leverages the `getpass` module to create a secure user authentication system.\n\n**Task:**\nWrite a function `authenticate_user(users_db: dict) -> bool` that:\n\n...
def is_palindrome(s): cleaned = ''.join([c for c in s.lower() if c.isalnum()]) return cleaned == cleaned[::-1]
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function to check if a given string is a palindrome, ignoring spaces, punctuation, and case sensitivity?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4182, "level": 1, "question": "How can I create a Python function to check if a given string is a palindrome, ignoring spaces, punctuation, and case sensitivity?", "split": "train" }
import torch def transform_named_tensor(input_tensor: torch.Tensor) -> torch.Tensor: """ Transform the input named tensor according to the given rules. Parameters: input_tensor (torch.Tensor): A named tensor of shape (N, C, H, W). Returns: torch.Tensor: The transformed tensor with appropriate...
simplelr_Docs
[ { "content": "Question:\n**Task:** Implement a function using PyTorch that takes as input a named tensor and performs a series of operations that demonstrate understanding of name inference rules as described in the provided documentation.\n\n### Function Signature\n```python\nimport torch\n\ndef transform_name...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4183, "level": 1, "question": "**Task:** Implement a function using PyTorch that takes as input a named tensor and performs a series of operations that demonstrate understanding of name inference rules as described in the provided documentation.\n\n### Function Signature\n```python\...
def find_duplicates(data): seen = set() duplicates = set() for num in data: if num in seen: duplicates.add(num) else: seen.add(num) return duplicates
simplelr_Algorithm
[ { "content": "Question:\n### Question: Data Validation for Unique Values\n\nIn data processing and analytics, it's common to encounter scenarios where you need to ensure that a dataset contains only unique values. This task will help you enforce data integrity by identifying any duplicate values within an input...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4184, "level": 1, "question": "### Question: Data Validation for Unique Values\n\nIn data processing and analytics, it's common to encounter scenarios where you need to ensure that a dataset contains only unique values. This task will help you enforce data integrity by identifying a...
def add_persistence(n): count = 0 while n >= 10: total = 0 while n > 0: total += n % 10 n = n // 10 n = total count += 1 return count
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a string of digits and calculates the add persistence of that number. Add persistence describes the number of times you must sum the digits of a number until you reach a single digit.\n\nFor example, `999` would become:\n```\nStep 1: 9 + 9 + 9 = 27\nStep 2: 2...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4185, "level": 1, "question": "Write a function that takes a string of digits and calculates the add persistence of that number. Add persistence describes the number of times you must sum the digits of a number until you reach a single digit.\n\nFor example, `999` would become:\n```...
def single_number(arr): res = 0 for num in arr: res ^= num return res
simplelr_Leetcode
[ { "content": "Question:\nGiven an array `arr` consisting of integers where every element appears exactly twice, except for one element which appears exactly once, return the single element that appears only once.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4186, "level": 1, "question": "Given an array `arr` consisting of integers where every element appears exactly twice, except for one element which appears exactly once, return the single element that appears only once.", "split": "train" }
from typing import List def max_profit(prices: List[int]) -> int: if len(prices) < 2: return 0 max_profit = 0 min_price = prices[0] for price in prices[1:]: current_profit = price - min_price if current_profit > max_profit: max_profit = current_profit if pric...
simplelr_Apps
[ { "content": "Question:\nConsider a list of positive integers representing stock prices of a company for `n` consecutive days, where the index of the list represents the day. You are allowed to buy and sell a single stock only once. Your goal is to maximize the profit by choosing a single day to buy the stock a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4187, "level": 1, "question": "Consider a list of positive integers representing stock prices of a company for `n` consecutive days, where the index of the list represents the day. You are allowed to buy and sell a single stock only once. Your goal is to maximize the profit by choos...
def is_power_of_two(n): """ Check if a number is a power of two. Args: n (int): The number to check. Returns: bool: True if the number is a power of two, False otherwise. """ if n <= 0: return False return (n & (n - 1)) == 0 # Example usage: print(is_po...
simplelr_Filter
[ { "content": "Question:\nOk, I want to create a script written in Python to check if a number is a power of 2. \nCan you provide me with an example of how to accomplish this?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4188, "level": 1, "question": "Ok, I want to create a script written in Python to check if a number is a power of 2. \nCan you provide me with an example of how to accomplish this?", "split": "train" }
def longest_substring(s): left = 0 max_length = 0 char_index = {} 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[char] = right current_length = right - left + 1 if ...
simplelr_Filter
[ { "content": "Question:\nThis is a code that defines a Python function `longest_substring(s)` that takes a string as input and returns the length of the longest substring without repeating characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4189, "level": 1, "question": "This is a code that defines a Python function `longest_substring(s)` that takes a string as input and returns the length of the longest substring without repeating characters.", "split": "train" }
import heapq from collections import Counter def reorganize_string(s): if not s: return s counts = Counter(s) max_char = None max_count = 0 for char, cnt in counts.items(): if cnt > max_count: max_char = char max_count = cnt if max_count > ...
simplelr_Taco
[ { "content": "Question:\nYou are given a string s consisting of lowercase English letters. You need to check if it is possible to rearrange the characters of the string such that no two adjacent characters are the same. If possible, return the rearranged string, otherwise, return an empty string.\n\nInput\n\nTh...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4190, "level": 1, "question": "You are given a string s consisting of lowercase English letters. You need to check if it is possible to rearrange the characters of the string such that no two adjacent characters are the same. If possible, return the rearranged string, otherwise, ret...
def custom_strlen(s): count = 0 index = 0 while True: try: s[index] except IndexError: break count += 1 index += 1 return count
simplelr_Filter
[ { "content": "Question:\nI need to write a custom function in Python to calculate the length of a string. However, I don't want to use any built-in functions or libraries. How can I do this using a while loop?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4191, "level": 1, "question": "I need to write a custom function in Python to calculate the length of a string. However, I don't want to use any built-in functions or libraries. How can I do this using a while loop?", "split": "train" }
def remove_all_occurrences(lst, element): return [x for x in lst if x != element]
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python function to remove all occurrences of a specific element from a list?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4192, "level": 1, "question": "Can you provide a Python function to remove all occurrences of a specific element from a list?", "split": "train" }
import re def is_valid_license_plate(s): return bool(re.fullmatch(r'^[A-Z]{3}\d{3}$', s))
simplelr_Evol
[ { "content": "Question:\nWrite a Python function `is_valid_license_plate` that takes a string as input and returns `True` if the string is a valid license plate number and `False` otherwise. A valid license plate number follows these rules:\n- It must be exactly 6 characters long.\n- The first 3 characters must...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4193, "level": 1, "question": "Write a Python function `is_valid_license_plate` that takes a string as input and returns `True` if the string is a valid license plate number and `False` otherwise. A valid license plate number follows these rules:\n- It must be exactly 6 characters l...
import json def extract_user_id(json_str): try: data = json.loads(json_str) return data.get('user_id') except json.JSONDecodeError: return None
simplelr_Filter
[ { "content": "Question:\nWrite a Python code snippet to extract the value associated with the key 'user_id' from a JSON object represented as a string. The JSON object may or may not contain the 'user_id' key. If the key is not present, the function should return None.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4194, "level": 1, "question": "Write a Python code snippet to extract the value associated with the key 'user_id' from a JSON object represented as a string. The JSON object may or may not contain the 'user_id' key. If the key is not present, the function should return None.", "sp...
import re from collections import Counter from typing import List def top_k_frequent_words(s: str, k: int) -> List[str]: # Extract all alphabetic words and convert to lowercase words = re.findall(r'[a-zA-Z]+', s) words = [word.lower() for word in words] # Count the frequency of each word word_...
simplelr_Evol
[ { "content": "Question:\nDesign a function that takes a string of words and a positive integer k as input, and returns the k most frequent words in the string sorted by their frequency. In case of a tie, sort the words alphabetically. Ignore any non-alphabetic characters in the string.\n\nExample:\n\nInput: \"T...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4195, "level": 1, "question": "Design a function that takes a string of words and a positive integer k as input, and returns the k most frequent words in the string sorted by their frequency. In case of a tie, sort the words alphabetically. Ignore any non-alphabetic characters in th...
def enhanced_gcd(a: int, b: int) -> int: """ Enhanced function to compute the greatest common divisor of two non-negative integers. :param a: A non-negative integer. :param b: A non-negative integer. :return: An integer representing the greatest common divisor of a and b. """ if a == 0:...
simplelr_Data_Structure
[ { "content": "Question:\n### Question: Enhanced Greatest Common Divisor Implementation with Applications\n\nYou are asked to implement a function that computes the greatest common divisor (GCD) of two non-negative integers using multiple approaches, ensuring optimization and error handling. Utilize bitwise oper...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4196, "level": 1, "question": "### Question: Enhanced Greatest Common Divisor Implementation with Applications\n\nYou are asked to implement a function that computes the greatest common divisor (GCD) of two non-negative integers using multiple approaches, ensuring optimization and e...
def two_sum(nums, target): if len(nums) < 2: return False seen = set() for num in nums: complement = target - num if complement in seen: return True seen.add(num) return False
simplelr_Algorithm
[ { "content": "Question:\n### Context\nYou are given an array of integers and an integer target. Your task is to determine if there are two distinct elements in the array that sum up to the target value.\n\n### Function Signature\nWrite a function called `two_sum` that takes in a list of integers and a single in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4197, "level": 1, "question": "### Context\nYou are given an array of integers and an integer target. Your task is to determine if there are two distinct elements in the array that sum up to the target value.\n\n### Function Signature\nWrite a function called `two_sum` that takes in...
def fizz_buzz(n): result = [] for i in range(1, n + 1): if i % 15 == 0: result.append("FizzBuzz") elif i % 3 == 0: result.append("Fizz") elif i % 5 == 0: result.append("Buzz") else: result.append(str(i)) return result
simplelr_Taco
[ { "content": "Question:\nYou are given an integer `n`. Your task is to generate a list of strings based on the following pattern:\n\nFor each number `i` from 1 to `n`:\n1. If the number is divisible by both 3 and 5, append \"FizzBuzz\" to the list.\n2. If the number is divisible by 3 but not 5, append \"Fizz\" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4198, "level": 1, "question": "You are given an integer `n`. Your task is to generate a list of strings based on the following pattern:\n\nFor each number `i` from 1 to `n`:\n1. If the number is divisible by both 3 and 5, append \"FizzBuzz\" to the list.\n2. If the number is divisib...
from collections import deque def shortest_path(board, start, end): if start == end: return 0 rows = len(board) if rows == 0: return -1 cols = len(board[0]) x1, y1 = start x2, y2 = end if board[x1][y1] == 1 or board[x2][y2] == 1: return -1 visited = [[False for _...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a 2D grid `board` representing a matrix of cells where each cell is either `0` (empty) or `1` (occupied). You are also given two points, `start` and `end`, representing the starting and ending cells, respectively, on the grid. You need to find the shortest path from `start...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4199, "level": 1, "question": "You are given a 2D grid `board` representing a matrix of cells where each cell is either `0` (empty) or `1` (occupied). You are also given two points, `start` and `end`, representing the starting and ending cells, respectively, on the grid. You need to...