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 min_coins(A, S): coins = list(set(A)) # Remove duplicates to optimize dp = [float('inf')] * (S + 1) dp[0] = 0 for i in range(1, S + 1): for coin in coins: if coin <= i: dp[i] = min(dp[i], dp[i - coin] + 1) return dp[S] if dp[S] != float('inf') else ...
simplelr_Taco
[ { "content": "Question:\n# Task\nGiven an array `A` of positive integers, where `A[i]` represents a coin with that value, determine the minimum number of coins that can be used to make a specific value `S`. If it is not possible to make that value, return `-1`.\n\n# Example\n\nFor `A = [1, 2, 5]` and `S = 11`, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9400, "level": 1, "question": "# Task\nGiven an array `A` of positive integers, where `A[i]` represents a coin with that value, determine the minimum number of coins that can be used to make a specific value `S`. If it is not possible to make that value, return `-1`.\n\n# Example\n\...
def sock_merchant(n, ar): frequency = {} for sock in ar: if sock in frequency: frequency[sock] += 1 else: frequency[sock] = 1 count = 0 for value in frequency.values(): count += value >> 1 return count
simplelr_Filter
[ { "content": "Question:\nHere is the link to the problem: https://www.hackerrank.com/challenges/sock-merchant/problem\n\nThe problem is to find the number of pairs of socks in a list of socks, where each pair consists of two identical socks. \n\nHere is the solution in Python:\n```python\ndef sock_merchant(n, a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9401, "level": 1, "question": "Here is the link to the problem: https://www.hackerrank.com/challenges/sock-merchant/problem\n\nThe problem is to find the number of pairs of socks in a list of socks, where each pair consists of two identical socks. \n\nHere is the solution in Python:...
def min_distance(str1, str2): m = len(str1) n = len(str2) # Create a DP table of (m+1) rows and (n+1) columns initialized to 0 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 # Need to delete all i characters from...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to calculate the minimum number of operations required to convert a given string to another string. You can perform operations like insert a character, delete a character, or replace a character.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9402, "level": 1, "question": "Write a python function to calculate the minimum number of operations required to convert a given string to another string. You can perform operations like insert a character, delete a character, or replace a character.", "split": "train" }
import heapq def shortest_path(graph, start, target): if start not in graph or target not in graph: return -1 if start == target: return 0 distances = {node: float('infinity') for node in graph} distances[start] = 0 pq = [] heapq.heappush(pq, (0, start)) while...
simplelr_Algorithm
[ { "content": "Question:\n### Graph Pathfinding Challenge\n\nYou are given a weighted, directed graph represented as an adjacency list. Your task is to find the shortest path from a given start node to a target node and return the total weight of that path. If there is no such path, return -1.\n\n#### Task:\nWri...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9403, "level": 1, "question": "### Graph Pathfinding Challenge\n\nYou are given a weighted, directed graph represented as an adjacency list. Your task is to find the shortest path from a given start node to a target node and return the total weight of that path. If there is no such ...
def reverse_elements(input_list): result = [] for item in input_list: if isinstance(item, str): reversed_item = item[::-1] else: reversed_item = str(item)[::-1] result.append(reversed_item) return result
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes the input as a list of elements. If the element is a string, reverse it; otherwise, convert it to a string and then reverse it.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9404, "level": 1, "question": "Create a function that takes the input as a list of elements. If the element is a string, reverse it; otherwise, convert it to a string and then reverse it.", "split": "train" }
def longest_rainfall_sequence(rainfall, threshold): max_length = 0 max_total = 0 current_length = 0 current_total = 0 for day in rainfall: if day > threshold: current_length += 1 current_total += day if current_length > max_length: max_leng...
simplelr_Evol
[ { "content": "Question:\nDesign a function that takes a list of integers representing the daily rainfall measurements over a month and returns the longest continuous sequence of days where the rainfall was above a given threshold. Additionally, the function should report the total rainfall for that sequence.\nA...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9405, "level": 1, "question": "Design a function that takes a list of integers representing the daily rainfall measurements over a month and returns the longest continuous sequence of days where the rainfall was above a given threshold. Additionally, the function should report the t...
def minCost(s, cost): if not s: return 0 prev_dp = {None: 0} for i in range(len(s)): current_char = s[i] current_cost = cost[i] current_dp = {} for prev_state, prev_cost in prev_dp.items(): # Option 1: Delete the current character key = prev_st...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` and an array of integers `cost` where `cost[i]` represents the cost of deleting the `i-th` character in `s`, your task is to remove the minimum number of characters from `s` such that no two adjacent characters are the same. The cost of removing a character is defined...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9406, "level": 1, "question": "Given a string `s` and an array of integers `cost` where `cost[i]` represents the cost of deleting the `i-th` character in `s`, your task is to remove the minimum number of characters from `s` such that no two adjacent characters are the same. The cost...
def find_common_elements(*lists): if not lists: return [] # Check if any list is empty for lst in lists: if not lst: return [] # Convert all lists to sets sets = [set(lst) for lst in lists] # Compute the intersection of all sets common_set = sets[0]...
simplelr_Filter
[ { "content": "Question:\nIn this problem, you'll implement a function `find_common_elements` that finds all the elements common to all the input lists. For example, if you have three lists [1, 2, 3], [2, 3, 4], and [3, 4, 5], the function should return [3] as it is the only element common to all the lists.\nAns...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9407, "level": 1, "question": "In this problem, you'll implement a function `find_common_elements` that finds all the elements common to all the input lists. For example, if you have three lists [1, 2, 3], [2, 3, 4], and [3, 4, 5], the function should return [3] as it is the only el...
from typing import List def count_packages(weights: List[int]) -> List[int]: light = 0 medium = 0 heavy = 0 for weight in weights: if weight < 5: light += 1 elif 5 <= weight <= 10: medium += 1 else: heavy += 1 return [light, medium, heavy]
simplelr_Apps
[ { "content": "Question:\nA courier company handles sorting packages into three different categories based on their weight: `light`, `medium`, and `heavy`. Each package has a weight that falls into one of these three categories. You are given a list of package weights and your task is to write a function that de...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9408, "level": 1, "question": "A courier company handles sorting packages into three different categories based on their weight: `light`, `medium`, and `heavy`. Each package has a weight that falls into one of these three categories. You are given a list of package weights and your ...
def categorize_numbers(nums: list) -> dict: positives = [] negatives = [] zeros = [] for num in nums: if num > 0: positives.append(num) elif num < 0: negatives.append(num) else: zeros.append(num) return { "positive": positives, ...
simplelr_Package
[ { "content": "Question:\nDesign a function named `categorize_numbers` that takes a list of integers and separates them into three different categories: positive, negative, and zero. Each category should be stored in its own list. The function should return a dictionary containing these three lists, under the ke...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9409, "level": 1, "question": "Design a function named `categorize_numbers` that takes a list of integers and separates them into three different categories: positive, negative, and zero. Each category should be stored in its own list. The function should return a dictionary contain...
def pairwise_sum(lst): if not lst: return [] new_list = list(lst) for i in range(1, len(new_list) - 1): new_list[i] = lst[i - 1] + lst[i] return new_list
simplelr_Apps
[ { "content": "Question:\nImplement the function `pairwise_sum` which takes a list of numbers as argument and returns a new list where each element is the sum of its adjacent elements from the original list. The first and last elements of the new list should be equal to the first and last elements of the origina...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9410, "level": 1, "question": "Implement the function `pairwise_sum` which takes a list of numbers as argument and returns a new list where each element is the sum of its adjacent elements from the original list. The first and last elements of the new list should be equal to the fir...
import string def count_words(sentences: list[str]) -> dict[str, int]: """ Count the occurrences of each word in the given list of sentences. Parameters: sentences (list[str]): A list of strings containing sentences. Returns: dict[str, int]: A dictionary mapping each unique word to its count....
simplelr_Algorithm
[ { "content": "Question:\n### Words Counter\n\nYour task is to create a function that counts the number of occurrences of each word in a given list of strings. The function should return the count of each word in a dictionary format.\n\n#### Requirements:\n1. Implement a function that accepts a list of strings.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9411, "level": 1, "question": "### Words Counter\n\nYour task is to create a function that counts the number of occurrences of each word in a given list of strings. The function should return the count of each word in a dictionary format.\n\n#### Requirements:\n1. Implement a functi...
def longest_balanced_subsequence(s): x_count = s.count('X') y_count = s.count('Y') return 2 * min(x_count, y_count)
simplelr_Filter
[ { "content": "Question:\nIn this problem, we need to find the length of the longest subsequence in a given string that has a balanced number of 'X' and 'Y'. A balanced number means that the number of 'X's is equal to the number of 'Y's.\n\nFor example, \"XYXYXY\" is a valid string with a balanced number of 'X' ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9412, "level": 1, "question": "In this problem, we need to find the length of the longest subsequence in a given string that has a balanced number of 'X' and 'Y'. A balanced number means that the number of 'X's is equal to the number of 'Y's.\n\nFor example, \"XYXYXY\" is a valid st...
import hashlib def string_to_sha256(input_string): if not isinstance(input_string, str): return None if input_string == "": return None try: encoded_string = input_string.encode('utf-8') hash_object = hashlib.sha256(encoded_string) hex_digest = hash_object.hexdigest(...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that converts a string to its SHA-256 hash equivalent. If the input string is empty, return `None`. Ensure the function is robust and handles potential errors gracefully.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9413, "level": 1, "question": "Create a function that converts a string to its SHA-256 hash equivalent. If the input string is empty, return `None`. Ensure the function is robust and handles potential errors gracefully.", "split": "train" }
from collections import Counter def can_form_palindrome(s: str) -> bool: counts = Counter(s) odd_counts = 0 for count in counts.values(): if count % 2 != 0: odd_counts += 1 if odd_counts > 1: return False return True
simplelr_Taco
[ { "content": "Question:\nWrite a function that determines if a given string can be rearranged to form a palindrome. A palindrome is a word or phrase that reads the same forward and backward. For example, \"level\" and \"racecar\" are palindromes, while \"hello\" is not.\n\nTo achieve this, a string can be rearr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9414, "level": 1, "question": "Write a function that determines if a given string can be rearranged to form a palindrome. A palindrome is a word or phrase that reads the same forward and backward. For example, \"level\" and \"racecar\" are palindromes, while \"hello\" is not.\n\nTo ...
def process_orders(orders: list) -> dict: total_orders = 0 total_value = 0.0 highest_value = None lowest_value = None for order in orders: # Check if the order is a dictionary if not isinstance(order, dict): raise ValueError("Invalid order: not a dictionary") # C...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\nImplement a function to simulate a simplified e-commerce order processing system. You need to design a function that accepts a list of orders and returns a summary of order statistics including the total number of orders, the total value of all orders, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9415, "level": 1, "question": "### Coding Assessment Question\n\nImplement a function to simulate a simplified e-commerce order processing system. You need to design a function that accepts a list of orders and returns a summary of order statistics including the total number of orde...
def remove_duplicates(data: list, ignore_case: bool = False) -> list: if not isinstance(data, list): return [] seen = set() result = [] for item in data: if ignore_case and isinstance(item, str): key = item.lower() else: key = item ...
simplelr_Evol
[ { "content": "Question:\nDesign and implement a Python function that takes a list of integers as input and returns a new list with all the duplicate values removed. The order of elements in the returned list should be the same as their first appearance in the original list. \n\nFurthermore, implement a feature ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9416, "level": 1, "question": "Design and implement a Python function that takes a list of integers as input and returns a new list with all the duplicate values removed. The order of elements in the returned list should be the same as their first appearance in the original list. \n...
def num_trees(n: int) -> int: if n == 0: return 1 dp = [0] * (n + 1) dp[0] = 1 # Base case: one way to have an empty tree for i in range(1, n + 1): for j in range(1, i + 1): dp[i] += dp[j - 1] * dp[i - j] return dp[n]
simplelr_Data_Structure
[ { "content": "Question:\n### Unique Binary Search Trees: Counting with Dynamic Programming\n\n#### Problem Statement\nGiven an integer \\(n\\), write a function `num_trees(n)` to determine the number of structurally unique Binary Search Trees (BSTs) that can be constructed using the values from 1 to \\(n\\).\n\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9417, "level": 1, "question": "### Unique Binary Search Trees: Counting with Dynamic Programming\n\n#### Problem Statement\nGiven an integer \\(n\\), write a function `num_trees(n)` to determine the number of structurally unique Binary Search Trees (BSTs) that can be constructed usi...
def rearrange_list(nums): evens = [num for num in nums if num % 2 == 0] odds = [num for num in nums if num % 2 != 0] sorted_evens = sorted(evens, reverse=True) sorted_odds = sorted(odds, reverse=True) return sorted_evens + sorted_odds
simplelr_Algorithm
[ { "content": "Question:\n### Coding Question on List Manipulation and Sorting\n\n#### Context\nManipulating and sorting lists are fundamental operations in programming that find use in numerous real-world applications. You're tasked with creating a function that rearranges a list of integers to meet specific cr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9418, "level": 1, "question": "### Coding Question on List Manipulation and Sorting\n\n#### Context\nManipulating and sorting lists are fundamental operations in programming that find use in numerous real-world applications. You're tasked with creating a function that rearranges a l...
from typing import List def consecutive_duplicates(nums: List[int]) -> List[int]: if not nums: return [] result = [nums[0]] for num in nums[1:]: if num != result[-1]: result.append(num) return result
simplelr_Package
[ { "content": "Question:\nYou are required to implement a function called `consecutive_duplicates` that collapses consecutive duplicate elements in a given list of integers, keeping only one instance of each consecutive sequence. This function effectively compresses sequences of the same number into a single occ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9419, "level": 1, "question": "You are required to implement a function called `consecutive_duplicates` that collapses consecutive duplicate elements in a given list of integers, keeping only one instance of each consecutive sequence. This function effectively compresses sequences o...
def sort_string(s): return ''.join(sorted(s))
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes a string as input and returns a new string with the characters sorted in ascending order. The function should be able to handle both uppercase and lowercase letters, as well as special characters, but it should sort them based on their ASCII values. Additiona...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9420, "level": 1, "question": "Write a function that takes a string as input and returns a new string with the characters sorted in ascending order. The function should be able to handle both uppercase and lowercase letters, as well as special characters, but it should sort them bas...
from typing import List def modified_counting_sort(arr: List[int]) -> List[int]: if not arr: return [] min_val = min(arr) shifted = [x - min_val for x in arr] max_shifted = max(shifted) if shifted else 0 count = [0] * (max_shifted + 1) for x in shifted: count[x] += 1 ...
simplelr_Data_Structure
[ { "content": "Question:\nYou are given an array of integers which may include negative numbers. Implement a modified version of Counting Sort that can handle both positive and negative numbers efficiently.\n\n### Function Signature:\n```python\ndef modified_counting_sort(arr: List[int]) -> List[int]:\n```\n\n##...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9421, "level": 1, "question": "You are given an array of integers which may include negative numbers. Implement a modified version of Counting Sort that can handle both positive and negative numbers efficiently.\n\n### Function Signature:\n```python\ndef modified_counting_sort(arr: ...
def rotate_matrix(matrix): n = len(matrix) rotated = [] for j in range(n): new_row = [] for i in range(n - 1, -1, -1): new_row.append(matrix[i][j]) rotated.append(new_row) return rotated
simplelr_Taco
[ { "content": "Question:\nImplement a function `rotate_matrix(matrix)` that takes a 2D list `matrix` representing an NxN matrix and rotates it 90 degrees clockwise, returning the rotated matrix. You are not allowed to use any additional matrix or collections to achieve this.\n\n**Notes:**\n* You may assume all i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9422, "level": 1, "question": "Implement a function `rotate_matrix(matrix)` that takes a 2D list `matrix` representing an NxN matrix and rotates it 90 degrees clockwise, returning the rotated matrix. You are not allowed to use any additional matrix or collections to achieve this.\n\...
def common_tuples(list1, list2): set1 = set(list1) set2 = set(list2) return list(set1 & set2)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that compares two lists of tuples and returns a list of tuples that are common to both lists. The function should be efficient and handle large datasets.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9423, "level": 1, "question": "Write a Python function that compares two lists of tuples and returns a list of tuples that are common to both lists. The function should be efficient and handle large datasets.", "split": "train" }
def factorial(n): """ Calculate the factorial of a non-negative integer n using recursion. Args: n (int): A non-negative integer. Returns: int: The factorial of n. Example: >>> factorial(5) 120 """ # Base case: 0! and 1! both equal 1 if n == 0 or n == 1...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to calculate the factorial of a non-negative integer `n`. Use recursion to implement the function. The function should handle the base case where `n` is 0 or 1, and recursively calculate the factorial for `n > 1`. Include comments and a docstring explaining the f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9424, "level": 1, "question": "Write a Python function to calculate the factorial of a non-negative integer `n`. Use recursion to implement the function. The function should handle the base case where `n` is 0 or 1, and recursively calculate the factorial for `n > 1`. Include commen...
def is_valid_password(password: str) -> bool: # Check the length of the password if not (8 <= len(password) <= 20): return False # Check for at least one lowercase letter has_lower = any(c.islower() for c in password) if not has_lower: return False # Check for at least ...
simplelr_Codeforces
[ { "content": "Question:\nA company wants to securely store passwords in a way that ensures passwords must contain at least one lowercase letter, one uppercase letter, one digit, and one special character from the set `!@#$%^&*()`. Additionally, the length of the password must be at least 8 characters and at mos...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9425, "level": 1, "question": "A company wants to securely store passwords in a way that ensures passwords must contain at least one lowercase letter, one uppercase letter, one digit, and one special character from the set `!@#$%^&*()`. Additionally, the length of the password must ...
def generate_even_numbers(max_num): return [x for x in range(0, max_num + 1) if x % 2 == 0]
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that generates a list of even numbers from 0 up to a given number (inclusive)?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9426, "level": 1, "question": "How can I create a Python function that generates a list of even numbers from 0 up to a given number (inclusive)?", "split": "train" }
def longest_string(lst): if not lst: return "" longest = lst[0] for s in lst[1:]: if len(s) > len(longest): longest = s return longest
simplelr_Filter
[ { "content": "Question:\nCan you help me with a programming challenge? I need to write a function that takes a list of strings and returns the longest string in the list. If there are multiple strings with the same maximum length, the function should return the first one that appears in the list.\nAnswer:\nLet'...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9427, "level": 1, "question": "Can you help me with a programming challenge? I need to write a function that takes a list of strings and returns the longest string in the list. If there are multiple strings with the same maximum length, the function should return the first one that ...
def squares_and_cubes(numbers): squares = {} cubes = {} for num in numbers: squares[num] = num ** 2 cubes[num] = num ** 3 return squares, cubes
simplelr_Evol
[ { "content": "Question:\nWrite a 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 squares of those integers. For an additional challenge, modify the function to also include the cubes of the integers in a separate dictionary and...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9428, "level": 1, "question": "Write a 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 squares of those integers. For an additional challenge, modify the function to also include the cubes of the in...
def reverse_inner_string(s): # Find the first non-space character first = 0 while first < len(s) and s[first] == ' ': first += 1 if first == len(s): return s # The string is empty or only spaces # Find the last non-space character last = len(s) - 1 while last >= 0 and s...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to reverse a string and output the reversed string. However, only reverse the characters between the first and last non-space characters of the string, ignoring the leading and trailing spaces.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9429, "level": 1, "question": "Write a function to reverse a string and output the reversed string. However, only reverse the characters between the first and last non-space characters of the string, ignoring the leading and trailing spaces.", "split": "train" }
from collections import deque def find_task_order(n, dependencies): # Initialize adjacency list and in-degree array adj = [[] for _ in range(n)] in_degree = [0] * n for a, b in dependencies: adj[a].append(b) in_degree[b] += 1 queue = deque() for i in range(n): if in_de...
simplelr_Leetcode
[ { "content": "Question:\nIn a project management system, tasks are linked to one another as dependencies, forming a directed acyclic graph (DAG). You are given `n` tasks labeled from `0` to `n-1` and a list of dependencies where dependencies[i] = [a, b] indicates that task `a` must be completed before task `b`....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9430, "level": 1, "question": "In a project management system, tasks are linked to one another as dependencies, forming a directed acyclic graph (DAG). You are given `n` tasks labeled from `0` to `n-1` and a list of dependencies where dependencies[i] = [a, b] indicates that task `a`...
from typing import List def improved_binary_search(array: List[int], target: int) -> int: low = 0 high = len(array) - 1 result = -1 while low <= high: mid = low + (high - low) // 2 if array[mid] == target: result = mid high = mid - 1 # Continue searching left fo...
simplelr_Data_Structure
[ { "content": "Question:\n### Task: Improved Binary Search\n\nYou are given a sorted array of integers and a target value. Your task is to write an optimized version of the binary search algorithm that handles potential integer overflow issues while calculating the mid index. Additionally, it should return the f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9431, "level": 1, "question": "### Task: Improved Binary Search\n\nYou are given a sorted array of integers and a target value. Your task is to write an optimized version of the binary search algorithm that handles potential integer overflow issues while calculating the mid index. A...
def convert_celsius_to_fahrenheit(celsius): fahrenheit = (celsius * 9/5) + 32 return fahrenheit # Example usage: if __name__ == "__main__": celsius_temp = float(input("Enter temperature in Celsius: ")) fahrenheit_temp = convert_celsius_to_fahrenheit(celsius_temp) print(f"{celsius_temp}°C is equal t...
simplelr_Filter
[ { "content": "Question:\nWrite a Python code that converts temperature from Celsius to Fahrenheit and handles the conversion in a function called `convert_celsius_to_fahrenheit()`. The code should take a Celsius temperature as input and output the corresponding Fahrenheit temperature.\nAnswer:\nLet's think step...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9432, "level": 1, "question": "Write a Python code that converts temperature from Celsius to Fahrenheit and handles the conversion in a function called `convert_celsius_to_fahrenheit()`. The code should take a Celsius temperature as input and output the corresponding Fahrenheit temp...
def count_ways(n: int) -> int: if n == 0: return 1 elif n == 1: return 1 a, b = 1, 1 # Representing Fib(1) and Fib(2) for i in range(3, n + 2): c = a + b a = b b = c return b
simplelr_Algorithm
[ { "content": "Question:\n### Question\nYou are given an integer `n` representing the number of steps in a staircase. You are initially on the 0th step and you can move to either the next step or skip one step. Write a function to compute the total number of distinct ways you can reach the nth step.\n\n### Funct...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9433, "level": 1, "question": "### Question\nYou are given an integer `n` representing the number of steps in a staircase. You are initially on the 0th step and you can move to either the next step or skip one step. Write a function to compute the total number of distinct ways you c...
def calculateRewards(jogging, cycling, swimming): jogging_points = sum(jogging) * 10 cycling_points = sum(cycling) * 5 swimming_points = sum(swimming) * 15 total_points = jogging_points + cycling_points + swimming_points return total_points // 100
simplelr_Taco
[ { "content": "Question:\nThe local gym is implementing a new reward system for its members. Members can earn points based on the type and duration of their workouts. They can then redeem their points for rewards. The gym wants to calculate how many rewards a member can receive based on their workout schedule an...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9434, "level": 1, "question": "The local gym is implementing a new reward system for its members. Members can earn points based on the type and duration of their workouts. They can then redeem their points for rewards. The gym wants to calculate how many rewards a member can receive...
import random def coin_flip_game(): player1 = 0 player2 = 0 flips = 0 while player1 < 10 and player2 < 10: flip = random.randint(0, 1) if flip == 0: player1 += 1 else: player2 += 1 flips += 1 return flips
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to simulate a simple coin flip game. The game continues until one player reaches a score of 10, and each player has an equal chance of winning a flip. The function should return the number of flips it took to reach the score of 10.\nAnswer:\nLet's think step by s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9435, "level": 1, "question": "Write a Python function to simulate a simple coin flip game. The game continues until one player reaches a score of 10, and each player has an equal chance of winning a flip. The function should return the number of flips it took to reach the score of ...
import os def manage_environment_variable(var_name: str, new_value: str, check_large_file_support: bool) -> str: try: current_value = os.environ[var_name] except KeyError: raise KeyError(f"Environment variable '{var_name}' does not exist.") if check_large_file_support: # For la...
simplelr_Docs
[ { "content": "Question:\n#### Coding Assessment Question\n\n**Objective:**\nWrite a Python function that manages environment variables and simulates system call errors using the functionalities provided by the \"posix\" module (imported through \"os\" module as recommended). Your function should:\n1. Retrieve t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9436, "level": 1, "question": "#### Coding Assessment Question\n\n**Objective:**\nWrite a Python function that manages environment variables and simulates system call errors using the functionalities provided by the \"posix\" module (imported through \"os\" module as recommended). Y...
from typing import List def max_hourglass_sum(matrix: List[List[int]]) -> int: n = len(matrix) max_sum = float('-inf') for i in range(n - 2): for j in range(n - 2): current_sum = (matrix[i][j] + matrix[i][j+1] + matrix[i][j+2] + matrix[i+1][j+1] + matrix[i+2][...
simplelr_Codeforces
[ { "content": "Question:\nYou are given a square matrix of size \\( n \\times n \\) containing integers. Your task is to find the maximum sum of any hourglass-shaped sub-matrix within the given matrix. \n\nAn hourglass in the matrix is formed by choosing a 3x3 subset of elements with the following pattern:\n```\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9437, "level": 1, "question": "You are given a square matrix of size \\( n \\times n \\) containing integers. Your task is to find the maximum sum of any hourglass-shaped sub-matrix within the given matrix. \n\nAn hourglass in the matrix is formed by choosing a 3x3 subset of element...
def is_palindrome(s: str) -> bool: """ Returns True if the input string is a palindrome, False otherwise. :param s: The input string to be checked. :return: A boolean indicating whether the string is a palindrome. """ left, right = 0, len(s) - 1 while left < right: if not s[left...
simplelr_Filter
[ { "content": "Question:\nGiven a string, determine if it is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization).\n\nExample:\nInput: \"A man, a plan, a canal: Panama\"\nOutput: \"True\"\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9438, "level": 1, "question": "Given a string, determine if it is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization).\n\nExample:\nInput: \"A man, a plan, a...
def insert_at_beginning(lst, num): return [num] + lst
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes two arguments - a list and a number. The function should return a new list with the number inserted at the beginning of the list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9439, "level": 1, "question": "Create a function that takes two arguments - a list and a number. The function should return a new list with the number inserted at the beginning of the list.", "split": "train" }
import sys def float_operations(number_str: str) -> tuple: a_float = float(number_str) str_a_float = str(a_float) is_float = isinstance(a_float, float) min_float = sys.float_info.min max_float = sys.float_info.max return (a_float, str_a_float, is_float, min_float, max_float)
simplelr_Docs
[ { "content": "Question:\nIn this exercise, you will implement a Python function that interacts with low-level details of floating-point objects. For this task, simulate some of the functionality described in the provided documentation using Python.\n\n### Objective\n\nWrite a Python function that:\n1. Takes a s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9440, "level": 1, "question": "In this exercise, you will implement a Python function that interacts with low-level details of floating-point objects. For this task, simulate some of the functionality described in the provided documentation using Python.\n\n### Objective\n\nWrite a ...
def find_event_days(days_past): days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] return [days[x % 7] for x in days_past]
simplelr_Evol
[ { "content": "Question:\nWrite a Python function called `find_event_days` that takes a list of integers where each integer represents the number of days past since an event occurred. The function should return a list of strings representing the day of the week on which each event happened. Assume today is Monda...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9441, "level": 1, "question": "Write a Python function called `find_event_days` that takes a list of integers where each integer represents the number of days past since an event occurred. The function should return a list of strings representing the day of the week on which each ev...
from collections import Counter def count_characters(words, chars): char_count = Counter(chars) total_length = 0 for word in words: word_counter = Counter(word) valid = True for c in word_counter: if word_counter[c] > char_count.get(c, 0): valid = False ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of strings `words` and another string `chars`. Each string in `words` is composed of lowercase English letters. The string `chars` is also composed of lowercase English letters. We want to determine the length of strings in `words` that can be formed using the let...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9442, "level": 1, "question": "You are given an array of strings `words` and another string `chars`. Each string in `words` is composed of lowercase English letters. The string `chars` is also composed of lowercase English letters. We want to determine the length of strings in `word...
def simplify_path(path: str) -> str: parts = path.split('/') stack = [] for part in parts: if part == '' or part == '.': continue elif part == '..': if stack: stack.pop() else: stack.append(part) if not stack: return '/'...
simplelr_Apps
[ { "content": "Question:\nGiven a string representing a file path in a Unix-style filesystem, your task is to simplify the path and return a standardized version. The path may contain multiple slashes (`/`), dots (`.`) representing the current directory, and double dots (`..`) representing the parent directory.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9443, "level": 1, "question": "Given a string representing a file path in a Unix-style filesystem, your task is to simplify the path and return a standardized version. The path may contain multiple slashes (`/`), dots (`.`) representing the current directory, and double dots (`..`) ...
def reverse_list(input_list): input_list.reverse() return input_list
simplelr_Prefill
[ { "content": "Question:\nWrite a function to reverse a list in Python. Which built-in method should be used to reverse a list?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9444, "level": 1, "question": "Write a function to reverse a list in Python. Which built-in method should be used to reverse a list?", "split": "train" }
from collections import defaultdict def max_length_subarray_two_colors(arr): count = defaultdict(int) left = 0 max_length = 0 for right in range(len(arr)): color = arr[right] count[color] += 1 # Shrink the window if more than two distinct colors are present whil...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of integers where each integer represents a different color of a marble. You need to form the largest possible contiguous subarray such that no more than two distinct colors are present in the subarray. \n\nReturn _the length of the longest such subarray_.\nAnswer...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9445, "level": 1, "question": "You are given an array of integers where each integer represents a different color of a marble. You need to form the largest possible contiguous subarray such that no more than two distinct colors are present in the subarray. \n\nReturn _the length of ...
def minSquares(N): # Precompute all squares up to N squares = [] j = 1 while j * j <= N: squares.append(j * j) j += 1 # Initialize DP array dp = [float('inf')] * (N + 1) dp[0] = 0 # Base case for i in range(1, N + 1): for s in squares: if s ...
simplelr_Taco
[ { "content": "Question:\nGiven a positive integer N, find the least number of perfect squares (like 1, 4, 9, 16, ...) which sum up to N.\n\nExample 1:\nInput: N = 12\nOutput: 3\nExplanation: 12 = 4 + 4 + 4\n\nExample 2:\nInput: N = 13\nOutput: 2\nExplanation: 13 = 4 + 9\n\nYour Task:\nYou don't need to read or ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9446, "level": 1, "question": "Given a positive integer N, find the least number of perfect squares (like 1, 4, 9, 16, ...) which sum up to N.\n\nExample 1:\nInput: N = 12\nOutput: 3\nExplanation: 12 = 4 + 4 + 4\n\nExample 2:\nInput: N = 13\nOutput: 2\nExplanation: 13 = 4 + 9\n\nYou...
def sumAlt(arr, index=0): if not arr: return 0 if index % 2 == 0: return arr[0] + sumAlt(arr[1:], index + 1) else: return sumAlt(arr[1:], index + 1)
simplelr_Filter
[ { "content": "Question:\nPlease construct a Python function dubbed 'sumAlt' that accepts an array of numerical values as an argument. This function should calculate the aggregate of those values situated at alternate indexes within the list, commencing from the initial index. Furthermore, the function should em...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9447, "level": 1, "question": "Please construct a Python function dubbed 'sumAlt' that accepts an array of numerical values as an argument. This function should calculate the aggregate of those values situated at alternate indexes within the list, commencing from the initial index. ...
from collections import deque def are_all_servers_connected(n, edges): if n == 0: return True if n == 1: return True # Build adjacency list adj = [[] for _ in range(n)] for u, v in edges: adj[u].append(v) adj[v].append(u) # BFS initialization visited = [False...
simplelr_Leetcode
[ { "content": "Question:\nA company has a network of servers connected by bidirectional links between pairs of servers. You are given an integer `n` representing the number of servers (labeled from `0` to `n-1`) and a 2D integer array `edges` where `edges[i] = [ui, vi]` indicates there is a link between servers ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9448, "level": 1, "question": "A company has a network of servers connected by bidirectional links between pairs of servers. You are given an integer `n` representing the number of servers (labeled from `0` to `n-1`) and a 2D integer array `edges` where `edges[i] = [ui, vi]` indicat...
def max_water(heights): left = 0 right = len(heights) - 1 max_area = 0 while left < right: width = right - left min_height = min(heights[left], heights[right]) current_area = width * min_height if current_area > max_area: max_area = current_area ...
simplelr_Taco
[ { "content": "Question:\nYou are given an array of integers `heights` representing the heights of buildings, where the `i`-th building is located at position `i`. Each building is `1` unit wide. Find two buildings such that together with the x-axis they form a container, which can hold the most water. Return th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9449, "level": 1, "question": "You are given an array of integers `heights` representing the heights of buildings, where the `i`-th building is located at position `i`. Each building is `1` unit wide. Find two buildings such that together with the x-axis they form a container, which...
from typing import List def max_profit(prices: List[int], fee: int) -> int: if not prices: return 0 current_not_holding = 0 current_holding = -prices[0] for price in prices[1:]: next_not_holding = max(current_not_holding, current_holding + price - fee) next_holding = m...
simplelr_Algorithm
[ { "content": "Question:\n### Question: Stock Profit Calculation with Transaction Fees\n\n**Context:**\n\nAs a financial analyst, you are tasked with devising a strategy to maximize profit from stock trading while accounting for transaction fees. Each transaction incurs a certain fee, which reduces the effective...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9450, "level": 1, "question": "### Question: Stock Profit Calculation with Transaction Fees\n\n**Context:**\n\nAs a financial analyst, you are tasked with devising a strategy to maximize profit from stock trading while accounting for transaction fees. Each transaction incurs a certa...
def check_sorted(nums): for i in range(1, len(nums)): if nums[i] < nums[i-1]: return (i-1, i) return -1
simplelr_Prefill
[ { "content": "Question:\nWrite a function to check if a list of numbers is sorted in ascending order. If there are any two successive numbers that are not in ascending order, the function should return the indices where the sorting stops. Otherwise, it should return -1 indicating the list is sorted.\nAnswer:\nL...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9451, "level": 1, "question": "Write a function to check if a list of numbers is sorted in ascending order. If there are any two successive numbers that are not in ascending order, the function should return the indices where the sorting stops. Otherwise, it should return -1 indicat...
def parse_log(log: str) -> dict: result = {} for part in log.split(';'): part = part.strip() if not part: continue key, value = part.split(':', 1) key = key.strip() value = value.strip() result[key] = value return result
simplelr_Package
[ { "content": "Question:\nYou are required to implement a function called `parse_log(log: str) -> dict`. This function should take a log of key-value pairs represented as a single string and return a dictionary with the key-value pairs parsed from the string. Each key-value pair in the log is separated by a semi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9452, "level": 1, "question": "You are required to implement a function called `parse_log(log: str) -> dict`. This function should take a log of key-value pairs represented as a single string and return a dictionary with the key-value pairs parsed from the string. Each key-value pai...
def read_numbers_from_file(filename): try: with open(filename, 'r') as file: numbers = [int(line.strip()) for line in file] return numbers except FileNotFoundError: print(f"File {filename} not found.") return [] # Example usage numbers = read_numbers_from_file('numbe...
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python code snippet to convert a text file containing a list of numbers into a list of integers in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9453, "level": 1, "question": "Can you provide a Python code snippet to convert a text file containing a list of numbers into a list of integers in Python?", "split": "train" }
def find_longest_substring(s): """ Finds the longest substring of a string that contains only unique characters. Args: s: The input string. Returns: The longest substring of s that contains only unique characters. """ longest_substring = "" for i in range(len(s)): c...
simplelr_Filter
[ { "content": "Question:\nThis code, written in Python, has a specific task:\n\n```python\ndef find_longest_substring(s):\n \"\"\"\n Finds the longest substring of a string that contains only unique characters.\n\n Args:\n s: The input string.\n\n Returns:\n The longest substring of s that contains onl...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9454, "level": 1, "question": "This code, written in Python, has a specific task:\n\n```python\ndef find_longest_substring(s):\n \"\"\"\n Finds the longest substring of a string that contains only unique characters.\n\n Args:\n s: The input string.\n\n Returns:\n The longe...
def run_length_encoding(s): if not s: return "" result = [] current_char = s[0] count = 1 for char in s[1:]: if char == current_char: count += 1 else: result.append(f"{current_char}{count}") current_char = char count = 1 res...
simplelr_Filter
[ { "content": "Question:\nWrite a program to encode a string using run-length encoding. Run-length encoding is a simple form of data compression where consecutive identical characters are replaced with a single character followed by the number of occurrences of that character. For example, the string \"aaabbbbcc...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9455, "level": 1, "question": "Write a program to encode a string using run-length encoding. Run-length encoding is a simple form of data compression where consecutive identical characters are replaced with a single character followed by the number of occurrences of that character. ...
def calculate_factorial(n): if n == 0 or n == 1: return 1 else: return n * calculate_factorial(n - 1)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that calculates the factorial of a given non-negative integer using a recursive approach. The function should be named `calculate_factorial` and take a single argument, `n`, which is the non-negative integer for which the factorial is to be calculated. The factor...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9456, "level": 1, "question": "Write a Python function that calculates the factorial of a given non-negative integer using a recursive approach. The function should be named `calculate_factorial` and take a single argument, `n`, which is the non-negative integer for which the factor...
def minEditDistance(a, b): m = len(a) n = len(b) dp = [[0] * (n + 1) for _ in range(m + 1)] # Initialize the base cases for i in range(m + 1): dp[i][0] = i for j in range(n + 1): dp[0][j] = j # Fill the DP table for i in range(1, m + 1): for j in range(1...
simplelr_Taco
[ { "content": "Question:\nYou are given two strings $a$ and $b$. Your task is to determine the minimum number of operations required to convert string $a$ into string $b$. You can perform the following three operations on the string $a$:\n\n1. Insert a character.\n2. Delete a character.\n3. Replace a character.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9457, "level": 1, "question": "You are given two strings $a$ and $b$. Your task is to determine the minimum number of operations required to convert string $a$ into string $b$. You can perform the following three operations on the string $a$:\n\n1. Insert a character.\n2. Delete a c...
import collections def walls_and_gates(rooms): if not rooms or len(rooms) == 0: return rows = len(rooms) cols = len(rooms[0]) if rows > 0 else 0 q = collections.deque() for i in range(rows): for j in range(cols): if rooms[i][j] == 0: q.append((i, j)) ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a matrix `rooms` representing a 2D grid of rooms where:\n- `-1` represents a wall or an obstacle.\n- `0` represents a gate.\n- `INF` represents an empty room. It's guaranteed that `INF` will be given as `2^31 - 1`.\n \nFill each empty room with the distance to its **neare...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9458, "level": 1, "question": "You are given a matrix `rooms` representing a 2D grid of rooms where:\n- `-1` represents a wall or an obstacle.\n- `0` represents a gate.\n- `INF` represents an empty room. It's guaranteed that `INF` will be given as `2^31 - 1`.\n \nFill each empty ro...
def best_string_reversal(s: str) -> str: return s[::-1]
simplelr_Data_Structure
[ { "content": "Question:\n### Context\nYou are tasked with designing a function that reverses a string using an efficient and clear approach while handling all common edge cases.\n\n### Problem Statement\nWrite a function, `best_string_reversal(s: str) -> str`, that reverses the given input string `s` while ensu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9459, "level": 1, "question": "### Context\nYou are tasked with designing a function that reverses a string using an efficient and clear approach while handling all common edge cases.\n\n### Problem Statement\nWrite a function, `best_string_reversal(s: str) -> str`, that reverses th...
def findUniqueElement(nums): seen_once = set() seen_twice = set() for num in nums: if num in seen_once: seen_once.remove(num) seen_twice.add(num) elif num in seen_twice: seen_twice.remove(num) else: seen_once.add(num) return next(it...
simplelr_Codeforces
[ { "content": "Question:\nYou are given an array of integers where each element appears exactly three times, except for one element which appears exactly once. Your task is to find the element that appears only once.\n\nWrite a function `findUniqueElement(nums)` that takes a list of integers `nums` and returns t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9460, "level": 1, "question": "You are given an array of integers where each element appears exactly three times, except for one element which appears exactly once. Your task is to find the element that appears only once.\n\nWrite a function `findUniqueElement(nums)` that takes a li...
def vowels_minus_consonants(s): vowels = 0 consonants = 0 for c in s: if c.isalpha(): lower_c = c.lower() if lower_c in {'a', 'e', 'i', 'o', 'u'}: vowels += 1 else: consonants += 1 return vowels - consonants
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as an argument and returns the number of vowels minus the number of consonants in the string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9461, "level": 1, "question": "Create a function that takes a string as an argument and returns the number of vowels minus the number of consonants in the string.", "split": "train" }
def find_last_occurrence(nums, target): last_index = -1 for i, num in enumerate(nums): if num == target: last_index = i return last_index
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `nums` and an integer `target`, return _the index of the **last** occurrence of_ `target` _in_ `nums`. _If_ `target` _is not present in_ `nums`, _return_ `-1`. _The array_ `nums` _is not necessarily sorted_.\nAnswer:\nLet's think step by step.\n", "role": ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9462, "level": 1, "question": "Given an array of integers `nums` and an integer `target`, return _the index of the **last** occurrence of_ `target` _in_ `nums`. _If_ `target` _is not present in_ `nums`, _return_ `-1`. _The array_ `nums` _is not necessarily sorted_.", "split": "tra...
def count_unique_elements(lst): return len(set(lst))
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers and returns the number of unique elements in the list. For example, if the list is [1, 2, 2, 3, 3, 4, 4, 4, 5], the function should return 5, since there are 5 unique elements (1, 2, 3, 4, 5).\nAnswer:\nLet's think step by step.\n", "r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9463, "level": 1, "question": "Create a function that takes a list of integers and returns the number of unique elements in the list. For example, if the list is [1, 2, 2, 3, 3, 4, 4, 4, 5], the function should return 5, since there are 5 unique elements (1, 2, 3, 4, 5).", "split"...
from typing import List def longest_consecutive_subsequence(numbers: List[int]) -> int: if not numbers: return 0 num_set = set(numbers) max_length = 0 for num in numbers: if (num - 1) not in num_set: current_length = 1 current = num while (c...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Longest Consecutive Subsequence\n\nYou have been hired as a software engineer by a data analytics company. One of your tasks is to analyze sequences of integers to find the longest consecutive subsequence. A consecutive subsequence is a sequence in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9464, "level": 1, "question": "### Coding Assessment Question\n\n#### Longest Consecutive Subsequence\n\nYou have been hired as a software engineer by a data analytics company. One of your tasks is to analyze sequences of integers to find the longest consecutive subsequence. A conse...
def filter_names_by_age(people): return [person['name'] for person in people if person['age'] > 30]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in a list of dictionaries, where each dictionary represents a person's information. Each dictionary contains keys 'name' and 'age'. The function should return a list of names where the age of the person is greater than 30.\nAnswer:\nLet's think step by step....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9465, "level": 1, "question": "Create a function that takes in a list of dictionaries, where each dictionary represents a person's information. Each dictionary contains keys 'name' and 'age'. The function should return a list of names where the age of the person is greater than 30."...
def maxSumSubarray(arr): n = len(arr) if n == 0: return 0 # though per constraints, n >=1 # Compute max_no_removal using Kadane's algorithm max_no_removal = current_max = arr[0] for i in range(1, n): current_max = max(arr[i], current_max + arr[i]) if current_max > max_n...
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers, return the maximum sum of any non-empty subarray with at most one element removed. A subarray is a contiguous part of an array. \n\nExample 1:\nInput:\narr = [1, -2, 0, 3]\nOutput: 4\nExplanation: \n* Subarray with no elements removed: [1, -2, 0, 3] with sum ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9466, "level": 1, "question": "Given an array of integers, return the maximum sum of any non-empty subarray with at most one element removed. A subarray is a contiguous part of an array. \n\nExample 1:\nInput:\narr = [1, -2, 0, 3]\nOutput: 4\nExplanation: \n* Subarray with no elemen...
def longest_common_subsequence(record1, record2): n = len(record1) m = len(record2) # Create a DP table to store lengths of the longest common subsequence dp = [[0] * (m + 1) for _ in range(n + 1)] # Fill the DP table for i in range(1, n + 1): for j in range(1, m + 1): ...
simplelr_Algorithm
[ { "content": "Question:\n## Coding Assessment Question\n\n**Scenario**: Your organization is developing a software solution that involves working with a large set of records. To optimize data storage and ensure quick retrieval, it is essential to identify the longest subsequence that appears in at least two set...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9467, "level": 1, "question": "## Coding Assessment Question\n\n**Scenario**: Your organization is developing a software solution that involves working with a large set of records. To optimize data storage and ensure quick retrieval, it is essential to identify the longest subsequen...
def is_balanced(labels: list) -> bool: """ Determines if the given list of labels is balanced with equal numbers of 1s and -1s. Args: labels (list): A list of integers where each element is either 1 or -1. Returns: bool: True if the number of 1s equals the number of -1s, False otherwis...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Context\nYou are part of a team developing a new AI-based data validation system. One of the foundational tasks is to verify if the given dataset's labels are balanced. For this purpose, you need to implement a function that determines if a dataset...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9468, "level": 1, "question": "### Coding Assessment Question\n\n#### Context\nYou are part of a team developing a new AI-based data validation system. One of the foundational tasks is to verify if the given dataset's labels are balanced. For this purpose, you need to implement a fu...
import grp from typing import List def get_user_groups(username: str) -> List[str]: try: groups = grp.getgrall() return [group.gr_name for group in groups if username in group.gr_mem] except Exception: return []
simplelr_Docs
[ { "content": "Question:\n## Coding Assessment Question\n\n### Objective\nDemonstrate your understanding and ability to work with Unix group database entries using the \"grp\" module in Python.\n\n### Problem Statement\n\nYou are tasked with implementing a function that takes a user name and returns a list of gr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9469, "level": 1, "question": "## Coding Assessment Question\n\n### Objective\nDemonstrate your understanding and ability to work with Unix group database entries using the \"grp\" module in Python.\n\n### Problem Statement\n\nYou are tasked with implementing a function that takes a...
def reverse_words(s): return ' '.join(s.split()[::-1])
simplelr_Taco
[ { "content": "Question:\nWrite a function ```reverseWords```(C# ```ReverseWords```, Python ```reverse_words```) that takes a string containing a sentence and returns a new string with the words in reverse order. Words are defined as sequences of characters separated by spaces. The input string will not have lea...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9470, "level": 1, "question": "Write a function ```reverseWords```(C# ```ReverseWords```, Python ```reverse_words```) that takes a string containing a sentence and returns a new string with the words in reverse order. Words are defined as sequences of characters separated by spaces....
from collections import Counter import math def sentence_similarity(sentence1, sentence2): # Preprocess the sentences into words words1 = sentence1.lower().split() words2 = sentence2.lower().split() # Handle empty sentences if not words1 and not words2: return 1.0 if not words1 or ...
simplelr_Filter
[ { "content": "Question:\nDevelop a programming function capable of assessing the similarity ratio between two provided sentences, premised on comparing word frequency and order in each. Subsequently, this function should yield a quantitative result ranging from zero to one, implying a complete mismatch and perf...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9471, "level": 1, "question": "Develop a programming function capable of assessing the similarity ratio between two provided sentences, premised on comparing word frequency and order in each. Subsequently, this function should yield a quantitative result ranging from zero to one, im...
def sum_of_series(n): return 2 ** (n + 1) - 1
simplelr_Prefill
[ { "content": "Question:\nCreate a function that computes the sum of the series \\(2^0 + 2^1 + 2^2 + \\ldots + 2^n\\). The function should be implemented in Python and should take one argument, \\(n\\). It should return the sum of the series up to \\(2^n\\). The function should handle large values of \\(n\\) eff...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9472, "level": 1, "question": "Create a function that computes the sum of the series \\(2^0 + 2^1 + 2^2 + \\ldots + 2^n\\). The function should be implemented in Python and should take one argument, \\(n\\). It should return the sum of the series up to \\(2^n\\). The function should...
def reverse_case(s): return s.swapcase()
simplelr_Filter
[ { "content": "Question:\nI need to create a Python function that can reverse the case of each character in a given string. How can I do this?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9473, "level": 1, "question": "I need to create a Python function that can reverse the case of each character in a given string. How can I do this?", "split": "train" }
from typing import List def optimized_shell_sort(arr: List[int]) -> List[int]: if not arr: return [] arr = arr.copy() n = len(arr) gaps = [] m = 1 # Generate Hibbard gaps while True: gap = 2 ** m - 1 if gap >= n: break gaps.append(gap) m +...
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario\nYou have recently joined a team working on a project to optimize sorting algorithms for a real-time data processing system. One of the core tasks is to efficiently sort incoming data which may vary significantly in size and content. \n\n### Task\nImplement an optimized ver...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9474, "level": 1, "question": "### Scenario\nYou have recently joined a team working on a project to optimize sorting algorithms for a real-time data processing system. One of the core tasks is to efficiently sort incoming data which may vary significantly in size and content. \n\n#...
from PIL import Image import os def generate_thumbnail(image_path: str, size: tuple) -> str: if not os.path.exists(image_path): return "File not found." try: img = Image.open(image_path) img.thumbnail(size) base, ext = os.path.splitext(image_path) new_path = f"{base}_thu...
simplelr_Package
[ { "content": "Question:\nIn this problem, you need to write a Python function called `generate_thumbnail` that generates a thumbnail image from a larger image. Use the Python Imaging Library (PIL), also known as `Pillow`, for this task. Your function should take an image file path and thumbnail size tuple as ar...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9475, "level": 1, "question": "In this problem, you need to write a Python function called `generate_thumbnail` that generates a thumbnail image from a larger image. Use the Python Imaging Library (PIL), also known as `Pillow`, for this task. Your function should take an image file ...
from bs4 import BeautifulSoup def extract_headings(html): soup = BeautifulSoup(html, 'html.parser') headings = soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) return [h.text.strip() if h.text else '' for h in headings]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to extract text from HTML and return a list of all headings in the HTML (H1 to H6).\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9476, "level": 1, "question": "Write a python function to extract text from HTML and return a list of all headings in the HTML (H1 to H6).", "split": "train" }
def find_zero_in_degree_nodes(num_nodes: int, edges: list) -> list: in_degree = [0] * num_nodes for u, v in edges: in_degree[v] += 1 result = [i for i in range(num_nodes) if in_degree[i] == 0] return result
simplelr_Algorithm
[ { "content": "Question:\n**Question**: Given a directed graph, implement a function to find all nodes with no incoming edges (i.e., zero in-degree) using an efficient graph traversal algorithm.\n\n### Details\n- **Input**:\n - `num_nodes`: An integer representing the number of nodes in the graph.\n - `edges`:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9477, "level": 1, "question": "**Question**: Given a directed graph, implement a function to find all nodes with no incoming edges (i.e., zero in-degree) using an efficient graph traversal algorithm.\n\n### Details\n- **Input**:\n - `num_nodes`: An integer representing the number o...
def find_dominant_elements(nums): if not nums: return [] res = [] current_max = nums[-1] res.append(current_max) for i in range(len(nums) - 2, -1, -1): if nums[i] > current_max: res.append(nums[i]) current_max = nums[i] return res[::-1]
simplelr_Leetcode
[ { "content": "Question:\nYou are given an integer array `nums`. An element in the array is defined as a **dominant element** if it is greater than all elements to its right. Return an array of all the **dominant elements** in the same order as they appear in `nums`. For example, if `nums` is `[16, 17, 4, 3, 5, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9478, "level": 1, "question": "You are given an integer array `nums`. An element in the array is defined as a **dominant element** if it is greater than all elements to its right. Return an array of all the **dominant elements** in the same order as they appear in `nums`. For exampl...
import math def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False sqrt_n = math.sqrt(n) for i in range(3, int(sqrt_n) + 1, 2): if n % i == 0: return False return True
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to check if a given number is a prime number. The function should return `True` if the number is prime, otherwise `False`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9479, "level": 1, "question": "Write a Python function to check if a given number is a prime number. The function should return `True` if the number is prime, otherwise `False`.", "split": "train" }
def find_largest_and_smallest(numbers): if not numbers: return None, None elif len(numbers) == 1: return (numbers[0], numbers[0]) else: return (max(numbers), min(numbers))
simplelr_Filter
[ { "content": "Question:\nWrite a program in Python that takes a list of numbers and returns the largest and the smallest number in the list. The program should be able to handle an empty list and should return `None` in such a case for both the largest and smallest numbers. Additionally, the program should be a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9480, "level": 1, "question": "Write a program in Python that takes a list of numbers and returns the largest and the smallest number in the list. The program should be able to handle an empty list and should return `None` in such a case for both the largest and smallest numbers. Ad...
def generate_permutations(strings: list[str]) -> list[list[str]]: """ Generates all possible permutations of a given list of strings using recursion. Parameters: strings (list[str]): A list of strings to generate permutations for. Returns: list[list[str]]: A list containing all possible permut...
simplelr_Algorithm
[ { "content": "Question:\n### Question Description\nGiven a list of strings, your task is to write a Python function that returns a list of all possible permutations of the strings. Use recursion to solve this problem and ensure your implementation handles edge cases gracefully.\n\n### Function Signature\n```pyt...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9481, "level": 1, "question": "### Question Description\nGiven a list of strings, your task is to write a Python function that returns a list of all possible permutations of the strings. Use recursion to solve this problem and ensure your implementation handles edge cases gracefully...
def find_palindromes(strings: list) -> list: return [s for s in strings if s == s[::-1]]
simplelr_Evol
[ { "content": "Question:\nWrite a program that takes a list of strings and returns a new list containing only the palindromic strings from the original list. A palindromic string is a string that reads the same backward as forward. For example, 'level' and 'rotor' are palindromes, while 'test' is not. Implement ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9482, "level": 1, "question": "Write a program that takes a list of strings and returns a new list containing only the palindromic strings from the original list. A palindromic string is a string that reads the same backward as forward. For example, 'level' and 'rotor' are palindrom...
def find_duplicates(lst: list) -> dict: element_indices = {} for index, elem in enumerate(lst): if elem in element_indices: element_indices[elem].append(index) else: element_indices[elem] = [index] duplicates = {k: v for k, v in element_indices.items() if len(v) >= 2}...
simplelr_Algorithm
[ { "content": "Question:\n## Context\n\nIn many data processing tasks, it becomes useful to identify duplicates within a list and their positions. In programming, creating an efficient way to not only detect duplicates but also track their occurrences can be crucial, especially when dealing with large datasets.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9483, "level": 1, "question": "## Context\n\nIn many data processing tasks, it becomes useful to identify duplicates within a list and their positions. In programming, creating an efficient way to not only detect duplicates but also track their occurrences can be crucial, especially...
def bubble_sort(data): data_copy = data.copy() n = len(data_copy) for i in range(n): swapped = False for j in range(0, n - i - 1): if data_copy[j] > data_copy[j+1]: # Swap elements data_copy[j], data_copy[j+1] = data_copy[j+1], data_copy[j] ...
simplelr_Filter
[ { "content": "Question:\nCan you generate an implementation of a bubble sort algorithm in Python? It would be great if you could also explain how it works.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9484, "level": 1, "question": "Can you generate an implementation of a bubble sort algorithm in Python? It would be great if you could also explain how it works.", "split": "train" }
def sum_of_squares(lst): total = 0 for num in lst: total += num ** 2 return total # Test the function numbers = [1, 2, 3, 4, 5] result = sum_of_squares(numbers) print(result) # Output should be 55
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of integers and returns the sum of the squares of the integers. Use a for loop to iterate through the list and calculate the sum of squares. Then, call the function with the list [1, 2, 3, 4, 5] and print the result.\nAnswer:\nLet's think step b...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9485, "level": 1, "question": "Write a Python function that takes a list of integers and returns the sum of the squares of the integers. Use a for loop to iterate through the list and calculate the sum of squares. Then, call the function with the list [1, 2, 3, 4, 5] and print the r...
def count_unique_characters(strings): result = [] for s in strings: unique_count = len(set(s)) result.append(unique_count) return result
simplelr_Evol
[ { "content": "Question:\nDevelop a function in Python that accepts a list of strings and returns a list of integers. Each integer represents the number of unique characters in the corresponding string from the input list. For example, given `[\"hello\", \"world\", \"python\"]`, the output should be `[4, 5, 6]` ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9486, "level": 1, "question": "Develop a function in Python that accepts a list of strings and returns a list of integers. Each integer represents the number of unique characters in the corresponding string from the input list. For example, given `[\"hello\", \"world\", \"python\"]`...
from datetime import datetime from typing import List, Tuple def find_overdue_books(current_date: str, books: List[Tuple[str, str]]) -> List[str]: current = datetime.strptime(current_date, "%Y-%m-%d %H:%M") overdue_books = [] for book in books: book_id, due_str = book due = datetime.strptim...
simplelr_Code_Contests
[ { "content": "Question:\nA university library system needs an efficient way of tracking overdue books. Each book has a unique identifier and a due date. The library system manager wants a function that takes in the current date and a list of books, then returns a list of book identifiers that are overdue.\n\nDu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9487, "level": 1, "question": "A university library system needs an efficient way of tracking overdue books. Each book has a unique identifier and a due date. The library system manager wants a function that takes in the current date and a list of books, then returns a list of book ...
def analyze_string(s: str) -> dict: stats = { 'length': 0, 'num_vowels': 0, 'num_consonants': 0, 'num_digits': 0, 'num_special_chars': 0 } vowels = {'a', 'e', 'i', 'o', 'u'} for c in s: if c.lower() in vowels: stats['num_vowels'] += 1 e...
simplelr_Evol
[ { "content": "Question:\nWrite a function `analyze_string(s: str) -> dict` that takes a string as input and returns a dictionary with the following statistics:\n- `length`: The length of the string.\n- `num_vowels`: The number of vowels in the string.\n- `num_consonants`: The number of consonants in the string....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9488, "level": 1, "question": "Write a function `analyze_string(s: str) -> dict` that takes a string as input and returns a dictionary with the following statistics:\n- `length`: The length of the string.\n- `num_vowels`: The number of vowels in the string.\n- `num_consonants`: The ...
def fibonacci(n): if n == 1: return [0] fib = [0, 1] for i in range(2, n): fib.append(fib[i-1] + fib[i-2]) return fib
simplelr_Apps
[ { "content": "Question:\nWrite a function that accepts an integer `n` as input and returns a list containing the fibonacci sequence up to the `n`th term.\n\n# Requirements\n- Your function should handle values of `n` >= 1.\n- The fibonacci sequence is defined as:\n - The first two numbers are 0 and 1.\n - Eac...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9489, "level": 1, "question": "Write a function that accepts an integer `n` as input and returns a list containing the fibonacci sequence up to the `n`th term.\n\n# Requirements\n- Your function should handle values of `n` >= 1.\n- The fibonacci sequence is defined as:\n - The firs...
def evaluate(s): tokens = s.split() # Process multiplication and division first while True: has_op = any(token in ('*', '/') for token in tokens) if not has_op: break for i in range(len(tokens)): if tokens[i] in ('*', '/'): a = float(token...
simplelr_Taco
[ { "content": "Question:\nYou are tasked with building a simple calculator that can evaluate basic arithmetic expressions involving addition, subtraction, multiplication, and division.\n\nThe calculator should accept a string containing a valid mathematical expression and return the result as a float. The expres...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9490, "level": 1, "question": "You are tasked with building a simple calculator that can evaluate basic arithmetic expressions involving addition, subtraction, multiplication, and division.\n\nThe calculator should accept a string containing a valid mathematical expression and retur...
def reverse_string(s: str) -> str: lst = list(s) i = 0 j = len(lst) - 1 while i < j: lst[i], lst[j] = lst[j], lst[i] i += 1 j -= 1 return ''.join(lst)
simplelr_Data_Structure
[ { "content": "Question:\n### Problem Description\n\nYou are tasked with writing a function to reverse a string using a strict iterative approach. This means you cannot use any built-in functions or slicing techniques that directly reverse the string. Instead, implement the reversal by swapping characters within...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9491, "level": 1, "question": "### Problem Description\n\nYou are tasked with writing a function to reverse a string using a strict iterative approach. This means you cannot use any built-in functions or slicing techniques that directly reverse the string. Instead, implement the rev...
def reverse_string(input_str): return input_str[::-1]
simplelr_Filter
[ { "content": "Question:\n# Define a function `reverse_string` that takes a string as input and returns the reversed string.\n\nHere is a Python solution for the task above:\n```python\ndef reverse_string(input_str):\n reversed_str = \"\"\n for char in input_str:\n reversed_str = char + reversed_str...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9492, "level": 1, "question": "# Define a function `reverse_string` that takes a string as input and returns the reversed string.\n\nHere is a Python solution for the task above:\n```python\ndef reverse_string(input_str):\n reversed_str = \"\"\n for char in input_str:\n ...
def celsius_to_fahrenheit(temperatures): return [round((t * 9/5) + 32, 1) for t in temperatures]
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to convert a list of temperatures from Celsius to Fahrenheit. Each temperature should be rounded to one decimal place.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9493, "level": 1, "question": "Write a Python function to convert a list of temperatures from Celsius to Fahrenheit. Each temperature should be rounded to one decimal place.", "split": "train" }
def union_sorted_arrays(arr1, arr2): # Combine both arrays combined = arr1 + arr2 # Convert to a set to remove duplicates unique_set = set(combined) # Convert back to a sorted list sorted_unique = sorted(unique_set) return sorted_unique
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the union of two sorted arrays. The function should be able to handle different scenarios such as arrays with different sizes, repeated numbers, and arrays that are not sorted. If the arrays are not sorted, the function should convert them to sorted before findi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9494, "level": 1, "question": "Write a function to find the union of two sorted arrays. The function should be able to handle different scenarios such as arrays with different sizes, repeated numbers, and arrays that are not sorted. If the arrays are not sorted, the function should ...
def compress_path(path): if not path: return '' directories = [part for part in path.split('/') if part] if not directories: return '' result = [] current = directories[0] count = 1 for dir in directories[1:]: if dir == current: count += 1 else: ...
simplelr_Taco
[ { "content": "Question:\n## Background:\n\nYou have recently joined a team that is developing a new file system. One of your tasks is to implement a compact method for encoding file paths.\n\nIn this file system, each path consists of directories and sub-directories, which are represented as a string of directo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9495, "level": 1, "question": "## Background:\n\nYou have recently joined a team that is developing a new file system. One of your tasks is to implement a compact method for encoding file paths.\n\nIn this file system, each path consists of directories and sub-directories, which are...
def extract_odd_numbers(lst): if not isinstance(lst, list): return [] result = [] for item in lst: if type(item) is not int: return [] if item % 2 != 0: result.append(item) return result
simplelr_Filter
[ { "content": "Question:\nWrite a Python function which accepts a list of integers and returns the odd numbers from that list. However, the function should also handle possible exceptions like non-integer values in the list and return empty list if the list is not valid.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9496, "level": 1, "question": "Write a Python function which accepts a list of integers and returns the odd numbers from that list. However, the function should also handle possible exceptions like non-integer values in the list and return empty list if the list is not valid.", "s...
def count_pairs(nums, target): if target == 0: count_zero = 0 for num in nums: if num == 0: count_zero += 1 count_non_zero = len(nums) - count_zero return (count_zero * (count_zero - 1)) // 2 + count_zero * count_non_zero else: freq = {} ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of **n** integers `nums` and an integer `target`. Return _the number of distinct pairs `(i, j)` where `0 <= i < j < n` and `nums[i] * nums[j] == target`._\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9497, "level": 1, "question": "You are given an array of **n** integers `nums` and an integer `target`. Return _the number of distinct pairs `(i, j)` where `0 <= i < j < n` and `nums[i] * nums[j] == target`._", "split": "train" }
def most_frequent_product(transactions: list) -> str: counts = {} first_occur = {} for index, product in enumerate(transactions): if product not in counts: counts[product] = 1 first_occur[product] = index else: counts[product] += 1 max_count ...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n**Context**:\nYou have been asked to develop a function for a system that processes customer transactions. One of the requirements is to determine the most frequently sold product. The input is a list of product names representing transactions.\n\n**Obj...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9498, "level": 1, "question": "### Coding Assessment Question\n\n**Context**:\nYou have been asked to develop a function for a system that processes customer transactions. One of the requirements is to determine the most frequently sold product. The input is a list of product names ...
def keyboard_words(words): row1 = set("qwertyuiop") row2 = set("asdfghjkl") row3 = set("zxcvbnm") result = [] for item in words: if isinstance(item, str) and item: # Ensure it's a non-empty string word_lower = item.lower() if all(c in row1 for c in word_lower): ...
simplelr_Evol
[ { "content": "Question:\nDesign a Python function that takes a list of words and returns a list of words that can be typed using letters of only one row of a standard QWERTY keyboard. The rows on the keyboard are:\n\n- Row 1: \"qwertyuiop\"\n- Row 2: \"asdfghjkl\"\n- Row 3: \"zxcvbnm\"\n\nThe function should be...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9499, "level": 1, "question": "Design a Python function that takes a list of words and returns a list of words that can be typed using letters of only one row of a standard QWERTY keyboard. The rows on the keyboard are:\n\n- Row 1: \"qwertyuiop\"\n- Row 2: \"asdfghjkl\"\n- Row 3: \"...