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_even_numbers(arr): """ Returns the sum of all even integers in the given array. Args: arr: An iterable containing integers. Returns: An integer representing the sum of all even integers in the array. """ sum_even = 0 try: for num in arr: ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an array of integers and returns the sum of all even numbers in the array. In Python, how would you define such a function, and what precautions would you take to ensure it handles potential errors effectively?\nAnswer:\nLet's think step by step.\n", "ro...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8800, "level": 1, "question": "Create a function that takes an array of integers and returns the sum of all even numbers in the array. In Python, how would you define such a function, and what precautions would you take to ensure it handles potential errors effectively?", "split":...
def maximum_product_of_three(nums): if len(nums) < 3: return None nums.sort() candidate1 = nums[-1] * nums[-2] * nums[-3] candidate2 = nums[0] * nums[1] * nums[-1] return max(candidate1, candidate2)
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes a list of integers and returns the maximum product that can be obtained by multiplying any three distinct numbers from the list. If the list contains fewer than three integers, the function should return None.\nAnswer:\nLet's think step by step.\n", "role...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8801, "level": 1, "question": "Write a function that takes a list of integers and returns the maximum product that can be obtained by multiplying any three distinct numbers from the list. If the list contains fewer than three integers, the function should return None.", "split": "...
from collections import Counter from typing import List def findLHS(nums: List[int]) -> int: freq = Counter(nums) max_len = 0 for num in freq: if (num + 1) in freq: current = freq[num] + freq[num + 1] if current > max_len: max_len = current return max_len
simplelr_Algorithm
[ { "content": "Question:\n### Problem: Find the Longest Harmonious Subsequence\n\nYou are given an integer array 'nums'. A harmonious subsequence of a sequence is one where the difference between its maximum value and its minimum value is exactly 1.\n\nYour task is to write a program that finds the length of the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8802, "level": 1, "question": "### Problem: Find the Longest Harmonious Subsequence\n\nYou are given an integer array 'nums'. A harmonious subsequence of a sequence is one where the difference between its maximum value and its minimum value is exactly 1.\n\nYour task is to write a p...
def nth_term_of_sequence(n: int) -> int: """ This function returns the nth term of the sequence defined as specified. """ return 3 ** (n - 1)
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n**Context**:\nA sequence of integers is defined as follows: the first term is 1, and each subsequent term is twice the sum of all previous terms plus 1. More formally, the sequence is \\( a_1 = 1 \\), and \\( a_n = 2 \\times (a_1 + a_2 + \\ldots + a_{n-...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8803, "level": 1, "question": "### Coding Assessment Question\n\n**Context**:\nA sequence of integers is defined as follows: the first term is 1, and each subsequent term is twice the sum of all previous terms plus 1. More formally, the sequence is \\( a_1 = 1 \\), and \\( a_n = 2 \...
def find_valley_points(grid: list[list[int]]) -> list[tuple[int, int]]: m = len(grid) if m == 0: return [] result = [] for i in range(m): row_length = len(grid[i]) for j in range(row_length): current = grid[i][j] is_valley = True for dx, dy in ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are given a two-dimensional grid of integers representing elevations, where each cell in the grid represents the elevation at that location. Your task is to implement a function that identifies the \"valley points\" in the grid. A valley point is defined as ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8804, "level": 1, "question": "### Problem Statement\n\nYou are given a two-dimensional grid of integers representing elevations, where each cell in the grid represents the elevation at that location. Your task is to implement a function that identifies the \"valley points\" in the ...
def schedule_event(device_schedule, device, event_time): # Split the event_time into hours and minutes parts = event_time.split(':') if len(parts) != 2: return "Unable to schedule event" for part in parts: if len(part) != 2 or not part.isdigit(): return "Unable to schedule ev...
simplelr_Apps
[ { "content": "Question:\nYou are hired to develop a new scheduling feature for a smart home application. The application should allow users to schedule their smart devices to turn on or off at specific times throughout the day. However, due to hardware limitations, each device can only have up to 10 scheduled e...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8805, "level": 1, "question": "You are hired to develop a new scheduling feature for a smart home application. The application should allow users to schedule their smart devices to turn on or off at specific times throughout the day. However, due to hardware limitations, each device...
def min_operations(s1, s2): m = len(s1) n = len(s2) # Create a table with (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 for j in range(n + 1): dp[0][j] = ...
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python function to find the minimum number of operations needed to make two strings equal by either inserting, deleting, or replacing characters? This is similar to finding the Levenshtein distance between two strings.\nAnswer:\nLet's think step by step.\n", "role"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8806, "level": 1, "question": "Can you provide a Python function to find the minimum number of operations needed to make two strings equal by either inserting, deleting, or replacing characters? This is similar to finding the Levenshtein distance between two strings.", "split": "t...
def strings_ending_with_ing(strings): """ Returns a list of strings that end with 'ing'. Args: strings (list): A list of strings. Returns: list: A list of strings that end with 'ing'. """ result = [] for s in strings: if s.endswith('ing'): result...
simplelr_Filter
[ { "content": "Question:\n### Integers Divisible by 3\nGiven an array of integers, create a function that returns a list of all integers in the array that are divisible by 3.\n\n#### Example Use Cases\n\n* Input: `[1, 2, 3, 4, 5, 6, 7, 8, 9]`\nOutput: `[3, 6, 9]`\n* Input: `[10, 15, 21, 30, 45, 50]`\nOutput: `[1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8807, "level": 1, "question": "### Integers Divisible by 3\nGiven an array of integers, create a function that returns a list of all integers in the array that are divisible by 3.\n\n#### Example Use Cases\n\n* Input: `[1, 2, 3, 4, 5, 6, 7, 8, 9]`\nOutput: `[3, 6, 9]`\n* Input: `[10...
def tuples_to_dicts(tuple_list): return [{k: v} for k, v in tuple_list]
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that takes a list of tuples and returns a list of dictionaries with each tuple converted to a dictionary? This function should assume that the first element of each tuple is the key and the second element is the value.\nAnswer:\nLet's think step by ste...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8808, "level": 1, "question": "How can I create a Python function that takes a list of tuples and returns a list of dictionaries with each tuple converted to a dictionary? This function should assume that the first element of each tuple is the key and the second element is the value...
def to_custom_binary(n): if n == 0: return '0b0_bin' sign = '-' if n < 0 else '' binary = bin(abs(n))[2:] # Convert absolute value to binary and strip '0b' return f'0b{sign}{binary}_bin'
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a single input, an integer, and returns its binary representation as a string, but with a prefix '0b' and a suffix '_bin'. The function should handle positive and negative integers, and return '0b0_bin' for zero.\nAnswer:\nLet's think step by step.\n", "...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8809, "level": 1, "question": "Create a function that takes a single input, an integer, and returns its binary representation as a string, but with a prefix '0b' and a suffix '_bin'. The function should handle positive and negative integers, and return '0b0_bin' for zero.", "split...
from collections import Counter def min_anagram_deletions(word1, word2): count1 = Counter(word1) count2 = Counter(word2) all_chars = set(count1.keys()).union(set(count2.keys())) total_deletions = 0 for char in all_chars: total_deletions += abs(count1.get(char, 0) - count2.get(char, 0)) ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given two strings `word1` and `word2` consisting of lowercase English letters. You can perform the following operation on either word any number of times: choose any character and delete it. Find the minimum number of operations required to make `word1` and `word2` anagrams of e...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8810, "level": 1, "question": "You are given two strings `word1` and `word2` consisting of lowercase English letters. You can perform the following operation on either word any number of times: choose any character and delete it. Find the minimum number of operations required to mak...
def sum_of_subarrays(arr, k): n = len(arr) if n == 0 or k == 0 or k > n: return 0 current_sum = sum(arr[:k]) total = current_sum for i in range(k, n): current_sum += arr[i] - arr[i - k] total += current_sum return total
simplelr_Apps
[ { "content": "Question:\nGiven a list of integers, find the sum of all the contiguous subarrays within the list which have a length exactly equal to a given integer k.\n\nExample 1:\nInput: arr = [1, 2, 3, 4, 5], k = 2\nOutput: 14\nExplanation: The subarrays of length 2 are [1, 2], [2, 3], [3, 4], and [4, 5]. T...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8811, "level": 1, "question": "Given a list of integers, find the sum of all the contiguous subarrays within the list which have a length exactly equal to a given integer k.\n\nExample 1:\nInput: arr = [1, 2, 3, 4, 5], k = 2\nOutput: 14\nExplanation: The subarrays of length 2 are [1...
def sum_of_squares(n): total = 0 for i in range(1, n+1): total += i ** 2 return total
simplelr_Filter
[ { "content": "Question:\nIn the context of a programming problem, how can we calculate the sum of the squares of the first n natural numbers in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8812, "level": 1, "question": "In the context of a programming problem, how can we calculate the sum of the squares of the first n natural numbers in Python?", "split": "train" }
from typing import List def sort_even_before_odd(arr: List[int]) -> List[int]: evens = [] odds = [] for num in arr: if num % 2 == 0: evens.append(num) else: odds.append(num) return evens + odds
simplelr_Evol
[ { "content": "Question:\nDesign an algorithm in Python to sort an array of integers such that all even numbers appear before all odd numbers, while maintaining the original relative order of both even and odd numbers. Provide the function signature as `def sort_even_before_odd(arr: List[int]) -> List[int]:`. De...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8813, "level": 1, "question": "Design an algorithm in Python to sort an array of integers such that all even numbers appear before all odd numbers, while maintaining the original relative order of both even and odd numbers. Provide the function signature as `def sort_even_before_odd...
def flip_bit_longest_seq(num: int) -> int: if num == 0: return 1 binary_str = bin(num)[2:] if all(c == '1' for c in binary_str): return len(binary_str) + 1 padded_str = '0' + binary_str + '0' n = len(padded_str) left_ones = [0] * n for i in range(1, n): ...
simplelr_Data_Structure
[ { "content": "Question:\n**Problem Scenario**:\nYou are tasked with analyzing and improving binary sequences. Given an integer, you need to determine the length of the longest sequence of 1s you could create by flipping exactly one bit from 0 to 1. This task will assess your ability to navigate and manipulate b...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8814, "level": 1, "question": "**Problem Scenario**:\nYou are tasked with analyzing and improving binary sequences. Given an integer, you need to determine the length of the longest sequence of 1s you could create by flipping exactly one bit from 0 to 1. This task will assess your a...
from typing import List, Tuple def top_k_accessed_files(files: List[Tuple[int, int]], k: int) -> List[int]: if not files or k == 0: return [] # Sort the files by descending access count and ascending ID sorted_files = sorted(files, key=lambda x: (-x[1], x[0])) # Extract the top k files top_...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are in charge of managing a storage system that keeps track of digital files. Each file is represented by a unique ID and an access count, which indicates how many times the file has been accessed. You need to implement a system that efficiently retrieves th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8815, "level": 1, "question": "### Problem Statement\n\nYou are in charge of managing a storage system that keeps track of digital files. Each file is represented by a unique ID and an access count, which indicates how many times the file has been accessed. You need to implement a s...
def singleNumber(nums): result = 0 for num in nums: result ^= num return result
simplelr_Code_Contests
[ { "content": "Question:\nA-Θ\n\nYou are given an array of integers where every element appears twice except for one. Find that single one.\n\nThe question is as follows: Given an array of integers nums where each element is in the range [1, 10000] and appears exactly twice except for one element which appears e...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8816, "level": 1, "question": "A-Θ\n\nYou are given an array of integers where every element appears twice except for one. Find that single one.\n\nThe question is as follows: Given an array of integers nums where each element is in the range [1, 10000] and appears exactly twice exc...
def transpose_lists_of_lists(matrix): if not matrix: return [] cols = len(matrix[0]) transposed = [] for j in range(cols): new_row = [row[j] for row in matrix] transposed.append(new_row) return transposed
simplelr_Package
[ { "content": "Question:\nCreate a function `transpose_lists_of_lists(matrix)` that takes a list of lists `matrix` and returns its transpose. The function should not use any external libraries or functions specifically designed to compute the transpose. Instead, it should manually construct the transposed matrix...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8817, "level": 1, "question": "Create a function `transpose_lists_of_lists(matrix)` that takes a list of lists `matrix` and returns its transpose. The function should not use any external libraries or functions specifically designed to compute the transpose. Instead, it should manua...
import itertools from typing import List, Any def list_combinations(input_lists: List[List[Any]]) -> List[List[Any]]: return [list(comb) for comb in itertools.product(*input_lists)]
simplelr_Package
[ { "content": "Question:\nYou are required to write a function `list_combinations` that takes in a list of lists and returns all possible combinations where each combination contains one element from each sublist. This exercise will test your ability to work with nested list structures and basic combinatorial lo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8818, "level": 1, "question": "You are required to write a function `list_combinations` that takes in a list of lists and returns all possible combinations where each combination contains one element from each sublist. This exercise will test your ability to work with nested list st...
def count_flips_to_convert(a: int, b: int) -> int: return bin(a ^ b).count('1')
simplelr_Data_Structure
[ { "content": "Question:\n### Context\nYou're working on a system that synchronizes data between two servers. Each data packet is represented as an integer, and the system uses bit-level operations to detect changes between packets efficiently. To ensure the synchronization process is minimal in data exchange, y...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8819, "level": 1, "question": "### Context\nYou're working on a system that synchronizes data between two servers. Each data packet is represented as an integer, and the system uses bit-level operations to detect changes between packets efficiently. To ensure the synchronization pro...
def check_substring(a, b): return a in b
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check whether the given string `a` is a.substring of `b` or not. If `a` is a substring, return `True`, otherwise return `False`. The function has to be named `check_substring`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8820, "level": 1, "question": "Write a python function to check whether the given string `a` is a.substring of `b` or not. If `a` is a substring, return `True`, otherwise return `False`. The function has to be named `check_substring`.", "split": "train" }
import re def extract_product_prices(filename): products = {} with open(filename, 'r') as file: for line in file: line = line.strip() match = re.search(r'Product: (.*?), Price: (\d+\.?\d*) dollars', line) if match: product = match.group(1) ...
simplelr_Filter
[ { "content": "Question:\nI have a text file containing product descriptions and prices. Each line in the file follows the format: \"Product: <product name>, Price: <price> dollars\". I want to read this file and extract the product names and their corresponding prices into a dictionary. How can I do this in Pyt...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8821, "level": 1, "question": "I have a text file containing product descriptions and prices. Each line in the file follows the format: \"Product: <product name>, Price: <price> dollars\". I want to read this file and extract the product names and their corresponding prices into a d...
def count_string_frequencies(string_list): freq_dict = {} for string in string_list: lower_str = string.lower() if lower_str in freq_dict: freq_dict[lower_str] += 1 else: freq_dict[lower_str] = 1 return freq_dict
simplelr_Filter
[ { "content": "Question:\nThis problem involves creating a function that takes a list of strings and returns a dictionary with the frequency of each string. \n\nBut there's a catch - the function should be able to handle a list of strings which may contain uppercase and lowercase letters, and it should treat 'A'...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8822, "level": 1, "question": "This problem involves creating a function that takes a list of strings and returns a dictionary with the frequency of each string. \n\nBut there's a catch - the function should be able to handle a list of strings which may contain uppercase and lowerca...
def int_to_binary(n): if n < 0: return '-' + bin(n * -1)[2:] else: return bin(n)[2:]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an integer as an input and returns a string representation of a binary number. For example, if the input integer is 5, the output should be \"101\". Make sure the function handles negative integers as well.\nAnswer:\nLet's think step by step.\n", "role":...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8823, "level": 1, "question": "Create a function that takes an integer as an input and returns a string representation of a binary number. For example, if the input integer is 5, the output should be \"101\". Make sure the function handles negative integers as well.", "split": "tr...
def max_distance_with_same_height(nums): first_last = {} for i in range(len(nums)): num = nums[i] if num not in first_last: first_last[num] = [i, i] else: first_last[num][1] = i max_dist = 0 for key in first_last: distance = first_last[key][1] - fi...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a **0-indexed** integer array `nums` representing the heights of a set of pillars. You need to compute the maximum **distance** such that the heights of the pillars at both ends of the distance are the same. The distance between the pillars at indices `i` and `j` is define...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8824, "level": 1, "question": "You are given a **0-indexed** integer array `nums` representing the heights of a set of pillars. You need to compute the maximum **distance** such that the heights of the pillars at both ends of the distance are the same. The distance between the pilla...
def character_count(s): counts = {} for char in s: if char != ' ': counts[char] = counts.get(char, 0) + 1 return counts
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as input and outputs the number of times each character appears in the string. The function should be case-sensitive and should ignore spaces.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8825, "level": 1, "question": "Create a function that takes a string as input and outputs the number of times each character appears in the string. The function should be case-sensitive and should ignore spaces.", "split": "train" }
def string_to_word_list(s): return s.split()
simplelr_Prefill
[ { "content": "Question:\nWrite a function to convert a string into a list of words. The function should handle cases where the string may contain multiple spaces between words, leading or trailing spaces, and should ignore empty strings.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8826, "level": 1, "question": "Write a function to convert a string into a list of words. The function should handle cases where the string may contain multiple spaces between words, leading or trailing spaces, and should ignore empty strings.", "split": "train" }
def calculate_total_sales(sales_data, target_product): total = 0.0 for sale in sales_data: if sale['product'] == target_product: total += sale['price'] * sale['quantity'] return total
simplelr_Package
[ { "content": "Question:\nYou are tasked with creating a function that processes a given list of dictionaries and calculates the total sales for a specified product.\n\nEach dictionary in the list represents a sales entry with the following keys:\n- `product`: The name of the product (string)\n- `price`: The pri...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8827, "level": 1, "question": "You are tasked with creating a function that processes a given list of dictionaries and calculates the total sales for a specified product.\n\nEach dictionary in the list represents a sales entry with the following keys:\n- `product`: The name of the p...
from typing import List def filter_emails(emails: List[str]) -> List[str]: valid_emails = [] for email in emails: parts = email.split('@') if len(parts) != 2: continue local, domain = parts[0], parts[1] # Validate local part if not local: ...
simplelr_Codeforces
[ { "content": "Question:\nImplement a function, filter_emails, that takes a list of email addresses and returns only those that follow specific criteria. An email address must consist of a local part, followed by the \"@\" symbol, and then a domain part. The local part must contain only alphanumeric characters a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8828, "level": 1, "question": "Implement a function, filter_emails, that takes a list of email addresses and returns only those that follow specific criteria. An email address must consist of a local part, followed by the \"@\" symbol, and then a domain part. The local part must con...
from typing import List def can_partition(nums: List[int]) -> bool: total = sum(nums) if total % 2 != 0: return False target = total // 2 dp = {0} for num in nums: for s in list(dp): current_sum = s + num if current_sum == target: return True ...
simplelr_Algorithm
[ { "content": "Question:\n**Array Partitioning for Equal Sums**\n\nYou are given an integer array `nums` containing `n` distinct elements. Write a function to determine if it is possible to partition the array into two subsets such that the sum of elements in both subsets is equal.\n\nImplement the function `can...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8829, "level": 1, "question": "**Array Partitioning for Equal Sums**\n\nYou are given an integer array `nums` containing `n` distinct elements. Write a function to determine if it is possible to partition the array into two subsets such that the sum of elements in both subsets is eq...
def sum_abs_mult_sign(lst): if not lst: return None product = 1 for num in lst: product *= num if product == 0: return 0 sum_abs = sum(abs(num) for num in lst) sign = 1 if product > 0 else -1 return sum_abs * sign
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers and returns the sum of the absolute values of all the integers in the list, multiplied by the sign of the product of all the integers. If the product of all the integers is 0, the function should return 0, regardless of the absolute values...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8830, "level": 1, "question": "Create a function that takes a list of integers and returns the sum of the absolute values of all the integers in the list, multiplied by the sign of the product of all the integers. If the product of all the integers is 0, the function should return 0...
def fibonacci(N): if N == 0: return 0 elif N == 1: return 1 a, b = 0, 1 for i in range(2, N + 1): current = a + b a = b b = current return b
simplelr_Taco
[ { "content": "Question:\nGiven an integer N, write a function to return the N'th term of the Fibonacci series. The Fibonacci sequence is defined as:\nFib(0) = 0,\nFib(1) = 1,\nand Fib(N) = Fib(N-1) + Fib(N-2) for N >= 2.\n\nExample 1:\nInput:\nN = 5\nOutput:\n5\nExplanation:\nThe first six terms of the Fibonacc...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8831, "level": 1, "question": "Given an integer N, write a function to return the N'th term of the Fibonacci series. The Fibonacci sequence is defined as:\nFib(0) = 0,\nFib(1) = 1,\nand Fib(N) = Fib(N-1) + Fib(N-2) for N >= 2.\n\nExample 1:\nInput:\nN = 5\nOutput:\n5\nExplanation:\n...
def isRobotBounded(instructions): # Calculate the net rotation r = instructions.count('R') l = instructions.count('L') delta_rot = (r - l) % 4 # Precompute the displacement for each starting direction v = [[0, 0] for _ in range(4)] for d in range(4): x, y = 0, 0 current_dir ...
simplelr_Codeforces
[ { "content": "Question:\nIn an infinite 2D grid, you are initially positioned at (0, 0). You are given a string `instructions` that consists of only the characters 'G', 'L', and 'R'. 'G' can be interpreted as move forward by one unit, 'L' can be interpreted as turn 90 degrees to the left, and 'R' can be interpr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8832, "level": 1, "question": "In an infinite 2D grid, you are initially positioned at (0, 0). You are given a string `instructions` that consists of only the characters 'G', 'L', and 'R'. 'G' can be interpreted as move forward by one unit, 'L' can be interpreted as turn 90 degrees ...
def flip_secondary_diagonal(matrix): n = len(matrix) for i in range(n): col = n - 1 - i matrix[i][col] = 255 - matrix[i][col] return matrix
simplelr_Filter
[ { "content": "Question:\nAssuming there is a square matrix of size n x n that represents a gray-scale image, write a code snippet to flip the colors of the pixels on the secondary diagonal from black to white and from white to black. The values in the matrix can range from 0 to 255, where 0 represents black and...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8833, "level": 1, "question": "Assuming there is a square matrix of size n x n that represents a gray-scale image, write a code snippet to flip the colors of the pixels on the secondary diagonal from black to white and from white to black. The values in the matrix can range from 0 t...
import re from collections import Counter def most_common_word(text, banned_words): # Tokenize the text into words, lowercase and ignoring case and punctuation tokens = re.findall(r"[a-z']+", text.lower()) # Convert banned words to a set for efficient look-up, in lowercase banned = set(word.lower() for...
simplelr_Package
[ { "content": "Question:\nWrite a function called `most_common_word` that takes in two parameters:\n1. `text`: A string representing a block of text.\n2. `banned_words`: A list of strings representing words that should be excluded from consideration.\n\nThe function should perform the following steps:\n1. Tokeni...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8834, "level": 1, "question": "Write a function called `most_common_word` that takes in two parameters:\n1. `text`: A string representing a block of text.\n2. `banned_words`: A list of strings representing words that should be excluded from consideration.\n\nThe function should perf...
def group_uris_by_resource(uri_list): resource_uris = {} for uri, resource in uri_list: if resource in resource_uris: resource_uris[resource].append(uri) else: resource_uris[resource] = [uri] return resource_uris
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of tuples, where each tuple contains two strings representing a URI and a resource label. The function should return a dictionary where the keys are the resources and the values are lists of URIs that map to each resource. If the list is empty, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8835, "level": 1, "question": "Write a Python function that takes a list of tuples, where each tuple contains two strings representing a URI and a resource label. The function should return a dictionary where the keys are the resources and the values are lists of URIs that map to ea...
def sum_even_numbers(lst): sum_even = 0 for num in lst: if type(num) is not int: raise TypeError("Element is not an integer") if num < 0: raise ValueError("Element is negative") if num % 2 == 0: sum_even += num return sum_even
simplelr_Filter
[ { "content": "Question:\nModify the given Python code to calculate the sum of the given list. However, the program should only include even numbers in the sum. Additionally, ensure that the program raises a ValueError if any element in the list is negative or a TypeError if any element is not an integer.\nAnswe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8836, "level": 1, "question": "Modify the given Python code to calculate the sum of the given list. However, the program should only include even numbers in the sum. Additionally, ensure that the program raises a ValueError if any element in the list is negative or a TypeError if an...
def is_palindrome_number(n): if n < 0: return False reversed_num = 0 original = n while n > 0: digit = n % 10 reversed_num = reversed_num * 10 + digit n = n // 10 return reversed_num == original
simplelr_Filter
[ { "content": "Question:\nIs there a way to check if a number is a palindrome in Python without converting it to a string?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8837, "level": 1, "question": "Is there a way to check if a number is a palindrome in Python without converting it to a string?", "split": "train" }
def repeat_elements(nums, k): result = [] for num in nums: result += [num] * k return result
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `nums` and an integer `k`, arrange the array such that each number in `nums` is repeated `k` times consecutively. The order of the elements should remain the same as the original order in `nums`. Return the modified array. For example, if `nums = [1, 2, 3]` an...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8838, "level": 1, "question": "Given an array of integers `nums` and an integer `k`, arrange the array such that each number in `nums` is repeated `k` times consecutively. The order of the elements should remain the same as the original order in `nums`. Return the modified array. Fo...
from typing import List def array_sum(numbers: List[int]) -> int: return sum(numbers)
simplelr_Apps
[ { "content": "Question:\n## Sum of Array Elements\n\nWrite a function that calculates the sum of all elements in an array. The function should take an array of integers as its parameter and return the total sum of the elements.\n\nFunction signature: `def array_sum(numbers: List[int]) -> int`\n\n### Input\n- An...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8839, "level": 1, "question": "## Sum of Array Elements\n\nWrite a function that calculates the sum of all elements in an array. The function should take an array of integers as its parameter and return the total sum of the elements.\n\nFunction signature: `def array_sum(numbers: Li...
def count_words(word_list): word_counts = {} for word in word_list: lower_word = word.lower() word_counts[lower_word] = word_counts.get(lower_word, 0) + 1 return word_counts
simplelr_Leetcode
[ { "content": "Question:\nWrite a function that takes as input a list of strings, where each string represents a word. The function should return a dictionary where the keys are the words from the input list and the values are the counts of how many times each word appears in the input list. Ensure the words are...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8840, "level": 1, "question": "Write a function that takes as input a list of strings, where each string represents a word. The function should return a dictionary where the keys are the words from the input list and the values are the counts of how many times each word appears in t...
def leading_substrings(string): """ Returns a list of all leading substrings of the input string. Args: string (str): The input string. Returns: list: A list of all leading substrings of the input string. """ substrings = [] for i in range(1, len(string) + 1): substrings.ap...
simplelr_Filter
[ { "content": "Question:\n### Leading Substrings of a String\n\nIf we have a string like `\"abcde\"`, the leading substrings are `\"a\"`, `\"ab\"`, `\"abc\"`, `\"abcd\"`, and `\"abcde\"`.\n\nWrite a function `leading_substrings(string)` that takes a string as input and returns a list of all leading substrings of...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8841, "level": 1, "question": "### Leading Substrings of a String\n\nIf we have a string like `\"abcde\"`, the leading substrings are `\"a\"`, `\"ab\"`, `\"abc\"`, `\"abcd\"`, and `\"abcde\"`.\n\nWrite a function `leading_substrings(string)` that takes a string as input and returns ...
import ast def is_valid_python_expression(s): try: ast.parse(s, mode='eval') return True except SyntaxError: return False
simplelr_Filter
[ { "content": "Question:\nIs there a function in Python to determine if a given string is a valid Python expression or not?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8842, "level": 1, "question": "Is there a function in Python to determine if a given string is a valid Python expression or not?", "split": "train" }
def diagonal_sum(matrix): primary_diagonal_sum = 0 secondary_diagonal_sum = 0 n = len(matrix) for i in range(n): primary_diagonal_sum += matrix[i][i] secondary_diagonal_sum += matrix[i][n - 1 - i] return (primary_diagonal_sum, secondary_diagonal_sum)
simplelr_Apps
[ { "content": "Question:\nGiven a matrix of size N x M (where N is the number of rows and M is the number of columns), implement a function `diagonal_sum(matrix)` that computes the sums of both primary and secondary diagonals.\n\nThe primary diagonal is formed by the elements at positions (i, i) for all valid i,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8843, "level": 1, "question": "Given a matrix of size N x M (where N is the number of rows and M is the number of columns), implement a function `diagonal_sum(matrix)` that computes the sums of both primary and secondary diagonals.\n\nThe primary diagonal is formed by the elements a...
from collections import defaultdict from typing import List, Tuple, Optional def unique_number(stream: List[Tuple[int, str]]) -> Optional[int]: net = defaultdict(int) total_sum = 0 for number, sign in stream: if sign == '+': net[number] += number total_sum += number ...
simplelr_Data_Structure
[ { "content": "Question:\n#### Scenario\nYou have been hired by a data streaming company to implement a real-time monitoring tool. This tool will process streams of transactions represented as tuples where each tuple contains a number and a sign ('+' or '-'). Your task is to determine if the stream is \"1-sparse...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8844, "level": 1, "question": "#### Scenario\nYou have been hired by a data streaming company to implement a real-time monitoring tool. This tool will process streams of transactions represented as tuples where each tuple contains a number and a sign ('+' or '-'). Your task is to de...
def count_capital_words(headline): count = 0 words = headline.split() for word in words: if word and word[0].isupper(): count += 1 return count
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes as input the text of an article headline, and returns the count of words that start with a capital letter. How do I solve this problem using Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8845, "level": 1, "question": "Create a function that takes as input the text of an article headline, and returns the count of words that start with a capital letter. How do I solve this problem using Python?", "split": "train" }
from typing import List def enhanced_shell_sort(arr: List[int]) -> List[int]: arr = list(arr) n = len(arr) if n <= 1: return arr gaps = [] h = 1 while h < n: gaps.append(h) h = 3 * h + 1 gaps.reverse() for gap in gaps: for i in range(gap, n): ...
simplelr_Data_Structure
[ { "content": "Question:\n### Shell Sort Enhanced Version\n\nUsing principles of the provided Shell Sort algorithm, extend its implementation to optimize its performance using the Knuth sequence for gap sizes. Ensure to handle edge cases and provide a stable sort (if possible). \n\n#### Knuth Sequence\nThe optim...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8846, "level": 1, "question": "### Shell Sort Enhanced Version\n\nUsing principles of the provided Shell Sort algorithm, extend its implementation to optimize its performance using the Knuth sequence for gap sizes. Ensure to handle edge cases and provide a stable sort (if possible)....
def is_rotation(s1, s2): if len(s1) != len(s2): return False if len(s1) == 0: return True doubled = s1 + s1 return s2 in doubled
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes two strings as input and checks if the second string is a rotation of the first string. A string is considered a rotation of another if it can be obtained by rotating the other string in a circular manner. For example, \"abc\" is a rotation of \"cba\" by rot...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8847, "level": 1, "question": "Create a function that takes two strings as input and checks if the second string is a rotation of the first string. A string is considered a rotation of another if it can be obtained by rotating the other string in a circular manner. For example, \"ab...
def mergeAndSort(listA, listB): merged = listA + listB return sorted(merged)
simplelr_Apps
[ { "content": "Question:\nWrite a function mergeAndSort that takes two lists of integers as input, merges them into a single list, and then returns the list sorted in non-decreasing order. For example, given the lists [3, 1, 4] and [4, 6, 5], the function should return [1, 3, 4, 4, 5, 6].\nAnswer:\nLet's think s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8848, "level": 1, "question": "Write a function mergeAndSort that takes two lists of integers as input, merges them into a single list, and then returns the list sorted in non-decreasing order. For example, given the lists [3, 1, 4] and [4, 6, 5], the function should return [1, 3, 4...
from typing import List def find_pivot_index(nums: List[int]) -> int: total = sum(nums) left_sum = 0 for i in range(len(nums)): right_sum = total - left_sum - nums[i] if left_sum == right_sum: return i left_sum += nums[i] return -1
simplelr_Algorithm
[ { "content": "Question:\n### Find the Pivot Index\n\nA pivot index of a list of numbers is an index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index. If no such index exists, return -1. If there are multiple pivot indexes, you should return the l...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8849, "level": 1, "question": "### Find the Pivot Index\n\nA pivot index of a list of numbers is an index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index. If no such index exists, return -1. If there are multiple piv...
def replace_chars(string: str, old: str, new: str) -> str: result = [] for char in string: if char == old: result.append(new) else: result.append(char) return ''.join(result)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function `replace_chars(string: str, old: str, new: str) -> str` that takes in a string `string`, and two characters `old` and `new`. The function should replace all occurrences of the character `old` in the string `string` with the character `new` and return the modified...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8850, "level": 1, "question": "Write a Python function `replace_chars(string: str, old: str, new: str) -> str` that takes in a string `string`, and two characters `old` and `new`. The function should replace all occurrences of the character `old` in the string `string` with the char...
def findMaxLengthSubarray(arr, N): s = set(arr) max_len = 0 for num in s: if (num - 1) not in s: current_num = num current_len = 1 while (current_num + 1) in s: current_num += 1 current_len += 1 if current_len > max_len:...
simplelr_Taco
[ { "content": "Question:\nGiven an array `arr[]` of size `N` consisting of distinct integers, write a program that finds the maximum length of the subarray with consecutive elements. The elements can be in any order within the subarray, but must be consecutive when sorted.\n\nExample 1:\nInput:\nN = 4\narr = {1,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8851, "level": 1, "question": "Given an array `arr[]` of size `N` consisting of distinct integers, write a program that finds the maximum length of the subarray with consecutive elements. The elements can be in any order within the subarray, but must be consecutive when sorted.\n\nE...
def unique_elements(lst): seen = set() result = [] for item in lst: if item not in seen: seen.add(item) result.append(item) return result
simplelr_Filter
[ { "content": "Question:\nHow can I create a function that takes a list and returns a new list with unique elements from the original list, preserving the order of their first occurrence?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8852, "level": 1, "question": "How can I create a function that takes a list and returns a new list with unique elements from the original list, preserving the order of their first occurrence?", "split": "train" }
def find_pairs(nums, target): pairs = set() n = len(nums) for i in range(n): for j in range(i + 1, n): a, b = nums[i], nums[j] if a + b == target: if a > b: pair = (b, a) else: pair = (a, b) ...
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a list of integers and an integer target value. The function should return a list of pairs (as tuples) from the input list whose elements sum up to the target value. Each pair should be sorted in ascending order, and the list of pairs should be sorted in asce...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8853, "level": 1, "question": "Write a function that takes a list of integers and an integer target value. The function should return a list of pairs (as tuples) from the input list whose elements sum up to the target value. Each pair should be sorted in ascending order, and the lis...
def spiralOrder(matrix): if not matrix: return [] rows = len(matrix) cols = len(matrix[0]) result = [] top, bottom = 0, rows - 1 left, right = 0, cols - 1 while top <= bottom and left <= right: # Traverse top row from left to right for i in range(left, right + 1)...
simplelr_Filter
[ { "content": "Question:\nTraverse a 2D array in spiral order and return the elements in that order.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8854, "level": 1, "question": "Traverse a 2D array in spiral order and return the elements in that order.", "split": "train" }
def move_all_x_to_end(arr, x): non_x = [] x_list = [] for num in arr: if num != x: non_x.append(num) else: x_list.append(num) return non_x + x_list
simplelr_Leetcode
[ { "content": "Question:\nYou are given an unsorted array of integers `arr` and an integer `x`. Your task is to move all occurrences of `x` to the end of the array while maintaining the relative order of the other elements. Return the modified array after performing the operation.\nAnswer:\nLet's think step by s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8855, "level": 1, "question": "You are given an unsorted array of integers `arr` and an integer `x`. Your task is to move all occurrences of `x` to the end of the array while maintaining the relative order of the other elements. Return the modified array after performing the operati...
import hashlib def string_to_md5(input_string, encoding='utf-8'): """ Computes the MD5 hash of an input string. Args: input_string (str): The string to be hashed. encoding (str, optional): The encoding type. Defaults to 'utf-8'. Returns: str: The MD5 hash as a hexadecimal stri...
simplelr_Filter
[ { "content": "Question:\nWrite a function that converts an input string to its MD5 hash. The function should be in Python and use the hashlib library. Ensure the function is well-documented with comments and a docstring explaining its purpose, parameters, and return value.\nAnswer:\nLet's think step by step.\n"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8856, "level": 1, "question": "Write a function that converts an input string to its MD5 hash. The function should be in Python and use the hashlib library. Ensure the function is well-documented with comments and a docstring explaining its purpose, parameters, and return value.", ...
def longest_subarray(arr: list[int]) -> int: """ Find the length of the longest subarray with equal number of 0s and 1s. Args: arr (list[int]): The input array of integers containing only 0s and 1s. Returns: int: The length of the longest subarray with equal number of 0s and 1s. ""...
simplelr_Algorithm
[ { "content": "Question:\n### Longest Subarray with Equal Number of 0s and 1s\n\nYou need to implement an algorithm that finds the length of the longest subarray with an equal number of 0s and 1s.\n\n**Function Signature:**\n```python\ndef longest_subarray(arr: list[int]) -> int:\n \"\"\"\n Find the length...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8857, "level": 1, "question": "### Longest Subarray with Equal Number of 0s and 1s\n\nYou need to implement an algorithm that finds the length of the longest subarray with an equal number of 0s and 1s.\n\n**Function Signature:**\n```python\ndef longest_subarray(arr: list[int]) -> in...
def second_largest(numbers): if not numbers: return None unique_numbers = set(numbers) if len(unique_numbers) < 2: return None sorted_unique = sorted(unique_numbers, reverse=True) return sorted_unique[1]
simplelr_Filter
[ { "content": "Question:\nHow can I create a function in Python that takes a list of numbers and returns the second largest number in the list? If the list does not have a second largest number (for example, all numbers are the same), the function should return `None`. Can you provide a code snippet for this?\nA...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8858, "level": 1, "question": "How can I create a function in Python that takes a list of numbers and returns the second largest number in the list? If the list does not have a second largest number (for example, all numbers are the same), the function should return `None`. Can you ...
def maxSubarray(arr, k): n = len(arr) if k > n: return [] max_sum = float('-inf') max_subarray = [] curr_sum = 0 for i in range(n): curr_sum += arr[i] if i >= k - 1: if curr_sum > max_sum: max_sum = curr_sum max_subarray = arr[i...
simplelr_Filter
[ { "content": "Question:\nYour task is to find the maximum sum of a subarray of size k from the given array. The array is 1-indexed. You can assume that the array has at least k elements.\n\nExample:\narr = [1, 2, 3, 4, 5], k = 3\nOutput: 12\n\nExplanation:\nThe maximum sum of a subarray of size 3 is 3 + 4 + 5 =...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8859, "level": 1, "question": "Your task is to find the maximum sum of a subarray of size k from the given array. The array is 1-indexed. You can assume that the array has at least k elements.\n\nExample:\narr = [1, 2, 3, 4, 5], k = 3\nOutput: 12\n\nExplanation:\nThe maximum sum of ...
def factorial(n): if n < 0: raise ValueError("n must be a non-negative integer") result = 1 for i in range(1, n + 1): result *= i return result
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the factorial of a given number. The function should be iterative and not use recursion.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8860, "level": 1, "question": "Write a python function to find the factorial of a given number. The function should be iterative and not use recursion.", "split": "train" }
def double_array(arr): return [x * 2 for x in arr]
simplelr_Apps
[ { "content": "Question:\nYou're given an array of integers and your goal is to write a function that returns a new array with each element doubled. Your function should take an array as an input and return an array where each integer is twice as large as the corresponding element in the input array. Consider ed...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8861, "level": 1, "question": "You're given an array of integers and your goal is to write a function that returns a new array with each element doubled. Your function should take an array as an input and return an array where each integer is twice as large as the corresponding elem...
def floyds_triangle(n): result = [] current = 1 for i in range(1, n + 1): row = list(range(current, current + i)) result.append(row) current += i return result
simplelr_Taco
[ { "content": "Question:\nThe Floyd's Triangle is a right-angled triangular array of natural numbers. It is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner. For example, a Floyd's Triangle with 5 rows looks like this:\n\n```\n1\n2 3\n4 5 6\n7 8 9 10\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8862, "level": 1, "question": "The Floyd's Triangle is a right-angled triangular array of natural numbers. It is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner. For example, a Floyd's Triangle with 5 rows looks like thi...
def convert_to_dict(nested_list): result = {} for index, sublist in enumerate(nested_list): result[index] = sublist return result # Example usage: nested_list = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'] ] result_dict = convert_to_dict(nested_list) print(result_dict)
simplelr_Filter
[ { "content": "Question:\nHere's an example of a nested list in Python: \n```python\nnested_list = [\n ['a', 'b', 'c'],\n ['d', 'e', 'f'],\n ['g', 'h', 'i']\n]\n```\nHow can I convert the above nested list into a dictionary where the keys are indices of the inner lists and the values are the correspondi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8863, "level": 1, "question": "Here's an example of a nested list in Python: \n```python\nnested_list = [\n ['a', 'b', 'c'],\n ['d', 'e', 'f'],\n ['g', 'h', 'i']\n]\n```\nHow can I convert the above nested list into a dictionary where the keys are indices of the inner lists...
def spiral_order(matrix): result = [] if not matrix: return result top = 0 bottom = len(matrix) - 1 left = 0 right = len(matrix[0]) - 1 while top <= bottom and left <= right: # Traverse top row from left to right for i in range(left, right + 1): ...
simplelr_Filter
[ { "content": "Question:\nWe are given a m x n matrix, print all elements of the matrix in spiral order, starting from top left and moving clockwise.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8864, "level": 1, "question": "We are given a m x n matrix, print all elements of the matrix in spiral order, starting from top left and moving clockwise.", "split": "train" }
import heapq from typing import List def streaming_median(stream: List[int]) -> List[float]: low = [] # max-heap implemented as a min-heap with negative values high = [] # min-heap medians = [] for num in stream: if not low or num <= -low[0]: heapq.heappush(low, -num) else...
simplelr_Evol
[ { "content": "Question:\nImplement a function to calculate the running median of a stream of integers. The running median is the current median value of all the numbers seen so far in the input stream.\n\nHere's a summary of the steps involved:\n\n1. Accept a stream of integers one by one.\n2. After each new in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8865, "level": 1, "question": "Implement a function to calculate the running median of a stream of integers. The running median is the current median value of all the numbers seen so far in the input stream.\n\nHere's a summary of the steps involved:\n\n1. Accept a stream of integer...
import logging import logging.config def configure_logging(config: dict) -> str: try: logging.config.dictConfig(config) return "Configuration successful" except Exception as e: return f"Error in configuration: {str(e)}"
simplelr_Docs
[ { "content": "Question:\n### **Coding Assessment Question**\n\n#### **Objective**\n\nImplement a Python function that configures the logging system using a dictionary configuration with validation against the dictionary schema provided in the `logging.config` module. Your function will handle custom formatters,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8866, "level": 1, "question": "### **Coding Assessment Question**\n\n#### **Objective**\n\nImplement a Python function that configures the logging system using a dictionary configuration with validation against the dictionary schema provided in the `logging.config` module. Your func...
from typing import List def warehouse_pigeonhole_sort(identifiers: List[int]) -> List[int]: if not identifiers: return [] # Initialize pigeonhole with 1000 zeros (indices 0 to 999) pigeonhole = [0] * 1000 # Count each identifier's occurrences for num in identifiers: pigeon...
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario\nYou are tasked with developing a sorting mechanism for a set of numeric identifiers representing products in a warehouse. These identifiers are within a small, fixed range due to being generated in sequence, making distribution-based sorts suitable for the task.\n\n### Que...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8867, "level": 1, "question": "### Scenario\nYou are tasked with developing a sorting mechanism for a set of numeric identifiers representing products in a warehouse. These identifiers are within a small, fixed range due to being generated in sequence, making distribution-based sort...
def max_profit(prices): if len(prices) < 2: return 0 buy1 = float('-inf') sell1 = 0 buy2 = float('-inf') sell2 = 0 for price in prices: new_buy1 = max(buy1, -price) new_sell1 = max(sell1, buy1 + price) new_buy2 = max(buy2, sell1 - price) new_sell2 = max(se...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the maximum profit from at most two transactions given a list of daily stock prices. This function should return the maximum profit possible from those transactions.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8868, "level": 1, "question": "Write a function to calculate the maximum profit from at most two transactions given a list of daily stock prices. This function should return the maximum profit possible from those transactions.", "split": "train" }
def find_pair_with_sum(arr, x): seen = {} for i, num in enumerate(arr): complement = x - num if complement in seen: return (seen[complement], i) seen[num] = i return -1
simplelr_Leetcode
[ { "content": "Question:\nYou are given an integer array `arr` and an integer `x`. Your task is to determine whether there are two distinct indices `i` and `j` in the array such that `arr[i] + arr[j] == x`. If such a pair exists, return the indices as a tuple `(i, j)` in ascending order. If no such pair exists, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8869, "level": 1, "question": "You are given an integer array `arr` and an integer `x`. Your task is to determine whether there are two distinct indices `i` and `j` in the array such that `arr[i] + arr[j] == x`. If such a pair exists, return the indices as a tuple `(i, j)` in ascend...
def first_non_repeated_character(s): # Create a frequency dictionary to count occurrences of each character freq = {} for char in s: if char in freq: freq[char] += 1 else: freq[char] = 1 # Iterate through the string to find the first character with count 1 ...
simplelr_Evol
[ { "content": "Question:\nCreate a function in Python that takes a string as an input and returns the first non-repeated character in the string. If there is no unique character, return `None`. For example, given the input \"swiss\", the function should return \"w\" because it is the first character in the strin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8870, "level": 1, "question": "Create a function in Python that takes a string as an input and returns the first non-repeated character in the string. If there is no unique character, return `None`. For example, given the input \"swiss\", the function should return \"w\" because it ...
def unique_values(input_list): unique = [] seen = set() for item in input_list: if item not in seen: unique.append(item) seen.add(item) return unique
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to create a list of unique values from a list. In the case when the input list is empty, the function should return an empty list. In the case when the input list contains duplicate values, the function should return a list of unique values only.\nAnswer:\nLet's ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8871, "level": 1, "question": "Write a python function to create a list of unique values from a list. In the case when the input list is empty, the function should return an empty list. In the case when the input list contains duplicate values, the function should return a list of u...
def is_bijective_pattern(pattern: str, sentence: str) -> bool: words = sentence.split() if len(pattern) != len(words): return False pattern_to_word = {} word_to_pattern = {} for p_char, word in zip(pattern, words): if p_char in pattern_to_word: if pattern_to_word[p_char...
simplelr_Data_Structure
[ { "content": "Question:\n### Question: Validate Word Pattern Mapping\n\nGiven a pattern string and a sentence string, your task is to implement the function `is_bijective_pattern(pattern: str, sentence: str) -> bool` that verifies if the sentence follows the same pattern as defined by the pattern string. A sent...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8872, "level": 1, "question": "### Question: Validate Word Pattern Mapping\n\nGiven a pattern string and a sentence string, your task is to implement the function `is_bijective_pattern(pattern: str, sentence: str) -> bool` that verifies if the sentence follows the same pattern as de...
def word_frequency(text): freq = {} tokens = text.split() for token in tokens: processed = ''.join([c for c in token if c.isalnum()]) if processed: lower_word = processed.lower() if lower_word in freq: freq[lower_word] += 1 else: ...
simplelr_Taco
[ { "content": "Question:\nSusan is working on a text analysis tool that helps her count the frequency of unique words in a given text. She needs your help to optimize her code to handle edge cases and different formats of input. The text can include punctuation, numbers, and special characters, and words are cas...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8873, "level": 1, "question": "Susan is working on a text analysis tool that helps her count the frequency of unique words in a given text. She needs your help to optimize her code to handle edge cases and different formats of input. The text can include punctuation, numbers, and sp...
def reverseWords(sentence): return ' '.join(sentence.split()[::-1])
simplelr_Taco
[ { "content": "Question:\nWrite a function to reverse the words in a given sentence. The sentence will only consist of alphanumeric characters and spaces. Words are defined as sequences of characters separated by spaces.\n\nThe function should be based on the following specifications:\n\nreverseWords(sentence)\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8874, "level": 1, "question": "Write a function to reverse the words in a given sentence. The sentence will only consist of alphanumeric characters and spaces. Words are defined as sequences of characters separated by spaces.\n\nThe function should be based on the following specific...
def sieve_of_eratosthenes(limit): if limit < 2: return [] sieve = [True] * (limit + 1) sieve[0] = sieve[1] = False for i in range(4, limit + 1, 2): sieve[i] = False for i in range(3, int(limit ** 0.5) + 1, 2): if sieve[i]: sieve[i*i : limit+1 : 2*i] = [False] * le...
simplelr_Filter
[ { "content": "Question:\nRewrite the example code to use the efficient Sieve of Eratosthenes algorithm to find the prime numbers up to a given limit, and exclude the even numbers in the process.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8875, "level": 1, "question": "Rewrite the example code to use the efficient Sieve of Eratosthenes algorithm to find the prime numbers up to a given limit, and exclude the even numbers in the process.", "split": "train" }
def count_ways_to_make_change(amount, coins): coins = list(set(coins)) # Remove duplicate coins dp = [0] * (amount + 1) dp[0] = 1 # Base case: one way to make amount 0 for coin in coins: if coin > amount: continue for i in range(coin, amount + 1): dp[i] += ...
simplelr_Filter
[ { "content": "Question:\nI need to write a Python function to determine the number of ways to make change for a given amount using a set of coin denominations. The order of coins does not matter. For example, for the amount 4 and denominations [1, 2, 3], the possible combinations are [1, 1, 1, 1], [1, 1, 2], [1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8876, "level": 1, "question": "I need to write a Python function to determine the number of ways to make change for a given amount using a set of coin denominations. The order of coins does not matter. For example, for the amount 4 and denominations [1, 2, 3], the possible combinati...
def remove_duplicates_and_sort(numbers): unique_numbers = [] for number in numbers: if number not in unique_numbers: unique_numbers.append(number) unique_numbers.sort() return unique_numbers test_list = [3, 1, 2, 3, 4, 1, 5] print(remove_duplicates_and_sort(test_list))
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes a list of integers as input, removes any duplicate values, sorts the remaining numbers in ascending order, and returns the sorted list. Provide an erroneous piece of code for the candidate to analyze and fix.\n\n#Erroneous code:\n\ndef remove_duplicates_and_s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8877, "level": 1, "question": "Write a function that takes a list of integers as input, removes any duplicate values, sorts the remaining numbers in ascending order, and returns the sorted list. Provide an erroneous piece of code for the candidate to analyze and fix.\n\n#Erroneous c...
def count_vowels(s): vowel_counts = {} vowels = {'a', 'e', 'i', 'o', 'u'} for char in s: if char in vowels: vowel_counts[char] = vowel_counts.get(char, 0) + 1 return vowel_counts
simplelr_Taco
[ { "content": "Question:\nYou are given a string s which consists of lowercase English letters and contains no spaces. Implement a function that counts the number of vowels (a, e, i, o, u) in the string and returns them in a dictionary where the key is the vowel and the value is the count of that vowel in the st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8878, "level": 1, "question": "You are given a string s which consists of lowercase English letters and contains no spaces. Implement a function that counts the number of vowels (a, e, i, o, u) in the string and returns them in a dictionary where the key is the vowel and the value i...
def is_fibonacci_like(sequence: list[int]) -> bool: if len(sequence) < 3: return False for i in range(len(sequence) - 2): if sequence[i] + sequence[i + 1] != sequence[i + 2]: return False return True
simplelr_Algorithm
[ { "content": "Question:\n### Problem Overview\nYou are given a list of integers representing a sequence where each integer is an element of a Fibonacci-like sequence. A sequence is considered Fibonacci-like if both of the following conditions hold:\n1. `sequence[i] + sequence[i + 1] = sequence[i + 2]`\n2. The l...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8879, "level": 1, "question": "### Problem Overview\nYou are given a list of integers representing a sequence where each integer is an element of a Fibonacci-like sequence. A sequence is considered Fibonacci-like if both of the following conditions hold:\n1. `sequence[i] + sequence[...
from typing import List def robust_interpolation_search(array: List[int], search_key: int) -> int: if not array: return -1 low = 0 high = len(array) - 1 while low <= high: if low == high: if array[low] == search_key: return low else: ...
simplelr_Data_Structure
[ { "content": "Question:\nYou are given a sorted array of integers and a search key. Your task is to implement and extend the Interpolation Search Algorithm to handle potential edge cases more robustly and improve its functionality.\n\n### Specifically:\n1. The array is always sorted in non-decreasing order.\n2....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8880, "level": 1, "question": "You are given a sorted array of integers and a search key. Your task is to implement and extend the Interpolation Search Algorithm to handle potential edge cases more robustly and improve its functionality.\n\n### Specifically:\n1. The array is always ...
def generate_character_frequency(input_string: str) -> dict: char_freq = {} for char in input_string: char_freq[char] = char_freq.get(char, 0) + 1 return char_freq
simplelr_Package
[ { "content": "Question:\nYou are required to write a Python function `generate_character_frequency()` that takes a string as input and returns a dictionary where the keys are the unique characters in the string and the values are the corresponding counts of occurrences of those characters. Your function should ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8881, "level": 1, "question": "You are required to write a Python function `generate_character_frequency()` that takes a string as input and returns a dictionary where the keys are the unique characters in the string and the values are the corresponding counts of occurrences of thos...
from typing import List def sum_of_squares_at_even_indices(nums: List[int]) -> int: even_elements = nums[::2] return sum(num ** 2 for num in even_elements)
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question:\n\n**Objective**:\nWrite a function that computes the sum of the squares of elements in a list, but only includes elements that are at even indices. This will test your ability to manipulate lists and use list indexing effectively.\n\n### Problem Statemen...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8882, "level": 1, "question": "### Coding Assessment Question:\n\n**Objective**:\nWrite a function that computes the sum of the squares of elements in a list, but only includes elements that are at even indices. This will test your ability to manipulate lists and use list indexing e...
def binary_to_decimal(s): if s.startswith('-'): binary_part = s[1:] return -int(binary_part, 2) else: return int(s, 2)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to convert a binary string to a decimal number. The function should handle both positive and negative binary strings. For positive binary strings, simply convert the binary number to a decimal. For negative binary strings, consider the two's complement representa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8883, "level": 1, "question": "Write a python function to convert a binary string to a decimal number. The function should handle both positive and negative binary strings. For positive binary strings, simply convert the binary number to a decimal. For negative binary strings, consi...
def length_of_longest_substring(s): last_seen = {} max_len = 0 left = 0 for right in range(len(s)): char = s[right] if char in last_seen and last_seen[char] >= left: left = last_seen[char] + 1 last_seen[char] = right current_len = right - left + 1 if c...
simplelr_Taco
[ { "content": "Question:\nViolet is working with strings and needs a function that will identify the longest substring without repeating characters. Her current solution has a time complexity of O(n^2), which is too slow for very long strings. Your task is to implement an optimized function that finds the longes...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8884, "level": 1, "question": "Violet is working with strings and needs a function that will identify the longest substring without repeating characters. Her current solution has a time complexity of O(n^2), which is too slow for very long strings. Your task is to implement an optim...
def is_candidate(s): parts = s.split(':') if len(parts) != 2: return False age_str = parts[0].strip() weight_str = parts[1].strip() try: age = float(age_str) weight = float(weight_str) except ValueError: return False return age >= 18 and weight >= 60
simplelr_Filter
[ { "content": "Question:\nTo determine whether someone is a good candidate for a certain medication, a doctor needs to know the patient's age and weight. Write a Python function that takes a string input, parses this string to extract the patient's age and weight, and then returns a boolean indicating whether th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8885, "level": 1, "question": "To determine whether someone is a good candidate for a certain medication, a doctor needs to know the patient's age and weight. Write a Python function that takes a string input, parses this string to extract the patient's age and weight, and then retu...
def check_sum_to_k(a, b, c, d, K): numbers = [a, b, c, d] for i in range(4): for j in range(i + 1, 4): if numbers[i] + numbers[j] == K: return True return False
simplelr_Filter
[ { "content": "Question:\nGiven four numbers a, b, c, d, develop a python function to check if any two distinct numbers out of these four sum up to a target value K.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8886, "level": 1, "question": "Given four numbers a, b, c, d, develop a python function to check if any two distinct numbers out of these four sum up to a target value K.", "split": "train" }
import re def extract_dates(text: str) -> list: pattern = r'(?<!\d)\d{2}-\d{2}-\d{4}(?!\d)' return re.findall(pattern, text)
simplelr_Docs
[ { "content": "Question:\n#### Objective\nImplement a Python function to identify and extract specific patterns from a given text using regular expressions (`re` module). This will test the students' understanding of regular expressions and their ability to apply them in practice.\n\n#### Problem Statement\nYou ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8887, "level": 1, "question": "#### Objective\nImplement a Python function to identify and extract specific patterns from a given text using regular expressions (`re` module). This will test the students' understanding of regular expressions and their ability to apply them in practi...
def sum_of_even_numbers(array): return sum(num for num in array if num % 2 == 0)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the sum of all even numbers in a given array. What is the best way to do it?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8888, "level": 1, "question": "Write a function to calculate the sum of all even numbers in a given array. What is the best way to do it?", "split": "train" }
from collections import defaultdict def find_indices_with_sum(arr, x): n = len(arr) if n < 3: return False freq = defaultdict(int) for num in arr: freq[num] += 1 for i in range(n): for j in range(i + 1, n): a = arr[i] b = arr[j] ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of `n` integers `arr` and an integer `x`. Your task is to determine if there exist three distinct indices `i`, `j`, and `k` in the array such that `arr[i] + arr[j] + arr[k] = x`. Return `true` if such indices exist, otherwise, return `false`. Your solution should ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8889, "level": 1, "question": "You are given an array of `n` integers `arr` and an integer `x`. Your task is to determine if there exist three distinct indices `i`, `j`, and `k` in the array such that `arr[i] + arr[j] + arr[k] = x`. Return `true` if such indices exist, otherwise, re...
def generate_report_card(student_scores): report = {} for student, scores in student_scores.items(): if not scores: student_report = { 'average': None, 'highest': None, 'lowest': None } else: average = round(sum(...
simplelr_Package
[ { "content": "Question:\nCreate a function `generate_report_card(student_scores)` that takes a dictionary `student_scores` where keys are student names (strings) and values are lists of their scores (integers). The function should compute the following for each student:\n\n1. Average score\n2. Highest score\n3....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8890, "level": 1, "question": "Create a function `generate_report_card(student_scores)` that takes a dictionary `student_scores` where keys are student names (strings) and values are lists of their scores (integers). The function should compute the following for each student:\n\n1. ...
def count_characters(s): char_count = {} for char in s: if char in char_count: char_count[char] += 1 else: char_count[char] = 1 return char_count
simplelr_Evol
[ { "content": "Question:\n寫一個函數,計算一個字符串中每個字符出現的次數。函數輸入是一個字符串,輸出是一個字典,其中鍵為字符,值為該字符在字符串中出現的次數。\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8891, "level": 1, "question": "寫一個函數,計算一個字符串中每個字符出現的次數。函數輸入是一個字符串,輸出是一個字典,其中鍵為字符,值為該字符在字符串中出現的次數。", "split": "train" }
def compare_file_sets(primary_list, backup_list): primary_dict = {f[0]: f[1] for f in primary_list} backup_dict = {f[0]: f[1] for f in backup_list} new_files = [file for file in primary_dict if file not in backup_dict] deleted_files = [file for file in backup_dict if file not in primary_dict] ...
simplelr_Code_Contests
[ { "content": "Question:\nAs a software engineer at a startup, you are responsible for developing an efficient data synchronization system. One of your current tasks is to compare two sets of files and determine which files are new, which ones are deleted, and which ones have been modified based on their content...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8892, "level": 1, "question": "As a software engineer at a startup, you are responsible for developing an efficient data synchronization system. One of your current tasks is to compare two sets of files and determine which files are new, which ones are deleted, and which ones have b...
import pandas as pd import pathlib def process_large_dataset(directory: str) -> dict: columns = ['name', 'id', 'x', 'y'] files = pathlib.Path(directory).glob("ts-*.parquet") unique_names = set() sum_x = 0 sum_y = 0 count_x = 0 count_y = 0 for file in files: df = pd.read_parquet...
simplelr_Docs
[ { "content": "Question:\n**Pandas Memory Optimization and Chunking**\n\n**Objective:**\nYou are given a large dataset of time series data stored in multiple parquet files in a directory. Your goal is to read and process this data efficiently to compute some overall statistics without exceeding memory limits.\n\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8893, "level": 1, "question": "**Pandas Memory Optimization and Chunking**\n\n**Objective:**\nYou are given a large dataset of time series data stored in multiple parquet files in a directory. Your goal is to read and process this data efficiently to compute some overall statistics ...
def count_pairs_with_sum(nums, target): seen = set() unique_pairs = set() for num in nums: complement = target - num if complement in seen: pair = tuple(sorted((num, complement))) unique_pairs.add(pair) seen.add(num) return len(unique_pairs)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to count the number of distinct pairs of integers in a list where the sum of the pairs equals a given number.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8894, "level": 1, "question": "Write a python function to count the number of distinct pairs of integers in a list where the sum of the pairs equals a given number.", "split": "train" }
def sum_of_natural_numbers(n): return n * (n + 1) // 2
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the sum of the first N natural numbers. What is the time complexity of this function?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8895, "level": 1, "question": "Write a python function to find the sum of the first N natural numbers. What is the time complexity of this function?", "split": "train" }
from typing import Tuple import pandas as pd def analyze_fleet_data(df: pd.DataFrame) -> Tuple[pd.DataFrame, pd.Series, pd.Series, pd.DataFrame]: # Step 6: Convert vehicle_type to lowercase and strip whitespace df_processed = df.copy() df_processed['vehicle_type'] = df_processed['vehicle_type'].str.strip()...
simplelr_Docs
[ { "content": "Question:\n### Pandas Assessment\n\n#### Problem Statement\n\nYou are provided with a dataset containing information about a fleet of vehicles. The dataset consists of columns such as `vehicle_id`, `vehicle_type`, `model_year`, `mileage`, `fuel_type`, and `last_serviced_date`.\n\nYour task is to i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8896, "level": 1, "question": "### Pandas Assessment\n\n#### Problem Statement\n\nYou are provided with a dataset containing information about a fleet of vehicles. The dataset consists of columns such as `vehicle_id`, `vehicle_type`, `model_year`, `mileage`, `fuel_type`, and `last_s...
def reverse_words(sentence): words = sentence.split() reversed_words = [word[::-1] for word in words] reversed_words_list = reversed_words[::-1] reversed_sentence = ' '.join(reversed_words_list) return reversed_sentence
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to reverse each word in a sentence and also return the reversed sentence.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8897, "level": 1, "question": "Write a python function to reverse each word in a sentence and also return the reversed sentence.", "split": "train" }
def validateCommands(transitions: dict, start: str, final: list, commands: str) -> bool: current_state = start for command in commands: current_state = transitions[current_state][command] return current_state in final
simplelr_Data_Structure
[ { "content": "Question:\n#### Context\nYou are working on designing a minimalistic robot controller that moves based on strings of commands it receives. The robot has a deterministic finite set of states, and the commands dictate state transitions. Your task is to determine if a given string of commands is vali...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8898, "level": 1, "question": "#### Context\nYou are working on designing a minimalistic robot controller that moves based on strings of commands it receives. The robot has a deterministic finite set of states, and the commands dictate state transitions. Your task is to determine if...
def binary_search(arr, target): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1
simplelr_Filter
[ { "content": "Question:\nImplement a function that takes a sorted array and a target value, and efficiently finds the index of the target value if it exists in the array. If the target value is not found, return -1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8899, "level": 1, "question": "Implement a function that takes a sorted array and a target value, and efficiently finds the index of the target value if it exists in the array. If the target value is not found, return -1.", "split": "train" }