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 sum_of_adjacent_elements(lst): if len(lst) < 2: return [] result = [] for i in range(len(lst) - 1): result.append(lst[i] + lst[i + 1]) return result
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers as input and returns a new list where each element is the sum of the adjacent elements in the input list. If the input list has less than two elements, return an empty list. For example, given the list [1, 2, 3, 4], the function should ret...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9200, "level": 1, "question": "Create a function that takes a list of integers as input and returns a new list where each element is the sum of the adjacent elements in the input list. If the input list has less than two elements, return an empty list. For example, given the list [1...
from collections import deque from typing import List def shortestPath(grid: List[List[int]]) -> int: rows = len(grid) if rows == 0: return -1 cols = len(grid[0]) if grid[0][0] == 1 or grid[rows-1][cols-1] == 1: return -1 if rows == 1 and cols == 1: return 0 visited = [...
simplelr_Apps
[ { "content": "Question:\nYou are given a 2D grid where some of the cells are empty (represented by 0) and some are obstacles (represented by 1). You need to find the shortest path from the top-left corner (0, 0) to the bottom-right corner (n-1, m-1), avoiding the obstacles. You can only move up, down, left, and...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9201, "level": 1, "question": "You are given a 2D grid where some of the cells are empty (represented by 0) and some are obstacles (represented by 1). You need to find the shortest path from the top-left corner (0, 0) to the bottom-right corner (n-1, m-1), avoiding the obstacles. Yo...
def char_count(s): counts = {} for char in s.lower(): if char in counts: counts[char] += 1 else: counts[char] = 1 return counts if __name__ == "__main__": user_str = input("Enter a string: ") result = char_count(user_str) print(result)
simplelr_Evol
[ { "content": "Question:\nWrite a Python function that takes a string as input and returns a dictionary where each key is a character from the string, and the corresponding value is the count of how often that character appears in the string. Characters should be treated as case-insensitive, meaning 'A' and 'a' ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9202, "level": 1, "question": "Write a Python function that takes a string as input and returns a dictionary where each key is a character from the string, and the corresponding value is the count of how often that character appears in the string. Characters should be treated as cas...
def can_partition(A): total = sum(A) if total % 2 != 0: return False target = total // 2 dp = [False] * (target + 1) dp[0] = True # Base case: sum 0 is always possible for num in A: for i in range(target, num - 1, -1): if dp[i - num]: dp[i] = Tru...
simplelr_Code_Contests
[ { "content": "Question:\nWrite a function that takes an integer array as input and returns a boolean indicating whether it is possible to partition the array into two subarrays such that the sum of the elements in both subarrays is equal. You are allowed to rearrange the elements of the array.\n\nInput\nInput c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9203, "level": 1, "question": "Write a function that takes an integer array as input and returns a boolean indicating whether it is possible to partition the array into two subarrays such that the sum of the elements in both subarrays is equal. You are allowed to rearrange the eleme...
def get_element_at_index(index, lst): try: return lst[index] except IndexError: return "Index out of bounds"
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes in two parameters, an index and a list. The goal of the function is to return the element at the specified index in the list. If the index is out of bounds, handle the error gracefully and return a default value or a custom message. Additionally, incor...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9204, "level": 1, "question": "Write a Python function that takes in two parameters, an index and a list. The goal of the function is to return the element at the specified index in the list. If the index is out of bounds, handle the error gracefully and return a default value or a ...
def factorial_iterative(n): if n < 0: raise ValueError("n must be a non-negative integer") result = 1 for i in range(2, n + 1): result *= i return result
simplelr_Filter
[ { "content": "Question:\nI have a Python code that is used to calculate the factorial of a number using recursion. Can you provide me with a Python function that calculates the factorial of a number using an iterative approach instead?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9205, "level": 1, "question": "I have a Python code that is used to calculate the factorial of a number using recursion. Can you provide me with a Python function that calculates the factorial of a number using an iterative approach instead?", "split": "train" }
from typing import List def smallest_missing_positive(nums: List[int]) -> int: positives = {x for x in nums if x > 0} current = 1 while current in positives: current += 1 return current
simplelr_Algorithm
[ { "content": "Question:\n### Smallest Missing Positive Integer\n\nYou are given an unsorted array of integers. Your task is to implement a function `smallest_missing_positive` that finds and returns the smallest missing positive integer from the array.\n\n#### Function Signature:\n```python\ndef smallest_missin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9206, "level": 1, "question": "### Smallest Missing Positive Integer\n\nYou are given an unsorted array of integers. Your task is to implement a function `smallest_missing_positive` that finds and returns the smallest missing positive integer from the array.\n\n#### Function Signatu...
def binary_to_decimal(binary_string): return int(binary_string, 2)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that converts a binary number to its decimal equivalent. The function should take a string `binary_string` as input, which represents a binary number, and return the decimal equivalent as an integer.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9207, "level": 1, "question": "Create a function that converts a binary number to its decimal equivalent. The function should take a string `binary_string` as input, which represents a binary number, and return the decimal equivalent as an integer.", "split": "train" }
import pickletools import io def analyze_and_optimize_pickle(input_file: str, annotated: bool = False) -> str: with open(input_file, 'rb') as f: data = f.read() buffer = io.StringIO() pickletools.dis(data, buffer, annotate=annotated) disassembly = buffer.getvalue() optimized = pickletools...
simplelr_Docs
[ { "content": "Question:\n#### Objective:\nYou are tasked with creating a utility to analyze and optimize pickle files using Python's `pickletools` module. This exercise will help you demonstrate your understanding of working with serialized data and utilizing the `pickletools` module for advanced operations on ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9208, "level": 1, "question": "#### Objective:\nYou are tasked with creating a utility to analyze and optimize pickle files using Python's `pickletools` module. This exercise will help you demonstrate your understanding of working with serialized data and utilizing the `pickletools`...
def findNextParticipant(n, k): return (k % n) + 1
simplelr_Taco
[ { "content": "Question:\nYou are organizing a relay race where participants pass a baton in a circular track. You need to determine the next participant to receive the baton after a certain number of passes.\n\nConsider a list of $n$ participants arranged in a circular manner. Each participant is identified by ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9209, "level": 1, "question": "You are organizing a relay race where participants pass a baton in a circular track. You need to determine the next participant to receive the baton after a certain number of passes.\n\nConsider a list of $n$ participants arranged in a circular manner....
def capitalize_first_character(s): if not s: return s return s[0].upper() + s[1:]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to convert the first character of a string to uppercase.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9210, "level": 1, "question": "Write a python function to convert the first character of a string to uppercase.", "split": "train" }
def sort_people(people): return sorted(people, key=lambda x: (-x['age'], x['name']))
simplelr_Filter
[ { "content": "Question:\nGiven a list of dictionaries, where each dictionary contains a key-value pair for 'name' and 'age', write a Python function that sorts the list based on the 'age' value in descending order. If two or more individuals have the same age, they should be sorted by their 'name' in ascending ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9211, "level": 1, "question": "Given a list of dictionaries, where each dictionary contains a key-value pair for 'name' and 'age', write a Python function that sorts the list based on the 'age' value in descending order. If two or more individuals have the same age, they should be s...
def lonely_integer(arr): result = 0 for num in arr: result ^= num return result
simplelr_Filter
[ { "content": "Question:\nHelp me write a program to solve the lonely integer problem. The problem statement is as follows: \nGiven an array of integers, find the lonely integer. Every element appears twice except for one. You may not use sorting.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9212, "level": 1, "question": "Help me write a program to solve the lonely integer problem. The problem statement is as follows: \nGiven an array of integers, find the lonely integer. Every element appears twice except for one. You may not use sorting.", "split": "train" }
def filter_list_by_frequency(lst: list, max_freq: int) -> list: counts = {} result = [] for num in lst: current_count = counts.get(num, 0) if current_count < max_freq: result.append(num) counts[num] = current_count + 1 return result
simplelr_Data_Structure
[ { "content": "Question:\n### Coding Task\n\n#### Scenario\nYou have been tasked with processing a list of numbers for a data analysis preparation pipeline. The requirement is to limit the frequency of each number within the list to a specified maximum without changing the order of elements.\n\n#### Objective\nW...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9213, "level": 1, "question": "### Coding Task\n\n#### Scenario\nYou have been tasked with processing a list of numbers for a data analysis preparation pipeline. The requirement is to limit the frequency of each number within the list to a specified maximum without changing the orde...
def parse_command(command: str) -> dict: tokens = command.strip().split() if not tokens: return {} action = tokens[0].lower() if action not in ['go', 'take', 'drop', 'save', 'load']: return {} if action in ['save', 'load']: return {'action': action} else: if len(t...
simplelr_Algorithm
[ { "content": "Question:\n### Scenario\nYou are developing a text-based adventure game, and you need to implement a feature that processes player commands. The commands could involve movement directions (like \"go north\", \"go south\"), actions (like \"take item\", \"drop item\"), and system commands (like \"sa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9214, "level": 1, "question": "### Scenario\nYou are developing a text-based adventure game, and you need to implement a feature that processes player commands. The commands could involve movement directions (like \"go north\", \"go south\"), actions (like \"take item\", \"drop item...
from typing import List def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]: if matrix == [ [] ]: return [ [] ] if not matrix: return [] num_cols = len(matrix[0]) transposed = [] for j in range(num_cols): new_row = [row[j] for row in matrix] transposed.a...
simplelr_Algorithm
[ { "content": "Question:\n## Problem Statement\n\nA matrix is a rectangular array of numbers arranged in rows and columns. One common operation on matrices is transposition, which involves swapping the matrix's rows and columns.\n\n### Task\n\nWrite a Python function `transpose_matrix(matrix: List[List[int]]) ->...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9215, "level": 1, "question": "## Problem Statement\n\nA matrix is a rectangular array of numbers arranged in rows and columns. One common operation on matrices is transposition, which involves swapping the matrix's rows and columns.\n\n### Task\n\nWrite a Python function `transpose...
def potential_energy(mass: float, height: float, gravity: float = 9.80665) -> float: if mass <= 0 or height <= 0 or gravity <= 0: raise ValueError("mass, height, and gravity all need to be positive") return mass * height * gravity
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are assigned to implement a function that computes the gravitational potential energy of an object. The potential energy is determined using the mass of the object, the height of the object above ground, and the gravitational acceleration constant. Ensure your...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9216, "level": 1, "question": "### Problem Statement\nYou are assigned to implement a function that computes the gravitational potential energy of an object. The potential energy is determined using the mass of the object, the height of the object above ground, and the gravitational...
import random def generate_word_cloud(word_freq): words_list = [] for word in word_freq: freq = word_freq[word] count = min(max(freq, 1), 10) words_list.extend([word] * count) random.shuffle(words_list) return ' '.join(words_list)
simplelr_Package
[ { "content": "Question:\nWrite a Python function `generate_word_cloud` that creates a word cloud from a given list of words and their respective frequencies. The word cloud should be a simple text-based representation where words with higher frequencies appear more prominently (i.e., are repeated more times). T...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9217, "level": 1, "question": "Write a Python function `generate_word_cloud` that creates a word cloud from a given list of words and their respective frequencies. The word cloud should be a simple text-based representation where words with higher frequencies appear more prominently...
def count_lucky_triples(nums): n = len(nums) if n < 3: return 0 left = [0] * n right = [0] * n # Compute left counts: number of previous elements that divide current for j in range(n): for i in range(j): if nums[i] != 0 and nums[j] % nums[i] == 0: ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to count the number of lucky triples in a list. A lucky triple is defined as a sequence of three numbers (a[i], a[j], a[k]) where i < j < k and a[i] divides a[j] and a[j] divides a[k].\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9218, "level": 1, "question": "Write a python function to count the number of lucky triples in a list. A lucky triple is defined as a sequence of three numbers (a[i], a[j], a[k]) where i < j < k and a[i] divides a[j] and a[j] divides a[k].", "split": "train" }
def longest_subarray_sum_leq_k(nums, k): max_length = 0 current_sum = 0 start = 0 for end in range(len(nums)): current_sum += nums[end] while current_sum > k: current_sum -= nums[start] start += 1 current_length = end - start + 1 if current_length ...
simplelr_Apps
[ { "content": "Question:\nYou are given an array of integers `nums` and an integer `k`. Find the longest subarray whose sum is less than or equal to `k`. \n\nReturn the length of this subarray. If no such subarray exists, return 0.\n\nExample :\nInput:\nnums = [1, 2, 3, 4, 5]\nk = 9\nOutput: 3\nExplanation: The ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9219, "level": 1, "question": "You are given an array of integers `nums` and an integer `k`. Find the longest subarray whose sum is less than or equal to `k`. \n\nReturn the length of this subarray. If no such subarray exists, return 0.\n\nExample :\nInput:\nnums = [1, 2, 3, 4, 5]\n...
def sum_arguments(*args, **kwargs): return sum(args) + sum(kwargs.values())
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a variable number of arguments and returns the sum of those arguments. The function should support both positional and keyword arguments.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9220, "level": 1, "question": "Create a function that takes a variable number of arguments and returns the sum of those arguments. The function should support both positional and keyword arguments.", "split": "train" }
import re def is_valid_username(username: str, existing_usernames: set) -> bool: pattern = r'^[A-Za-z][A-Za-z0-9_]{3,19}$' if re.match(pattern, username): return username not in existing_usernames return False
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement:\nYou are designing a feature for a social media platform where users can register with unique usernames. To ensure username availability and prevent duplicates, you need to write a function that checks the validity of a username based on a set of preexisting usern...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9221, "level": 1, "question": "### Problem Statement:\nYou are designing a feature for a social media platform where users can register with unique usernames. To ensure username availability and prevent duplicates, you need to write a function that checks the validity of a username ...
def sum_arrays(arr1, arr2): result = [] max_length = max(len(arr1), len(arr2)) for i in range(max_length): val1 = arr1[i] if i < len(arr1) else 0 val2 = arr2[i] if i < len(arr2) else 0 result.append(val1 + val2) return result
simplelr_Prefill
[ { "content": "Question:\nWrite a function to take two arrays, and sum the corresponding elements. If the arrays are not of the same length, the function should handle it gracefully and either ignore extra elements or fill in missing elements with zero.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9222, "level": 1, "question": "Write a function to take two arrays, and sum the corresponding elements. If the arrays are not of the same length, the function should handle it gracefully and either ignore extra elements or fill in missing elements with zero.", "split": "train" }
def largest_divisible_subset(arr): zero_count = 0 non_zero = [] for num in arr: if num == 0: zero_count += 1 else: non_zero.append(num) if not non_zero: return 1 if zero_count > 0 else 0 non_zero.sort() n = len(non_zero) dp = [1] * n ...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to solve the problem of finding the largest divisible subset of an array. The function should take an array of integers as input and return the size of the largest subset where every pair of elements (x, y) in the subset satisfies x % y == 0 or y % x == 0.\nAnswer:\nLet...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9223, "level": 1, "question": "Write a function to solve the problem of finding the largest divisible subset of an array. The function should take an array of integers as input and return the size of the largest subset where every pair of elements (x, y) in the subset satisfies x % ...
def print_name(name, greeting): print(f"{greeting}, {name}!")
simplelr_Filter
[ { "content": "Question:\nWe have a function called **print_name** which takes one argument, **name**, and prints the name to the console. \n\nHere's the code:\n\n```python\ndef print_name(name):\n print(name)\n\nprint_name(\"Alice\")\n```\n \n This code will output:\n\n```\nAlice\n```\n\nNow we want to modify ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9224, "level": 1, "question": "We have a function called **print_name** which takes one argument, **name**, and prints the name to the console. \n\nHere's the code:\n\n```python\ndef print_name(name):\n print(name)\n\nprint_name(\"Alice\")\n```\n \n This code will output:\n\n```\nA...
def sum_even_position_digits(s): total = 0 for position, char in enumerate(s, start=1): if position % 2 == 0: total += int(char) return total
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string of digits as input and returns the sum of the digits at even positions in the string. Positioning starts from 1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9225, "level": 1, "question": "Create a function that takes a string of digits as input and returns the sum of the digits at even positions in the string. Positioning starts from 1.", "split": "train" }
def max_subarray_sum(arr): if not arr: return 0 max_current = max_so_far = arr[0] for num in arr[1:]: max_current = max(num, max_current + num) if max_current > max_so_far: max_so_far = max_current return max_so_far
simplelr_Prefill
[ { "content": "Question:\nCreate a function that accepts an array of integers and returns the maximum sum of a contiguous subarray within the array. This is known as Kadane's Algorithm. Can you write a Python function to implement this?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9226, "level": 1, "question": "Create a function that accepts an array of integers and returns the maximum sum of a contiguous subarray within the array. This is known as Kadane's Algorithm. Can you write a Python function to implement this?", "split": "train" }
def first_occurrence(arr, target): low = 0 high = len(arr) - 1 result = -1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: result = mid high = mid - 1 elif arr[mid] < target: low = mid + 1 else: high = mid ...
simplelr_Filter
[ { "content": "Question:\n# problem - Given a sorted array of integers, write a python function to find the first occurence of an element using binary search algorithm.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9227, "level": 1, "question": "# problem - Given a sorted array of integers, write a python function to find the first occurence of an element using binary search algorithm.", "split": "train" }
def most_frequent_element(lst): frequency = {} for item in lst: frequency[item] = frequency.get(item, 0) + 1 max_freq = max(frequency.values()) most_freq_elements = [element for element, freq in frequency.items() if freq == max_freq] # Return the smallest element among the most fre...
simplelr_Filter
[ { "content": "Question:\nI have an integer list and I want to find the most frequent element in the list. If there are multiple elements with the same highest frequency, I want to return the smallest of them.\n\nHere is my code, but it does not work:\n```python\ndef most_frequent_element(lst):\n frequency = ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9228, "level": 1, "question": "I have an integer list and I want to find the most frequent element in the list. If there are multiple elements with the same highest frequency, I want to return the smallest of them.\n\nHere is my code, but it does not work:\n```python\ndef most_frequ...
import tempfile def process_temp_files_and_dirs(data: str) -> str: with tempfile.TemporaryDirectory() as temp_dir: # Create a temporary file using TemporaryFile with tempfile.TemporaryFile() as temp_file: temp_file.write(data.encode('utf-8')) temp_file.seek(0) co...
simplelr_Docs
[ { "content": "Question:\n**Coding Assessment Question:**\n\n### Context:\nYou are working on a project where you need to handle temporary files and directories effectively to ensure secure and optimal temporary storage. You are required to use the `tempfile` module in Python to achieve this.\n\n### Task:\nWrite...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9229, "level": 1, "question": "**Coding Assessment Question:**\n\n### Context:\nYou are working on a project where you need to handle temporary files and directories effectively to ensure secure and optimal temporary storage. You are required to use the `tempfile` module in Python t...
import re def count_emails(text): pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" emails = re.findall(pattern, text) return len(emails)
simplelr_Filter
[ { "content": "Question:\nCan you provide a simple example of a Python function using regular expressions to find and count the number of email addresses in a given string?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9230, "level": 1, "question": "Can you provide a simple example of a Python function using regular expressions to find and count the number of email addresses in a given string?", "split": "train" }
def pathArea(L, W, P): total_area = (L + 2 * P) * (W + 2 * P) original_area = L * W return total_area - original_area
simplelr_Taco
[ { "content": "Question:\nA Farmer owns a rectangular field of length L meters and width W meters. He wants to create a path of uniform width P (in meters) around the perimeter of the field so that he can walk around the entire field without stepping on the crops. You need to calculate the area of the path.\n\nY...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9231, "level": 1, "question": "A Farmer owns a rectangular field of length L meters and width W meters. He wants to create a path of uniform width P (in meters) around the perimeter of the field so that he can walk around the entire field without stepping on the crops. You need to c...
from typing import List def find_words(text: str, words: List[str]) -> List[bool]: text_words = text.split() text_set = set(text_words) return [word in text_set for word in words]
simplelr_Codeforces
[ { "content": "Question:\nAlice and Bob are working on a new coding project together. They often need to search through large files of text to find whether certain words exist within those files. To make this process more efficient, they decide to write a program that can quickly determine if a list of words exi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9232, "level": 1, "question": "Alice and Bob are working on a new coding project together. They often need to search through large files of text to find whether certain words exist within those files. To make this process more efficient, they decide to write a program that can quick...
from collections import Counter def is_special_string(s): vowels = {'a', 'e', 'i', 'o', 'u'} counts = Counter(s) for vowel in vowels: if counts.get(vowel, 0) % 2 != 0: return False return True
simplelr_Taco
[ { "content": "Question:\n## **Instructions**\n\nYou are working on a project that requires you to analyze strings for specific patterns. The task is to write a function that determines if a given string is a \"special\" string. A \"special\" string is defined as a string where every vowel (a, e, i, o, u) appear...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9233, "level": 1, "question": "## **Instructions**\n\nYou are working on a project that requires you to analyze strings for specific patterns. The task is to write a function that determines if a given string is a \"special\" string. A \"special\" string is defined as a string where...
def count_swaps_to_sort(heights): sorted_heights = sorted(heights) count = 0 for i in range(len(heights)): if heights[i] != sorted_heights[i]: count += 1 return count
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `heights` representing the heights of a group of students standing in a line, return the minimum number of indices where the heights need to be swapped to make the entire array sorted in non-decreasing order. Note that each student must maintain their original pos...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9234, "level": 1, "question": "Given an integer array `heights` representing the heights of a group of students standing in a line, return the minimum number of indices where the heights need to be swapped to make the entire array sorted in non-decreasing order. Note that each stude...
def zero_matrix(matrix: list[list[int]]) -> None: if not matrix or not matrix[0]: return m = len(matrix) n = len(matrix[0]) zero_rows = set() zero_cols = set() # First pass to find all zero rows and columns for i in range(m): for j in range(n): if m...
simplelr_Algorithm
[ { "content": "Question:\n### Matrix Zeroing Function\n\nDevelop a function that modifies a given MxN matrix based on the rule that if an element is 0, its entire row and column are set to 0.\n\n### Objective\nImplement a function that takes an MxN matrix and updates it in place such that if an element is 0 in t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9235, "level": 1, "question": "### Matrix Zeroing Function\n\nDevelop a function that modifies a given MxN matrix based on the rule that if an element is 0, its entire row and column are set to 0.\n\n### Objective\nImplement a function that takes an MxN matrix and updates it in plac...
def find_pattern(word: str, text: str) -> int: len_word = len(word) len_text = len(text) if len_word == 0: return -1 if len_word > len_text: return -1 base = 256 mod = 10**9 + 7 base_pow_m_minus_1 = pow(base, len_word - 1, mod) # Compute the hash of the pattern ...
simplelr_Data_Structure
[ { "content": "Question:\n**Problem Statement**:\n\nYou are given a text and a word (pattern) that you need to locate within the text. Write a function `find_pattern(word: str, text: str) -> int` that implements the Rabin Karp algorithm to find the starting index of the first occurrence of the word in the text. ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9236, "level": 1, "question": "**Problem Statement**:\n\nYou are given a text and a word (pattern) that you need to locate within the text. Write a function `find_pattern(word: str, text: str) -> int` that implements the Rabin Karp algorithm to find the starting index of the first o...
def reverse_list_in_place(lst): for i in range(len(lst) // 2): lst[i], lst[len(lst) - 1 - i] = lst[len(lst) - 1 - i], lst[i] return lst
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to reverse the order of the elements in a list in place. The function should also handle the case where the list is empty or contains only one element.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9237, "level": 1, "question": "Write a python function to reverse the order of the elements in a list in place. The function should also handle the case where the list is empty or contains only one element.", "split": "train" }
def first_occurrences(lst): result = {} for index, value in enumerate(lst): if value not in result: result[value] = index return result
simplelr_Evol
[ { "content": "Question:\nWrite a Python function that takes a list of integers and returns a dictionary, where the keys are the integers from the list and the values are the positions of their first occurrence in the list. The function should handle scenarios with negative integers and varying list lengths, inc...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9238, "level": 1, "question": "Write a Python function that takes a list of integers and returns a dictionary, where the keys are the integers from the list and the values are the positions of their first occurrence in the list. The function should handle scenarios with negative int...
import numpy as np import itertools def max_pairwise_dot_product(words, embeddings): """ Find the permutation of words that has the maximum possible sum of pairwise dot products. Args: words (list of str): A list of words. embeddings (dict): A dictionary where keys are words and values are...
simplelr_Filter
[ { "content": "Question:\nI have written a code that generates all permutations of a given set of words and then finds the permutation that has the maximum possible sum of pairwise dot products. You can find the code below:\n\n```python\nimport numpy as np\nfrom scipy import spatial\nimport itertools\n\ndef max_...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9239, "level": 1, "question": "I have written a code that generates all permutations of a given set of words and then finds the permutation that has the maximum possible sum of pairwise dot products. You can find the code below:\n\n```python\nimport numpy as np\nfrom scipy import sp...
import bisect def length_of_LIS(nums): tails = [] for num in nums: idx = bisect.bisect_left(tails, num) if idx == len(tails): tails.append(num) else: tails[idx] = num return len(tails)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an array of integers and returns the length of the longest strictly increasing subsequence (LIS). A strictly increasing subsequence is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining e...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9240, "level": 1, "question": "Create a function that takes an array of integers and returns the length of the longest strictly increasing subsequence (LIS). A strictly increasing subsequence is a sequence that can be derived from the array by deleting some or no elements without ch...
def check_permutation_substring(s1: str, s2: str) -> bool: len_s1 = len(s1) len_s2 = len(s2) if len_s1 > len_s2: return False # Initialize the count arrays for s1 and the first window of s2 count_s1 = [0] * 26 for c in s1: count_s1[ord(c) - ord('a')] += 1 count...
simplelr_Evol
[ { "content": "Question:\nImplement a function to determine whether a given string contains any permutation of another given string. For instance, given strings `s1` and `s2`, the function should return `true` if any permutation of `s1` is a substring of `s2`, and `false` otherwise.\n\n### Function Signature\n``...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9241, "level": 1, "question": "Implement a function to determine whether a given string contains any permutation of another given string. For instance, given strings `s1` and `s2`, the function should return `true` if any permutation of `s1` is a substring of `s2`, and `false` other...
def count_characters(s): counts = {} for char in s: if char in counts: counts[char] += 1 else: counts[char] = 1 return counts
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes a string as an input and returns a dictionary where each key is a unique character from the string, and the value is the number of occurrences of that character. The function should be case-sensitive and consider spaces and punctuation as valid characters.\n\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9242, "level": 1, "question": "Write a function that takes a string as an input and returns a dictionary where each key is a unique character from the string, and the value is the number of occurrences of that character. The function should be case-sensitive and consider spaces and ...
def max_apples(grid): if not grid or not grid[0]: return 0 m = len(grid) n = len(grid[0]) dp = [[0 for _ in range(n)] for _ in range(m)] dp[0][0] = grid[0][0] for j in range(1, n): dp[0][j] = dp[0][j-1] + grid[0][j] for i in range(1, m): dp[i][0] = dp[i...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an `m x n` integer matrix `grid` where `grid[i][j]` represents the number of apples in the cell located at row `i` and column `j`. A robot wants to collect as many apples as possible by starting at the top-left corner of the matrix (cell `(0, 0)`) and moving to the bottom-...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9243, "level": 1, "question": "You are given an `m x n` integer matrix `grid` where `grid[i][j]` represents the number of apples in the cell located at row `i` and column `j`. A robot wants to collect as many apples as possible by starting at the top-left corner of the matrix (cell ...
def find_intersection(a, b, c, d, e, f): determinant = a * e - b * d if determinant == 0: return None else: x = (c * e - b * f) / determinant y = (a * f - c * d) / determinant return (x, y)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the intersection point of two lines given by the equations ax + by = c and dx + ey = f. The function should return the intersection point as a tuple (x, y). If the lines do not intersect, the function should return None.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9244, "level": 1, "question": "Write a function to find the intersection point of two lines given by the equations ax + by = c and dx + ey = f. The function should return the intersection point as a tuple (x, y). If the lines do not intersect, the function should return None.", "s...
def temperature_trend(temperatures): stack = [] result = [0] * len(temperatures) for i in range(len(temperatures) - 1, -1, -1): while stack and temperatures[stack[-1]] <= temperatures[i]: stack.pop() if stack: result[i] = stack[-1] - i else: result...
simplelr_Apps
[ { "content": "Question:\nYou are given a list of integers representing daily temperatures. Implement a function `temperature_trend` that returns a list of the same length where each element in the new list represents the number of days you would have to wait until a warmer temperature. If there is no future day...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9245, "level": 1, "question": "You are given a list of integers representing daily temperatures. Implement a function `temperature_trend` that returns a list of the same length where each element in the new list represents the number of days you would have to wait until a warmer tem...
def smallest_subarray_with_given_sum(arr: list[int], x: int) -> int: prefix_sum = [0] for num in arr: prefix_sum.append(prefix_sum[-1] + num) min_length = float('inf') deque = [0] # This deque will store indices of prefix_sum in increasing order for j in range(1, len(prefix_sum)):...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Problem Statement\nYou are given an array of integers and an integer `x`. Implement a function that finds the length of the smallest subarray with a sum greater than or equal to `x`. If no such subarray exists, return 0.\n\n#### Function Signature\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9246, "level": 1, "question": "### Coding Assessment Question\n\n#### Problem Statement\nYou are given an array of integers and an integer `x`. Implement a function that finds the length of the smallest subarray with a sum greater than or equal to `x`. If no such subarray exists, re...
def min_edit_distance(word1: str, word2: str) -> int: m = len(word1) n = len(word2) # Create a DP table with (m+1) rows and (n+1) columns dp = [[0] * (n + 1) for _ in range(m + 1)] # Initialize the first row and column for i in range(m + 1): dp[i][0] = i for j in range(n + 1): ...
simplelr_Algorithm
[ { "content": "Question:\n### Question\n\nYou need to implement a function to determine the minimum edit distance between two strings. The edit distance is defined as the minimum number of operations required to convert one string into the other. The allowed operations are insertion, deletion, or substitution of...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9247, "level": 1, "question": "### Question\n\nYou need to implement a function to determine the minimum edit distance between two strings. The edit distance is defined as the minimum number of operations required to convert one string into the other. The allowed operations are inse...
from collections import Counter def can_prepare_dish(ingredients_needed, pantry_stock): needed = Counter(ingredients_needed) stock = Counter(pantry_stock) for ingredient, count in needed.items(): if stock.get(ingredient, 0) < count: return False return True
simplelr_Code_Contests
[ { "content": "Question:\nA chef in a renowned restaurant has a list of ingredients needed to prepare different dishes. Each ingredient is represented by an uppercase letter from 'A' to 'Z'. Some ingredients are needed multiple times for the same dish. The chef has access to a stock of ingredients in the pantry,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9248, "level": 1, "question": "A chef in a renowned restaurant has a list of ingredients needed to prepare different dishes. Each ingredient is represented by an uppercase letter from 'A' to 'Z'. Some ingredients are needed multiple times for the same dish. The chef has access to a ...
def longest_substring_k_distinct(s: str, k: int) -> str: if k == 0 or len(s) == 0: return "" char_count = {} max_length = 0 start = 0 left = 0 for right in range(len(s)): char = s[right] if char in char_count: char_count[char] += 1 else: ...
simplelr_Apps
[ { "content": "Question:\n## Find Longest Substring with K Distinct Characters\n\nYou've been asked to analyze data streams and devise a method to detect patterns within a specified range. Specifically, you'd like to identify the longest contiguous substring that contains exactly `k` distinct characters. This mi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9249, "level": 1, "question": "## Find Longest Substring with K Distinct Characters\n\nYou've been asked to analyze data streams and devise a method to detect patterns within a specified range. Specifically, you'd like to identify the longest contiguous substring that contains exact...
def sum_and_count(numbers): return sum(numbers), len(numbers)
simplelr_Filter
[ { "content": "Question:\nCreate a Python function to sum all numbers in a list. The function should also return the count of numbers in the list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9250, "level": 1, "question": "Create a Python function to sum all numbers in a list. The function should also return the count of numbers in the list.", "split": "train" }
def reverse_words(s: str) -> str: tokens = [] current_word = [] current_space = [] for c in s: if c == ' ': if current_word: tokens.append(''.join(current_word)) current_word = [] current_space.append(c) else: if current...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are required to implement a Python function that reverses the letters of each word in a given string, but maintains the order of words and the original whitespace characters.\n\n### Input\n- A string `s` containing space-separated words, where 1 <= len(s) <=...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9251, "level": 1, "question": "### Problem Statement\n\nYou are required to implement a Python function that reverses the letters of each word in a given string, but maintains the order of words and the original whitespace characters.\n\n### Input\n- A string `s` containing space-se...
from typing import List def generate_pascals_triangle(N: int) -> List[List[int]]: if N == 0: return [] triangle = [[1]] for i in range(1, N): new_row = [1] prev_row = triangle[i - 1] for j in range(1, i): new_row.append(prev_row[j - 1] + prev_row[j]) new_...
simplelr_Codeforces
[ { "content": "Question:\nWrite a function to generate a Pascal's Triangle of a given number of rows $$$N$$$ ($$$1 \\le N \\le 20$$$). Pascal's Triangle is a triangular array of the binomial coefficients. Each row is constructed by adding the number above and to the left with the number above and to the right.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9252, "level": 1, "question": "Write a function to generate a Pascal's Triangle of a given number of rows $$$N$$$ ($$$1 \\le N \\le 20$$$). Pascal's Triangle is a triangular array of the binomial coefficients. Each row is constructed by adding the number above and to the left with t...
def process_strings(strings): result = {} for s in strings: if len(s) % 2 == 0: processed = s[::2] else: processed = s[1::2] result[s] = processed return result
simplelr_Filter
[ { "content": "Question:\nCreate a sequential plan and code for a function that receives a list of strings as an input, iteratively evaluates each, determine if they have a length that is even or odd, combines characters at even or odd indexes based on that determination, and finally assembles a dictionary that ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9253, "level": 1, "question": "Create a sequential plan and code for a function that receives a list of strings as an input, iteratively evaluates each, determine if they have a length that is even or odd, combines characters at even or odd indexes based on that determination, and f...
def count_ones(n: int) -> int: count = 0 while n: n &= n - 1 count += 1 return count
simplelr_Data_Structure
[ { "content": "Question:\n### Counting '1' Bits in a Binary Representation\n\n**Scenario**:\nYou are working with a team that is optimizing a network security tool. This tool requires frequent analysis of binary representations of IP addresses to count the number of '1' bits. Your task is to write a function tha...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9254, "level": 1, "question": "### Counting '1' Bits in a Binary Representation\n\n**Scenario**:\nYou are working with a team that is optimizing a network security tool. This tool requires frequent analysis of binary representations of IP addresses to count the number of '1' bits. Y...
def iterative_binomial_coefficient(n, k): if k == 0 or k == n: return 1 if k > n - k: k = n - k result = 1 for i in range(1, k + 1): numerator = (n - k + i) result = result * numerator // i return result
simplelr_Data_Structure
[ { "content": "Question:\n### Question:\nImplement an iterative version of the binomial coefficient calculation. Your task is to write a function that calculates and returns the binomial coefficient C(n, k) using an iterative approach to avoid the issues caused by deep recursion.\n\n#### Requirements:\n- **Funct...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9255, "level": 1, "question": "### Question:\nImplement an iterative version of the binomial coefficient calculation. Your task is to write a function that calculates and returns the binomial coefficient C(n, k) using an iterative approach to avoid the issues caused by deep recursio...
def word_pattern(pattern: str, str: str) -> bool: words = str.split() if len(words) != len(pattern): return False # Normalize the pattern pattern_sequence = [] mapping_p = {} counter_p = 0 for c in pattern: if c not in mapping_p: mapping_p[c] = counter_p ...
simplelr_Data_Structure
[ { "content": "Question:\n### Question: Verify Word Pattern Matching\n\n#### Description:\nYou are given a pattern and a string. Your task is to determine if the string follows the same pattern. A string follows the pattern if, for each distinct character in the pattern, there is exactly one unique word in the s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9256, "level": 1, "question": "### Question: Verify Word Pattern Matching\n\n#### Description:\nYou are given a pattern and a string. Your task is to determine if the string follows the same pattern. A string follows the pattern if, for each distinct character in the pattern, there ...
def is_palindrome(word): left = 0 right = len(word) - 1 while left < right: if word[left] != word[right]: return False left += 1 right -= 1 return True
simplelr_Filter
[ { "content": "Question:\nGiven the code, write a function that determines if a word is a palindrome or not. However, you're not allowed to use any built-in string reverse functions, string comparison functions, or arrays. You must solve the problem using only iterative control structures and basic string manipu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9257, "level": 1, "question": "Given the code, write a function that determines if a word is a palindrome or not. However, you're not allowed to use any built-in string reverse functions, string comparison functions, or arrays. You must solve the problem using only iterative control...
def largest_rectangle_area(heights): max_area = 0 stack = [] n = len(heights) for i in range(n): while stack and heights[i] < heights[stack[-1]]: k = stack.pop() left = stack[-1] if stack else -1 width = i - left - 1 area = heights[k] * width ...
simplelr_Taco
[ { "content": "Question:\nYou are given a list of integers representing heights of buildings standing in a row. The goal is to determine the maximum area of a rectangle that can be formed by any set of consecutive buildings where the rectangle's height is defined by the shortest building in that set.\n\nYour tas...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9258, "level": 1, "question": "You are given a list of integers representing heights of buildings standing in a row. The goal is to determine the maximum area of a rectangle that can be formed by any set of consecutive buildings where the rectangle's height is defined by the shortes...
def largest_product_of_three(nums): if len(nums) < 3: return None nums_sorted = sorted(nums) product1 = nums_sorted[-1] * nums_sorted[-2] * nums_sorted[-3] product2 = nums_sorted[0] * nums_sorted[1] * nums_sorted[-1] return max(product1, product2)
simplelr_Package
[ { "content": "Question:\nYou are tasked to write a function that determines the largest product of any three integers in a list of integers. This problem tests your ability to correctly identify and calculate maximum/minimum values in a list.\n\nWrite a function named `largest_product_of_three` with the followi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9259, "level": 1, "question": "You are tasked to write a function that determines the largest product of any three integers in a list of integers. This problem tests your ability to correctly identify and calculate maximum/minimum values in a list.\n\nWrite a function named `largest...
def smallestProductNumber(N): if N == 1: return 1 factors = [] for d in range(9, 1, -1): while N % d == 0: factors.append(d) N = N // d if N != 1: return -1 factors.sort() return int(''.join(map(str, factors)))
simplelr_Taco
[ { "content": "Question:\nGiven a positive integer N, your task is to find the smallest positive integer M such that the product of the digits of M is equal to N. If such an M does not exist, return -1. \n\nExample 1:\nInput: N = 18\nOutput: 29\nExplanation: 2 * 9 = 18, which is the desired product.\n\nExample 2...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9260, "level": 1, "question": "Given a positive integer N, your task is to find the smallest positive integer M such that the product of the digits of M is equal to N. If such an M does not exist, return -1. \n\nExample 1:\nInput: N = 18\nOutput: 29\nExplanation: 2 * 9 = 18, which i...
def sum_matrix(matrix): sum_total = 0 for row in matrix: for num in row: sum_total += num return sum_total # Example usage: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(sum_matrix(matrix)) # Output: 45
simplelr_Filter
[ { "content": "Question:\nWrite a program that will find the sum of all elements in a given 2D array (matrix). The program should be able to handle matrices of any size.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9261, "level": 1, "question": "Write a program that will find the sum of all elements in a given 2D array (matrix). The program should be able to handle matrices of any size.", "split": "train" }
from collections import Counter def find_duplicates(nums): counts = Counter(nums) return [num for num, cnt in counts.items() if cnt > 1]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers and returns a new list containing only the integers that appear more than once.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9262, "level": 1, "question": "Create a function that takes a list of integers and returns a new list containing only the integers that appear more than once.", "split": "train" }
def word_pattern(pattern: str, string: str) -> bool: words = string.split() if len(words) != len(pattern): return False p_map = {} w_map = {} for p_char, word in zip(pattern, words): if p_char in p_map: if p_map[p_char] != word: return False else...
simplelr_Data_Structure
[ { "content": "Question:\n**Question: Word Pattern Matching**\n\nGiven a pattern and a string 's', determine if 's' follows the same pattern as the given pattern string. Every character in the pattern should map to a word in the string, and vice versa, ensuring a one-to-one relationship.\n\n### Function Signatur...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9263, "level": 1, "question": "**Question: Word Pattern Matching**\n\nGiven a pattern and a string 's', determine if 's' follows the same pattern as the given pattern string. Every character in the pattern should map to a word in the string, and vice versa, ensuring a one-to-one rel...
def find_majority_element(arr): if not arr: # Empty array case return None if len(arr) == 1: # Single element case return arr[0] # Find the candidate using Boyer-Moore algorithm count = 0 candidate = None for num in arr: if count == 0: candidate = num ...
simplelr_Apps
[ { "content": "Question:\nWrite a function `find_majority_element` that takes in an array of integers and returns the majority element. The majority element is the element that appears more than half the time in the array. If no such element exists, return `None`. Implement the solution with O(n) time complexity...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9264, "level": 1, "question": "Write a function `find_majority_element` that takes in an array of integers and returns the majority element. The majority element is the element that appears more than half the time in the array. If no such element exists, return `None`. Implement the...
def sort_descending(arr): return sorted(arr, reverse=True)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in an integer array and returns a new array with the elements sorted in descending order. The function should handle edge cases such as empty arrays and arrays with duplicate elements.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9265, "level": 1, "question": "Create a function that takes in an integer array and returns a new array with the elements sorted in descending order. The function should handle edge cases such as empty arrays and arrays with duplicate elements.", "split": "train" }
def is_palindrome(s: str) -> bool: s_clean = ''.join([c.lower() for c in s if c.isalnum()]) return s_clean == s_clean[::-1]
simplelr_Evol
[ { "content": "Question:\nImplement a function to check if a given string is a palindrome, considering only alphanumeric characters and ignoring cases. A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward. Examples of palindromes are \"A man, a plan, a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9266, "level": 1, "question": "Implement a function to check if a given string is a palindrome, considering only alphanumeric characters and ignoring cases. A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward. Examples of...
def most_frequent_elements(input_list: list) -> list: if not input_list: return [] freq_dict = {} for num in input_list: if num in freq_dict: freq_dict[num] += 1 else: freq_dict[num] = 1 max_freq = max(freq_dict.values()) result = [key for ke...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Description\n\nYou are given a list of integers and your task is to find the element in the list that appears the most frequently. If there is a tie (i.e., two or more elements appear the same maximum number of times), return all such elements as a list, sorted in ascending ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9267, "level": 1, "question": "### Problem Description\n\nYou are given a list of integers and your task is to find the element in the list that appears the most frequently. If there is a tie (i.e., two or more elements appear the same maximum number of times), return all such eleme...
def minPathCost(moveCost): m = len(moveCost) if m == 0: return 0 n = len(moveCost[0]) dp = [[0 for _ in range(n)] for _ in range(m)] dp[0][0] = moveCost[0][0] for i in range(m): for j in range(n): if i == 0 and j == 0: continue if i ==...
simplelr_Leetcode
[ { "content": "Question:\nA robot is located at the top-left corner of an `m x n` grid (`grid[0][0]`). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (`grid[m-1][n-1]`). The robot's movement is dictated by a 2D integer array `mo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9268, "level": 1, "question": "A robot is located at the top-left corner of an `m x n` grid (`grid[0][0]`). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (`grid[m-1][n-1]`). The robot's movement is...
def can_form_rotated_palindrome(s): freq = {} for c in s: freq[c] = freq.get(c, 0) + 1 odd_count = 0 for count in freq.values(): if count % 2 != 0: odd_count += 1 if len(s) % 2 == 0: return odd_count == 0 else: return odd_count == 1
simplelr_Apps
[ { "content": "Question:\n### Rotated Palindromes\n\n# Overview\nA palindrome is a string that reads the same forward and backward. For instance, \"level\", \"radar\", and \"madam\" are palindromes. Your task in this problem is a bit more challenging: you need to determine whether a string can be rearranged to f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9269, "level": 1, "question": "### Rotated Palindromes\n\n# Overview\nA palindrome is a string that reads the same forward and backward. For instance, \"level\", \"radar\", and \"madam\" are palindromes. Your task in this problem is a bit more challenging: you need to determine whet...
def remove_inactive_users(groups, inactive_users): inactive_set = set(inactive_users) return [[user for user in group if user not in inactive_set] for group in groups]
simplelr_Code_Contests
[ { "content": "Question:\nYou are tasked with developing a feature for a chat application that manages group conversations. Each group conversation has a unique ID, and a user can belong to multiple groups. To efficiently manage and update the groups, you need to periodically remove users who are inactive for a ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9270, "level": 1, "question": "You are tasked with developing a feature for a chat application that manages group conversations. Each group conversation has a unique ID, and a user can belong to multiple groups. To efficiently manage and update the groups, you need to periodically r...
def reverse_words(s): words = s.split() words.reverse() return ' '.join(words)
simplelr_Filter
[ { "content": "Question:\nThis code defines a function called `reverse_words` that takes a string as input and returns a string with the words in reverse order.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9271, "level": 1, "question": "This code defines a function called `reverse_words` that takes a string as input and returns a string with the words in reverse order.", "split": "train" }
def binary_search(array, target): low = 0 high = len(array) - 1 while low <= high: mid = (low + high) // 2 if array[mid] == target: return mid elif target < array[mid]: high = mid - 1 else: low = mid + 1 return -1
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a sorted array and a target value, and returns the index of the target value in the array. If the target is not found, return -1. The function should perform this search using the Binary Search algorithm.\nAnswer:\nLet's think step by step.\n", "role": "...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9272, "level": 1, "question": "Create a function that takes a sorted array and a target value, and returns the index of the target value in the array. If the target is not found, return -1. The function should perform this search using the Binary Search algorithm.", "split": "trai...
import urllib.request import ssl from urllib.error import HTTPError, URLError from typing import Optional, Tuple def fetch_url(url: str, data: Optional[bytes] = None, is_post: bool = False, use_proxy: bool = False) -> Tuple[int, str]: # Determine the HTTP method and prepare data if is_post: method = 'P...
simplelr_Docs
[ { "content": "Question:\n### Advanced URL Handling with urllib.request\n\nIn this assessment, you will implement a URL fetcher using Python's `urllib.request` module. The URL fetcher should demonstrate your understanding of both basic and advanced functionality provided by this module, including SSL contexts, p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9273, "level": 1, "question": "### Advanced URL Handling with urllib.request\n\nIn this assessment, you will implement a URL fetcher using Python's `urllib.request` module. The URL fetcher should demonstrate your understanding of both basic and advanced functionality provided by thi...
from datetime import datetime, timedelta def add_days(date_str, days): date = datetime.strptime(date_str, '%Y-%m-%d').date() new_date = date + timedelta(days=days) return new_date.strftime('%Y-%m-%d') # Example usage: result_str = add_days('2022-01-01', 10) print(result_str) # Outputs: 2022-01-11
simplelr_Filter
[ { "content": "Question:\nI have a variable that holds a date with date part only, without any time. (e.g., `2022-01-01`). I want to add an arbitrary number of days to it. I can add days as follows:\n\n```python\nfrom datetime import datetime, timedelta\n\nsome_date = datetime.strptime('2022-01-01', '%Y-%m-%d')....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9274, "level": 1, "question": "I have a variable that holds a date with date part only, without any time. (e.g., `2022-01-01`). I want to add an arbitrary number of days to it. I can add days as follows:\n\n```python\nfrom datetime import datetime, timedelta\n\nsome_date = datetime....
import json def parse_json(json_obj): data = json.loads(json_obj) return [value for obj in data['listOfObjects'] for value in obj['values']] # Test the function json_obj = ''' { "listOfObjects": [ { "id": 1, "values": ["string1", "string2", "string3"] }, { ...
simplelr_Filter
[ { "content": "Question:\nI have a JSON object that contains a list of objects. Each object has a nested list of strings. I'm trying to write a function that will parse this JSON and extract all the strings from the nested lists. The function should return a list of all the strings in the order they appear in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9275, "level": 1, "question": "I have a JSON object that contains a list of objects. Each object has a nested list of strings. I'm trying to write a function that will parse this JSON and extract all the strings from the nested lists. The function should return a list of all the ...
def split_and_insert(s, n): s_str = str(s) digits = [] if s_str[0] == '-': digits.append(int(s_str[0] + s_str[1])) for c in s_str[2:]: digits.append(int(c)) else: digits = [int(c) for c in s_str] result = [] for i in range(len(digits)): result.app...
simplelr_Filter
[ { "content": "Question:\nGiven two integers s and n, Write a python program to split each digit of integer s, and put n in between these separated digits, then concate and construct a new integer list\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9276, "level": 1, "question": "Given two integers s and n, Write a python program to split each digit of integer s, and put n in between these separated digits, then concate and construct a new integer list", "split": "train" }
def smallest_unique_index(lst): if not lst: return -1 first_occurrence = {} unique_candidates = set() for idx, num in enumerate(lst): if num not in first_occurrence: first_occurrence[num] = idx unique_candidates.add(num) else: if num in unique_...
simplelr_Filter
[ { "content": "Question:\nGiven a list of integers, write a Python function to find the index of the smallest unique integer in the list. If there is no unique integer (i.e., every integer appears more than once), return -1. Assume that the list can contain up to 10,000,000 elements and the elements can be any 3...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9277, "level": 1, "question": "Given a list of integers, write a Python function to find the index of the smallest unique integer in the list. If there is no unique integer (i.e., every integer appears more than once), return -1. Assume that the list can contain up to 10,000,000 ele...
import matplotlib.pyplot as plt import numpy as np def plot_line(m, b): # Generate x values x = np.linspace(-10, 10, 400) # Calculate corresponding y values y = m * x + b # Create the plot plt.figure(figsize=(8,6)) # Optional: Set the figure size plt.plot(x, y, label=f'y = {m}x +...
simplelr_Filter
[ { "content": "Question:\nHere's a simple slope-intercept form of a line y = mx + b. Given an input of m (slope) and b (y-intercept), write a code to generate a line on a matplotlib plot.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9278, "level": 1, "question": "Here's a simple slope-intercept form of a line y = mx + b. Given an input of m (slope) and b (y-intercept), write a code to generate a line on a matplotlib plot.", "split": "train" }
def findTriangular(n): return n * (n + 1) // 2
simplelr_Apps
[ { "content": "Question:\nGiven a positive integer n, compute the nth triangular number. The nth triangular number is defined as the sum of the first n natural numbers and can be represented by the formula:\n> T(n) = n * (n + 1) / 2\n\nWrite a function `findTriangular` that takes an integer `n` as input and retu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9279, "level": 1, "question": "Given a positive integer n, compute the nth triangular number. The nth triangular number is defined as the sum of the first n natural numbers and can be represented by the formula:\n> T(n) = n * (n + 1) / 2\n\nWrite a function `findTriangular` that tak...
def min_operations_to_make_identical(arr1, arr2): return sum(abs(a - b) for a, b in zip(arr1, arr2))
simplelr_Leetcode
[ { "content": "Question:\nYou are given two integer arrays `arr1` and `arr2` of equal length. Each element in `arr1` can be incremented or decremented by 1 in one operation. Determine the minimum number of operations required to make the two arrays identical.\nAnswer:\nLet's think step by step.\n", "role": "...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9280, "level": 1, "question": "You are given two integer arrays `arr1` and `arr2` of equal length. Each element in `arr1` can be incremented or decremented by 1 in one operation. Determine the minimum number of operations required to make the two arrays identical.", "split": "trai...
from typing import List def reshape_vector(vector: List[int], rows: int, cols: int) -> List[List[int]]: if len(vector) != rows * cols: return [] matrix = [] for i in range(rows): start = i * cols end = start + cols matrix.append(vector[start:end]) return matrix
simplelr_Algorithm
[ { "content": "Question:\n### Tensor Manipulation Assessment\n\nYou are required to design a function that reshapes a given one-dimensional list (vector) into a two-dimensional matrix of integers, following matrix dimensions specified by the user. If the reshaping operation cannot be performed (i.e., the number ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9281, "level": 1, "question": "### Tensor Manipulation Assessment\n\nYou are required to design a function that reshapes a given one-dimensional list (vector) into a two-dimensional matrix of integers, following matrix dimensions specified by the user. If the reshaping operation can...
def find_min_index(nums1, nums2): s = set(nums2) min_val = float('inf') min_index = -1 for i, num in enumerate(nums1): if num in s: if num < min_val: min_val = num min_index = i return min_index if min_index != -1 else -1
simplelr_Leetcode
[ { "content": "Question:\nYou are given two arrays, `nums1` and `nums2`, each consisting of unique integers. Your task is to find the smallest index `i` in `nums1` such that `nums1[i]` is present in `nums2`. If there are multiple answers, return the one with the smallest value of `nums1[i]`. If no such index exi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9282, "level": 1, "question": "You are given two arrays, `nums1` and `nums2`, each consisting of unique integers. Your task is to find the smallest index `i` in `nums1` such that `nums1[i]` is present in `nums2`. If there are multiple answers, return the one with the smallest value ...
def three_sum(nums): nums.sort() res = [] for i in range(len(nums) - 2): # Skip duplicate for i if i > 0 and nums[i] == nums[i - 1]: continue left = i + 1 right = len(nums) - 1 while left < right: current_sum = nums[i] + nums[left] + nums[right...
simplelr_Filter
[ { "content": "Question:\nGiven a set of integers, find all possible combinations of 3 integers that sum to 0.\n\nExample: \nInput: [-1, 0, 1, 2, -1, -4]\nOutput: [\n [-1, -1, 2],\n [-1, 0, 1]\n]\n\nNote: The output should not contain duplicate triplets.\n\nHere is my code in python:\n```python\ndef three_sum(...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9283, "level": 1, "question": "Given a set of integers, find all possible combinations of 3 integers that sum to 0.\n\nExample: \nInput: [-1, 0, 1, 2, -1, -4]\nOutput: [\n [-1, -1, 2],\n [-1, 0, 1]\n]\n\nNote: The output should not contain duplicate triplets.\n\nHere is my code in...
def minAdditionalHills(n, heights): if n <= 1: return 0 count = 0 prev = heights[0] current_run_length = 1 for i in range(1, n): if heights[i] == prev: current_run_length += 1 else: count += max(0, current_run_length - 1) prev = heights[i] ...
simplelr_Taco
[ { "content": "Question:\nYou are given an array of n integers which represents the height of hills in a row. Your task is to determine the minimum number of additional hills that need to be constructed such that no hill's height is the same as any of its adjacent hills. If it is already not possible, return -1....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9284, "level": 1, "question": "You are given an array of n integers which represents the height of hills in a row. Your task is to determine the minimum number of additional hills that need to be constructed such that no hill's height is the same as any of its adjacent hills. If it ...
from typing import List def stutter(stack: List[int]) -> List[int]: auxiliary = [] while stack: x = stack.pop() auxiliary.append(x) auxiliary.append(x) output = [] while auxiliary: output.append(auxiliary.pop()) return output
simplelr_Data_Structure
[ { "content": "Question:\n### Stutter Function for Stack Manipulation\n\nIn this assessment, you are required to implement a function `stutter` that uses the given approaches to double the values in a stack.\n\n**Objective**:\nWrite a function `stutter` that takes a stack as input and returns the stack with each...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9285, "level": 1, "question": "### Stutter Function for Stack Manipulation\n\nIn this assessment, you are required to implement a function `stutter` that uses the given approaches to double the values in a stack.\n\n**Objective**:\nWrite a function `stutter` that takes a stack as in...
from typing import List def can_form_increasing_sequence(arr: List[int]) -> str: sorted_arr = sorted(arr) for i in range(1, len(sorted_arr)): if sorted_arr[i] <= sorted_arr[i-1]: return "NO" return "YES"
simplelr_Codeforces
[ { "content": "Question:\n// Given an array of integers, determine whether the array can be rearranged to form a strictly increasing sequence. If it can be done, return \"YES\"; otherwise, return \"NO\".\n\n// An array forms a strictly increasing sequence if every element is strictly greater than the preceding o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9286, "level": 1, "question": "// Given an array of integers, determine whether the array can be rearranged to form a strictly increasing sequence. If it can be done, return \"YES\"; otherwise, return \"NO\".\n\n// An array forms a strictly increasing sequence if every element is st...
def rotate_matrix(matrix): return [list(row[::-1]) for row in zip(*matrix)]
simplelr_Apps
[ { "content": "Question:\nImplement a function `rotate_matrix(matrix)` that takes a 2D list (matrix) and rotates it 90 degrees clockwise. Assume the matrix is a non-empty square matrix (n x n).\n\nEx.\n```\nrotate_matrix([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n```\nshould return\n```\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9287, "level": 1, "question": "Implement a function `rotate_matrix(matrix)` that takes a 2D list (matrix) and rotates it 90 degrees clockwise. Assume the matrix is a non-empty square matrix (n x n).\n\nEx.\n```\nrotate_matrix([[1, 2, 3],\n [4, 5, 6],\n [7...
def find_first_duplicate(nums): n = len(nums) seen = [False] * (n + 1) for num in nums: if seen[num]: return num seen[num] = True return -1
simplelr_Filter
[ { "content": "Question:\n### Implement an efficient algorithm to find the first duplicate in an array of integers. The given array contains n integers. Each integer is in the range [1, n] (1-indexed). The algorithm should return one duplicate number if it exists, otherwise, return -1.\n\n# Example 1:\n# Input: ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9288, "level": 1, "question": "### Implement an efficient algorithm to find the first duplicate in an array of integers. The given array contains n integers. Each integer is in the range [1, n] (1-indexed). The algorithm should return one duplicate number if it exists, otherwise, re...
def sum_even_numbers(lst): return sum(num for num in lst if num % 2 == 0)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of integers as input and returns the sum of all the even numbers in the list. If there are no even numbers in the list, the function should return 0. The function should handle empty lists as well. Use the modulo operator to determine if a numbe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9289, "level": 1, "question": "Write a Python function that takes a list of integers as input and returns the sum of all the even numbers in the list. If there are no even numbers in the list, the function should return 0. The function should handle empty lists as well. Use the modu...
def longest_common_prefix(strs): if not strs: return "" prefix = "" i = 0 while True: # Check if all strings have at least i+1 characters if any(len(s) <= i for s in strs): break current_char = strs[0][i] # Check if all other strings have the same char...
simplelr_Filter
[ { "content": "Question:\nWrite a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string. For example, given the array [\"flower\",\"flow\",\"flight\"], the longest common prefix is \"fl\". Given the array [\"dog\",\"racecar\",\"car\"],...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9290, "level": 1, "question": "Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string. For example, given the array [\"flower\",\"flow\",\"flight\"], the longest common prefix is \"fl\". Given the a...
from typing import List def optimized_exchange_sort(arr: List[int]) -> List[int]: n = len(arr) if n <= 1: return arr for i in range(n): swapped = False for j in range(n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] ...
simplelr_Data_Structure
[ { "content": "Question:\nYou are given an array of integers. Your task is to write a function `optimized_exchange_sort` that sorts the array using an optimized version of the Exchange Sort algorithm. The optimized approach should minimize redundant comparisons and improve overall performance. \n\n### Requiremen...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9291, "level": 1, "question": "You are given an array of integers. Your task is to write a function `optimized_exchange_sort` that sorts the array using an optimized version of the Exchange Sort algorithm. The optimized approach should minimize redundant comparisons and improve over...
from typing import List def min_path_sum(grid: List[List[int]]) -> int: if not grid: return 0 m = len(grid) n = len(grid[0]) if m > 0 else 0 # Fill the first row for j in range(1, n): grid[0][j] += grid[0][j-1] # Fill the first column for i in range(1, m): ...
simplelr_Algorithm
[ { "content": "Question:\n**Context:** Dynamic Programming is a powerful technique for solving optimization and combinatorial problems by breaking them down into simpler subproblems. One classic problem is the \"Minimum Path Sum\" problem, where you need to find a path in a grid that minimizes the sum of the num...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9292, "level": 1, "question": "**Context:** Dynamic Programming is a powerful technique for solving optimization and combinatorial problems by breaking them down into simpler subproblems. One classic problem is the \"Minimum Path Sum\" problem, where you need to find a path in a gri...
def hcf(a, b): a = abs(a) b = abs(b) while b != 0: temp = b b = a % b a = temp return a
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes two integer numbers as input and returns the highest common factor (HCF) of the two numbers using the Euclidean algorithm.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9293, "level": 1, "question": "Create a function that takes two integer numbers as input and returns the highest common factor (HCF) of the two numbers using the Euclidean algorithm.", "split": "train" }
import math def find_primes(n): if n < 2: return [] sieve = [True] * (n + 1) sieve[0] = sieve[1] = False for current in range(2, int(math.sqrt(n)) + 1): if sieve[current]: for multiple in range(current * current, n + 1, current): sieve[multiple] = False p...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find and list all prime numbers up to a given number `n`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9294, "level": 1, "question": "Write a function to find and list all prime numbers up to a given number `n`.", "split": "train" }
def search(nums, target): if not nums: return -1 low = 0 high = len(nums) - 1 while low <= high: mid = (low + high) // 2 if nums[mid] == target: return mid if nums[mid] > nums[high]: # Left half is sorted if nums[low] <= target <= nums[...
simplelr_Apps
[ { "content": "Question:\n# Task\nYou are given a sorted (in ascending order) integer array `nums` of `n` elements and an integer `target`. Given that the array was originally rotated at an unknown pivot index k (0 <= k < n) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1],...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9295, "level": 1, "question": "# Task\nYou are given a sorted (in ascending order) integer array `nums` of `n` elements and an integer `target`. Given that the array was originally rotated at an unknown pivot index k (0 <= k < n) such that the resulting array is `[nums[k], nums[k+1]...
def max_projects(teams, projects): # Compute the remaining capacities for each team remaining = [end - start for start, end in teams] # Sort the projects in increasing order of duration projects.sort() count = 0 for duration in projects: best_team = -1 max_rem = -1 ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an assignment to schedule several teams to work on different projects over a certain period. Each team has a specific availability period during which they can work on projects, and each project requires a specific continuous time duration to be completed. You need to assi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9296, "level": 1, "question": "You are given an assignment to schedule several teams to work on different projects over a certain period. Each team has a specific availability period during which they can work on projects, and each project requires a specific continuous time duratio...
def generate_sequence(a, b, N): sequence = [a, b] if N == 2: return sequence for i in range(2, N): next_term = sequence[i-1] + sequence[i-2] sequence.append(next_term) return sequence
simplelr_Taco
[ { "content": "Question:\nIn mathematics, the Fibonacci sequence is a sequence in which each number is the sum of the two preceding ones, usually starting with 0 and 1. However, as part of your computer science studies, you want to implement a function to generate Fibonacci-like sequences where the starting two ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9297, "level": 1, "question": "In mathematics, the Fibonacci sequence is a sequence in which each number is the sum of the two preceding ones, usually starting with 0 and 1. However, as part of your computer science studies, you want to implement a function to generate Fibonacci-lik...
def is_valid_ip(ip): # Check for leading or trailing whitespace if ip.strip() != ip: return False parts = ip.split('.') if len(parts) != 4: return False for part in parts: # Check if the part is a digit string if not part.isdigit(): return False # ...
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python code to validate an IP address? The code should check if the given string is a valid IPv4 address.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9298, "level": 1, "question": "Can you provide a Python code to validate an IP address? The code should check if the given string is a valid IPv4 address.", "split": "train" }
def are_anagrams(s1: str, s2: str) -> bool: if len(s1) != len(s2): return False counts1 = [0] * 26 counts2 = [0] * 26 for c in s1: index = ord(c) - ord('a') counts1[index] += 1 for c in s2: index = ord(c) - ord('a') counts2[index] += 1 ...
simplelr_Data_Structure
[ { "content": "Question:\n### Anagram Checking\nYou are given two strings `s1` and `s2`. Your task is to determine if these strings are anagrams of each other. Two strings are anagrams if they contain the same characters with the same frequencies, but their order can be different.\n\nWrite a function `are_anagra...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9299, "level": 1, "question": "### Anagram Checking\nYou are given two strings `s1` and `s2`. Your task is to determine if these strings are anagrams of each other. Two strings are anagrams if they contain the same characters with the same frequencies, but their order can be differe...