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 count_words_and_numbers(input_string: str) -> dict: tokens = input_string.split() words = 0 numbers = 0 for token in tokens: if token.isalpha(): words += 1 elif token.isdigit(): numbers += 1 return {'words': words, 'numbers': numbers}
simplelr_Taco
[ { "content": "Question:\nYou are given a string containing a mix of words and numbers, separated by spaces. Your task is to count the number of words and the number of numeric values and return them as a dictionary. Words here are defined as sequences of alphabetic characters, while numeric values consist of se...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8500, "level": 1, "question": "You are given a string containing a mix of words and numbers, separated by spaces. Your task is to count the number of words and the number of numeric values and return them as a dictionary. Words here are defined as sequences of alphabetic characters,...
def is_leap_year(year: int) -> bool: if year % 4 != 0: return False elif year % 100 != 0: return True else: return year % 400 == 0
simplelr_Evol
[ { "content": "Question:\n### Coding Assessment Question\n\nYou are given the task of creating a program to determine if a given year is a leap year. A leap year is divisible by 4, but if it is divisible by 100, it should also be divisible by 400 to be considered a leap year.\n\nWrite a function `is_leap_year(ye...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8501, "level": 1, "question": "### Coding Assessment Question\n\nYou are given the task of creating a program to determine if a given year is a leap year. A leap year is divisible by 4, but if it is divisible by 100, it should also be divisible by 400 to be considered a leap year.\n...
def reverse_string(s): return s[::-1]
simplelr_Filter
[ { "content": "Question:\nWrite a function in Python that takes a string as input and returns the string reversed. However, make sure that the function also handles the reversal of strings containing special characters and numbers, maintaining their positions. For example, if the input is \"Hello, World! 123\", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8502, "level": 1, "question": "Write a function in Python that takes a string as input and returns the string reversed. However, make sure that the function also handles the reversal of strings containing special characters and numbers, maintaining their positions. For example, if t...
def count_triangular_numbers(n: int) -> list: return [k * (k + 1) // 2 for k in range(1, n + 1)]
simplelr_Package
[ { "content": "Question:\nYou are tasked with creating a function `count_triangular_numbers(n)` that computes and returns a list of the first `n` triangular numbers. Triangular numbers are a sequence of numbers generated by the formula:\n\n\\[ T_k = \\frac{k(k+1)}{2} \\]\n\nwhere \\( T_k \\) is the \\( k \\)-th ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8503, "level": 1, "question": "You are tasked with creating a function `count_triangular_numbers(n)` that computes and returns a list of the first `n` triangular numbers. Triangular numbers are a sequence of numbers generated by the formula:\n\n\\[ T_k = \\frac{k(k+1)}{2} \\]\n\nwhe...
def count_characters(s): counts = {} for char in s: if char in counts: counts[char] += 1 else: counts[char] = 1 return counts
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a string as input and returns the number of times each character appears in the string. The function should return a dictionary where the keys are the characters and the values are their respective counts. For example, given the input \"apple\", the output sh...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8504, "level": 1, "question": "Write a function that takes a string as input and returns the number of times each character appears in the string. The function should return a dictionary where the keys are the characters and the values are their respective counts. For example, given...
def find_max_min_positions(lst): if not lst: return None, None, None, None max_val = max(lst) min_val = min(lst) max_positions = [i for i, x in enumerate(lst) if x == max_val] min_positions = [i for i, x in enumerate(lst) if x == min_val] return (max_val, max_positions, mi...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers as input and returns the maximum and minimum values from the list. The function should also return the positions of the maximum and minimum values in the list. If there are multiple occurrences of the maximum or minimum value, return their...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8505, "level": 1, "question": "Create a function that takes a list of integers as input and returns the maximum and minimum values from the list. The function should also return the positions of the maximum and minimum values in the list. If there are multiple occurrences of the max...
def find_second_largest(lst): if not lst: return None unique = list(set(lst)) if len(unique) < 2: return None unique_sorted = sorted(unique, reverse=True) return unique_sorted[1]
simplelr_Apps
[ { "content": "Question:\nWrite a function that takes a list of integers and returns the second largest unique number in the list. If such a number does not exist, return `None`. For example:\n\n```\nfind_second_largest([1, 2, 3, 4, 5]) ==> 4\nfind_second_largest([5, 5, 4, 4, 3]) ==> 3\nfind_second_largest([1, 1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8506, "level": 1, "question": "Write a function that takes a list of integers and returns the second largest unique number in the list. If such a number does not exist, return `None`. For example:\n\n```\nfind_second_largest([1, 2, 3, 4, 5]) ==> 4\nfind_second_largest([5, 5, 4, 4, 3...
def remove_duplicates(nums): seen = set() result = [] for num in nums: if num not in seen: seen.add(num) result.append(num) return result
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of integers and returns a new list with duplicates removed while maintaining the original order of the elements. Additionally, ensure that the function is efficient in terms of time complexity.\nAnswer:\nLet's think step by step.\n", "role":...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8507, "level": 1, "question": "Write a Python function that takes a list of integers and returns a new list with duplicates removed while maintaining the original order of the elements. Additionally, ensure that the function is efficient in terms of time complexity.", "split": "tr...
def shift_right(lst: list[int]) -> list[int]: if not lst: return [] return [lst[-1]] + lst[:-1]
simplelr_Algorithm
[ { "content": "Question:\nWrite a function that takes a list of integers and returns a list of the same numbers, but shifted to the right by one position. The last item of the list should be moved to the front.\n\n### Function Signature\n```python\ndef shift_right(lst: list[int]) -> list[int]:\n```\n\n### Input\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8508, "level": 1, "question": "Write a function that takes a list of integers and returns a list of the same numbers, but shifted to the right by one position. The last item of the list should be moved to the front.\n\n### Function Signature\n```python\ndef shift_right(lst: list[int...
def num_subarray_product_less_than_k(nums, k): count = 0 n = len(nums) for i in range(n): product = 1 has_zero = False for j in range(i, n): if nums[j] == 0: has_zero = True product = 0 # Once a zero is encountered, product remains 0 ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an unsorted array of integers `nums`. Write a function to find the number of contiguous subarrays within which the product of all the elements is less than a given integer `k`. \n\nFor example, given the array `nums = [10, 5, 2, 6]` and `k = 100`, the answer would be `8` a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8509, "level": 1, "question": "You are given an unsorted array of integers `nums`. Write a function to find the number of contiguous subarrays within which the product of all the elements is less than a given integer `k`. \n\nFor example, given the array `nums = [10, 5, 2, 6]` and `...
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:\nGiven a sorted list of distinct integers, write a Python function to find the index of a given target value using binary search. If the target is not found, return -1. Ensure your function is efficient and works for any list of integers and any target value.\nAnswer:\nLet's think step b...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8510, "level": 1, "question": "Given a sorted list of distinct integers, write a Python function to find the index of a given target value using binary search. If the target is not found, return -1. Ensure your function is efficient and works for any list of integers and any target ...
def lengthOfLongestSubstring(s): char_index = {} max_length = start = 0 for i, c in enumerate(s): if c in char_index and char_index[c] >= start: start = char_index[c] + 1 char_index[c] = i current_length = i - start + 1 if current_length > max_length: ...
simplelr_Filter
[ { "content": "Question:\nGiven a string, find the length of the longest substring without repeating characters.\nExample:\nInput: \"abcabcbb\"\nOutput: 3 \nExplanation: The answer is \"abc\", with the length of 3. \n\nInput: \"bbbbb\"\nOutput: 1 \nExplanation: The answer is \"b\", with the length of 1.\n\nInput...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8511, "level": 1, "question": "Given a string, find the length of the longest substring without repeating characters.\nExample:\nInput: \"abcabcbb\"\nOutput: 3 \nExplanation: The answer is \"abc\", with the length of 3. \n\nInput: \"bbbbb\"\nOutput: 1 \nExplanation: The answer is \"...
def longest_common_substring(words): if not words: return "" shortest = min(words, key=lambda x: len(x)) for length in range(len(shortest), 0, -1): for i in range(len(shortest) - length + 1): substr = shortest[i:i+length] if all(substr in word for word in words): ...
simplelr_Filter
[ { "content": "Question:\nI have a large list of words, and I want to find the longest substring that appears in all the words. This substring can be a single character or longer. How do you implement this in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8512, "level": 1, "question": "I have a large list of words, and I want to find the longest substring that appears in all the words. This substring can be a single character or longer. How do you implement this in Python?", "split": "train" }
def binary_to_decimal(binary_str): result = 0 for bit in binary_str: result += result # Multiply result by 2 using addition result += int(bit) # Add the current bit value return result
simplelr_Filter
[ { "content": "Question:\nWrite a function in Python to convert a given binary string to its equivalent decimal representation. However, you are not allowed to use any built-in functions or libraries for conversion, and your solution should have a time complexity of O(n), where n is the length of the binary stri...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8513, "level": 1, "question": "Write a function in Python to convert a given binary string to its equivalent decimal representation. However, you are not allowed to use any built-in functions or libraries for conversion, and your solution should have a time complexity of O(n), where...
def get_mime_type(file_list): """ This function determines the MIME type of a list of given files based on their extensions. Args: file_list (list): A list of file names. Returns: dict: A dictionary where the keys are the file names and the values are their corresponding MIME types. ...
simplelr_Filter
[ { "content": "Question:\n### MIME Typing Game\n#### Introduction\nMIME is a way of identifying files on the Internet according to their nature and format. Based on this, **.jpg** is identified by the MIME type **image/jpeg**, **.png** is identified by **image/png**, etc.\nIn this problem, we will be writing a p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8514, "level": 1, "question": "### MIME Typing Game\n#### Introduction\nMIME is a way of identifying files on the Internet according to their nature and format. Based on this, **.jpg** is identified by the MIME type **image/jpeg**, **.png** is identified by **image/png**, etc.\nIn t...
from math import gcd def least_common_multiple(a: int, b: int) -> int: """ This function calculates the Least Common Multiple (LCM) of two integers using the GCD method. Args: a (int): The first integer. b (int): The second integer. Returns: int: The LCM of a and b, wh...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Context\nYou have been tasked with developing a module to handle simple mathematical functions. This particular task involves computing the Least Common Multiple (LCM) of two integers. The LCM of two integers is the smallest positive integer that i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8515, "level": 1, "question": "### Coding Assessment Question\n\n#### Context\nYou have been tasked with developing a module to handle simple mathematical functions. This particular task involves computing the Least Common Multiple (LCM) of two integers. The LCM of two integers is t...
def highest_product_of_three(numbers): if len(numbers) < 3: raise ValueError("Less than three numbers provided") numbers = sorted(numbers) option1 = numbers[-1] * numbers[-2] * numbers[-3] option2 = numbers[0] * numbers[1] * numbers[-1] return max(option1, option2)
simplelr_Evol
[ { "content": "Question:\nCreate a function that finds the highest product of any three numbers from a list of integers and returns that product. Your solution should work efficiently for large lists.\n\ndef highest_product_of_three(numbers):\n if len(numbers) < 3:\n raise ValueError(\"Less than three ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8516, "level": 1, "question": "Create a function that finds the highest product of any three numbers from a list of integers and returns that product. Your solution should work efficiently for large lists.\n\ndef highest_product_of_three(numbers):\n if len(numbers) < 3:\n ...
def find_common_elements(list1: list[int], list2: list[int]) -> list[int]: set1 = set(list1) set2 = set(list2) common_elements = set1 & set2 return sorted(common_elements)
simplelr_Package
[ { "content": "Question:\nCreate a Python function `find_common_elements` that takes two lists of integers as input and returns a list of integers that are present in both input lists. The resulting list should be sorted in ascending order and should not contain any duplicates. \n\nEnsure that your solution effi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8517, "level": 1, "question": "Create a Python function `find_common_elements` that takes two lists of integers as input and returns a list of integers that are present in both input lists. The resulting list should be sorted in ascending order and should not contain any duplicates....
def check_divisibility_by_5(numbers): result = [] for num in numbers: if num % 5 == 0: result.append('Five') else: result.append(num) return result
simplelr_Filter
[ { "content": "Question:\nWrite a Python function which receives a list of numbers and for each number, checks if it is divisible by 5. If a number is divisible, it should append 'Five' to a new list; if not, it should append the number itself. The function should finally return the new list.\nAnswer:\nLet's thi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8518, "level": 1, "question": "Write a Python function which receives a list of numbers and for each number, checks if it is divisible by 5. If a number is divisible, it should append 'Five' to a new list; if not, it should append the number itself. The function should finally retur...
def max_final_card_value(numbers): return sum(numbers)
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of `numbers` representing the values of cards in a card game. Each player makes a move by selecting two different cards, `numbers[i]` and `numbers[j]`, and replaces them with a single new card whose value is the sum of `numbers[i]` and `numbers[j]`. The players cont...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8519, "level": 1, "question": "You are given a list of `numbers` representing the values of cards in a card game. Each player makes a move by selecting two different cards, `numbers[i]` and `numbers[j]`, and replaces them with a single new card whose value is the sum of `numbers[i]`...
from typing import List def ternary_search(left: int, right: int, key: int, arr: List[int]) -> int: while left <= right: if left == right: return left if arr[left] == key else -1 mid1 = left + (right - left) // 3 mid2 = right - (right - left) // 3 if arr[mid1] == key: ...
simplelr_Data_Structure
[ { "content": "Question:\n### Ternary Search Challenge\n\n#### Context\nYou are given a sorted list of integers, and you need to implement a function to determine the position of a specific key using the Ternary Search algorithm. Your implementation should be efficient and consider edge cases.\n\n#### Function S...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8520, "level": 1, "question": "### Ternary Search Challenge\n\n#### Context\nYou are given a sorted list of integers, and you need to implement a function to determine the position of a specific key using the Ternary Search algorithm. Your implementation should be efficient and cons...
def max_profit(prices): if len(prices) < 2: return 0 min_price = prices[0] max_profit = 0 for price in prices: if price < min_price: min_price = price current_profit = price - min_price if current_profit > max_profit: max_profit = current_profit ...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the maximum profit that can be achieved from an array of stock prices on different days. The function should take in a list of prices and return the maximum profit.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8521, "level": 1, "question": "Write a function to find the maximum profit that can be achieved from an array of stock prices on different days. The function should take in a list of prices and return the maximum profit.", "split": "train" }
def maxSubArraySum(arr): if not arr: return 0 max_so_far = max_ending_here = arr[0] for num in arr[1:]: max_ending_here = max(num, max_ending_here + num) if max_ending_here > max_so_far: max_so_far = max_ending_here return max_so_far
simplelr_Taco
[ { "content": "Question:\nWrite a function `maxSubArraySum(arr)` that takes an array of integers `arr` and returns the sum of the largest sum contiguous subarray.\n\nFor example, given the array `arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]`, the function should return `6`, which is the sum of the subarray `[4, -1, 2, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8522, "level": 1, "question": "Write a function `maxSubArraySum(arr)` that takes an array of integers `arr` and returns the sum of the largest sum contiguous subarray.\n\nFor example, given the array `arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]`, the function should return `6`, which is t...
from typing import List def number_spiral(n: int) -> List[List[int]]: if n == 0: return [] matrix = [[0 for _ in range(n)] for _ in range(n)] directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # right, down, left, up current_dir = 0 current_row, current_col = 0, 0 for num in range(1,...
simplelr_Algorithm
[ { "content": "Question:\n### Number Spiral Generator\n\n#### Problem Description\n\nYou have been hired as a software engineer at a company that specializes in visualization tools. Your current task is to develop a function that generates a number spiral for a given size. \n\nA number spiral is a square grid (n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8523, "level": 1, "question": "### Number Spiral Generator\n\n#### Problem Description\n\nYou have been hired as a software engineer at a company that specializes in visualization tools. Your current task is to develop a function that generates a number spiral for a given size. \n\n...
def factorial(n): if n <= 0: return 1 else: return n * factorial(n - 1)
simplelr_Filter
[ { "content": "Question:\nCan you write a Python function that calculates the factorial of a given number using recursion? The function should be named `factorial` and should take an integer `n` as its argument. The factorial of a number `n` is the product of all positive integers less than or equal to `n`. For ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8524, "level": 1, "question": "Can you write a Python function that calculates the factorial of a given number using recursion? The function should be named `factorial` and should take an integer `n` as its argument. The factorial of a number `n` is the product of all positive integ...
def pair_elements(list1, list2): result = [] min_len = min(len(list1), len(list2)) for i in range(min_len): t1 = list1[i] t2 = list2[i] min_j = min(len(t1), len(t2)) for j in range(min_j): result.append((t1[j], t2[j])) return result
simplelr_Filter
[ { "content": "Question:\nI have two lists of tuples. I want to create a new list where each tuple contains a pair of elements, one from each list. \nThe pairs should be generated based on their position in the list. For example, if the first list is [(1, 2), (3, 4)] and the second list is [(5, 6), (7, 8)], the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8525, "level": 1, "question": "I have two lists of tuples. I want to create a new list where each tuple contains a pair of elements, one from each list. \nThe pairs should be generated based on their position in the list. For example, if the first list is [(1, 2), (3, 4)] and the se...
from collections import Counter def min_deletions_to_k_repetitions(s, k): counts = Counter(s) deletions = 0 for char, cnt in counts.items(): if cnt > k: deletions += cnt - k return deletions
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s`, which consists of lowercase English letters. You are also given an integer `k`. You can choose any character in the string and delete it, but each deletion costs you one point. Your goal is to delete some characters from the string to create a string in which...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8526, "level": 1, "question": "You are given a string `s`, which consists of lowercase English letters. You are also given an integer `k`. You can choose any character in the string and delete it, but each deletion costs you one point. Your goal is to delete some characters from the...
def sort_active_counts(dict_list): # Filter the dictionaries where status is 'active' active_dicts = [d for d in dict_list if d.get('status') == 'active'] # Sort the filtered list based on 'count' in ascending order sorted_dicts = sorted(active_dicts, key=lambda x: x['count']) return sorted_dicts
simplelr_Filter
[ { "content": "Question:\nCreate a Python function to sort a list of dictionaries in ascending order of \"count\", but only include dictionaries that have a key \"status\" with the value \"active\". Additionally, ensure that the sorting is stable, meaning that dictionaries with the same \"count\" value should re...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8527, "level": 1, "question": "Create a Python function to sort a list of dictionaries in ascending order of \"count\", but only include dictionaries that have a key \"status\" with the value \"active\". Additionally, ensure that the sorting is stable, meaning that dictionaries with...
def replace_numbers_less_than_10(lst): return ['X' if x < 10 else x for x in lst]
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of numbers and returns a new list with all the numbers less than 10 replaced with the string 'X'.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8528, "level": 1, "question": "Write a Python function that takes a list of numbers and returns a new list with all the numbers less than 10 replaced with the string 'X'.", "split": "train" }
from collections import Counter def max_palindrome_count(s): freq = Counter(s) sum_pairs = 0 num_odds = 0 for count in freq.values(): sum_pairs += (count // 2) * 2 if count % 2 != 0: num_odds += 1 if num_odds >= 1: sum_pairs += 1 re...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nA palindrome is a string that reads the same backward as forward. Given a string `s`, write a function `max_palindrome_count` that returns the length of the longest palindrome that can be constructed by any permutation of the characters in `s`.\n\n#### Input\n- ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8529, "level": 1, "question": "### Problem Statement\n\nA palindrome is a string that reads the same backward as forward. Given a string `s`, write a function `max_palindrome_count` that returns the length of the longest palindrome that can be constructed by any permutation of the c...
import collections def shortest_subarray_with_sum_at_least_k(nums, k): prefix = [0] for num in nums: prefix.append(prefix[-1] + num) dq = collections.deque() dq.append(0) min_len = float('inf') for j in range(1, len(prefix)): current = prefix[j] target = c...
simplelr_Leetcode
[ { "content": "Question:\nGiven a list of integers `nums`, and an integer `k`, return _the length of the shortest contiguous subarray whose sum is greater than or equal to `k`. If there is no such subarray, return `0`.\n\nNote: Your solution must achieve better than O(n^2) time complexity.\nAnswer:\nLet's think ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8530, "level": 1, "question": "Given a list of integers `nums`, and an integer `k`, return _the length of the shortest contiguous subarray whose sum is greater than or equal to `k`. If there is no such subarray, return `0`.\n\nNote: Your solution must achieve better than O(n^2) time...
def count_characters(s): upper = 0 lower = 0 digits = 0 special = 0 for char in s: if 'A' <= char <= 'Z': upper += 1 elif 'a' <= char <= 'z': lower += 1 elif '0' <= char <= '9': digits += 1 else: special += 1 return ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as input and returns a tuple containing the counts of uppercase letters, lowercase letters, digits, and special characters in the string. Implement the function without using Python's built-in count() method or regex.\nAnswer:\nLet's think step by s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8531, "level": 1, "question": "Create a function that takes a string as input and returns a tuple containing the counts of uppercase letters, lowercase letters, digits, and special characters in the string. Implement the function without using Python's built-in count() method or reg...
def multiply_digits(n): product = 1 for digit in str(abs(n)): product *= int(digit) return product
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an integer as an argument and returns the result of multiplying all the digits in that number together.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8532, "level": 1, "question": "Create a function that takes an integer as an argument and returns the result of multiplying all the digits in that number together.", "split": "train" }
def dna_complement(dna_sequence: str) -> str: return dna_sequence.translate(str.maketrans('ATCG', 'TAGC'))
simplelr_Algorithm
[ { "content": "Question:\nDNA Sequence Complement\n\nTo assess your understanding of string manipulation and basic biological computation, your task is to create a function that generates the complementary DNA strand for a given DNA sequence.\n\nIn a DNA sequence, \n- 'A' (Adenine) pairs with 'T' (Thymine)\n- 'T...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8533, "level": 1, "question": "DNA Sequence Complement\n\nTo assess your understanding of string manipulation and basic biological computation, your task is to create a function that generates the complementary DNA strand for a given DNA sequence.\n\nIn a DNA sequence, \n- 'A' (Aden...
def get_most_recently_added(cart): return cart[-1] if cart else None
simplelr_Filter
[ { "content": "Question:\nI have a list of strings representing items in a shopping cart. I want to write a function that will return the most recently added item to the cart. If the cart is empty, I want it to return None. \n\nHere is the example of how it would work: \n\n```\ncart = [\"apple\", \"banana\", \"o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8534, "level": 1, "question": "I have a list of strings representing items in a shopping cart. I want to write a function that will return the most recently added item to the cart. If the cart is empty, I want it to return None. \n\nHere is the example of how it would work: \n\n```\...
def max_balanced_length(s): return len(set(s))
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` containing only lowercase letters. A \"balanced\" string is defined as a string where no letter appears more than once. You can remove one or more characters from `s` to obtain a new string. Your task is to return the maximum possible length of a \"balanced\" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8535, "level": 1, "question": "You are given a string `s` containing only lowercase letters. A \"balanced\" string is defined as a string where no letter appears more than once. You can remove one or more characters from `s` to obtain a new string. Your task is to return the maximum...
def min_path_sum(grid): m = len(grid) if m == 0: return 0 # Though the problem states grid has at least one cell n = len(grid[0]) if n == 0: return 0 # Though the problem states each cell has a cost # Create a DP table initialized with zeros dp = [[0 for _ in range(n)] for...
simplelr_Package
[ { "content": "Question:\nYou are given a grid with rows and columns represented by a 2D list of integers. Each cell in the grid contains a value representing the cost to enter that cell. Write a function `min_path_sum` that finds the minimum cost path from the top-left corner to the bottom-right corner of the g...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8536, "level": 1, "question": "You are given a grid with rows and columns represented by a 2D list of integers. Each cell in the grid contains a value representing the cost to enter that cell. Write a function `min_path_sum` that finds the minimum cost path from the top-left corner ...
def rabin_karp(word: str, text: str) -> int: m = len(word) n = len(text) if m == 0: return -1 # though per problem statement, word is non-empty if m > n: return -1 mod = 10**9 + 7 base = 256 base_pow = pow(base, m - 1, mod) # Compute hash for the word...
simplelr_Data_Structure
[ { "content": "Question:\n### Rabin-Karp Algorithm for String Matching\n\n#### Objective:\nImplement a function to find the first occurrence of a given word within a text string using the Rabin-Karp algorithm.\n\n#### Task:\nWrite a function `rabin_karp` that returns the index of the first occurrence of the give...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8537, "level": 1, "question": "### Rabin-Karp Algorithm for String Matching\n\n#### Objective:\nImplement a function to find the first occurrence of a given word within a text string using the Rabin-Karp algorithm.\n\n#### Task:\nWrite a function `rabin_karp` that returns the index ...
from collections import Counter def is_permutation(str1: str, str2: str) -> bool: if len(str1) != len(str2): return False return Counter(str1) == Counter(str2)
simplelr_Algorithm
[ { "content": "Question:\n### String Permutation Check\n\n#### Context\nIn many programming applications, such as cryptographic algorithms and password validation, it's often necessary to determine whether one string is a permutation of another. A permutation is a rearrangement of the characters of a string into...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8538, "level": 1, "question": "### String Permutation Check\n\n#### Context\nIn many programming applications, such as cryptographic algorithms and password validation, it's often necessary to determine whether one string is a permutation of another. A permutation is a rearrangement...
def max_unique_elements_in_sliding_window(arr, k): if k == 0: return 0 max_unique = 0 current_unique = 0 freq = {} left = 0 n = len(arr) for right in range(n): char = arr[right] if char in freq: freq[char] += 1 else: freq[char] = 1 ...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to solve the problem of finding the maximum number of unique elements in a sliding window of size k in a given array. The function should take two parameters: an array of integers and the size of the sliding window k.\nAnswer:\nLet's think step by step.\n", "role": ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8539, "level": 1, "question": "Write a function to solve the problem of finding the maximum number of unique elements in a sliding window of size k in a given array. The function should take two parameters: an array of integers and the size of the sliding window k.", "split": "tra...
def has_pair_with_sum(arr, target): seen = set() for num in arr: complement = target - num if complement in seen: return True seen.add(num) return False
simplelr_Apps
[ { "content": "Question:\nGiven an array of integers and a target sum, write a function that returns True if there are two distinct numbers in the array that add up to the target sum, and False otherwise. Do not use the same element twice, and consider the solution with the best possible time complexity.\n\nFor ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8540, "level": 1, "question": "Given an array of integers and a target sum, write a function that returns True if there are two distinct numbers in the array that add up to the target sum, and False otherwise. Do not use the same element twice, and consider the solution with the bes...
from collections import defaultdict def find_anagrams(words): anagrams = defaultdict(list) for word in words: key = ''.join(sorted(word)) anagrams[key].append(word) result = [group for group in anagrams.values() if len(group) >= 2] return result
simplelr_Algorithm
[ { "content": "Question:\n### Anagram Problem\nYou are developing a text processing tool that detects relationships between different words in a large corpus. One key feature is to identify anagrams—pairs of words that contain the exact same characters in a different order.\n\nWrite a function `find_anagrams` th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8541, "level": 1, "question": "### Anagram Problem\nYou are developing a text processing tool that detects relationships between different words in a large corpus. One key feature is to identify anagrams—pairs of words that contain the exact same characters in a different order.\n\n...
def find_conflicts(meetings): if not meetings: return [] # Create a list of tuples with original indices indexed_meetings = [(m[0], m[1], i) for i, m in enumerate(meetings)] # Sort the meetings by start time, then end time sorted_meetings = sorted(indexed_meetings, key=lambda x: (x...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\nYou are implementing a feature for a calendar application that schedules meetings while avoiding conflicts. Each meeting is represented by its start and end times in minutes since the start of the day (e.g., a meeting starting at 9:00 AM and ending at 1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8542, "level": 1, "question": "### Coding Assessment Question\n\nYou are implementing a feature for a calendar application that schedules meetings while avoiding conflicts. Each meeting is represented by its start and end times in minutes since the start of the day (e.g., a meeting ...
def search(nums, target): low = 0 high = len(nums) - 1 while low <= high: mid = (low + high) // 2 if nums[mid] == target: return mid if nums[low] <= nums[mid]: # Left half is sorted if nums[low] <= target <= nums[mid]: high = mid - ...
simplelr_Filter
[ { "content": "Question:\n### Technical Interview Practice: Algorithms\n#### Problem: Search in Rotated Sorted Array\nSuppose a sorted array is rotated at some pivot unknown to you beforehand. Find a given target value in the rotated array.\n\n**Example 1:**\n```\nInput: nums = [4,5,6,7,0,1,2], target = 0\nOutpu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8543, "level": 1, "question": "### Technical Interview Practice: Algorithms\n#### Problem: Search in Rotated Sorted Array\nSuppose a sorted array is rotated at some pivot unknown to you beforehand. Find a given target value in the rotated array.\n\n**Example 1:**\n```\nInput: nums =...
def rotate_matrix_clockwise(matrix: list[list[int]]) -> list[list[int]]: n = len(matrix) # Transpose the matrix in place for i in range(n): for j in range(i + 1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # Reverse each row in place for row in matrix: row...
simplelr_Algorithm
[ { "content": "Question:\n## Task\nWrite a function that takes a square matrix and rotates it 90 degrees clockwise with O(1) space complexity.\n\n### Function Signature\n```python\ndef rotate_matrix_clockwise(matrix: list[list[int]]) -> list[list[int]]:\n pass\n```\n\n### Input\n- A 2D list `matrix` represent...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8544, "level": 1, "question": "## Task\nWrite a function that takes a square matrix and rotates it 90 degrees clockwise with O(1) space complexity.\n\n### Function Signature\n```python\ndef rotate_matrix_clockwise(matrix: list[list[int]]) -> list[list[int]]:\n pass\n```\n\n### In...
def quick_sort(arr): if len(arr) <= 1: return arr first = arr[0] middle = arr[len(arr) // 2] last = arr[-1] # Determine the median of three if (first <= middle <= last) or (last <= middle <= first): pivot = middle elif (first <= last and last <= middle) or (middle <= las...
simplelr_Filter
[ { "content": "Question:\nSort a given array of integers using Quick Sort and make sure that the algorithm has a time complexity of O(nlogn) in all cases. Additionally, the algorithm should be implemented in a recursive manner and should not use any built-in sorting functions or libraries.\nAnswer:\nLet's think ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8545, "level": 1, "question": "Sort a given array of integers using Quick Sort and make sure that the algorithm has a time complexity of O(nlogn) in all cases. Additionally, the algorithm should be implemented in a recursive manner and should not use any built-in sorting functions o...
def rabin_karp_enhanced(pattern: str, text: str) -> int: # Check for edge cases where pattern is empty or longer than text if not pattern or len(pattern) > len(text): return -1 n = len(pattern) m = len(text) if m == 0: return -1 # If text is empty, return -1 base = 256...
simplelr_Data_Structure
[ { "content": "Question:\n### Rabin-Karp Algorithm Enhancement\n\n#### Problem Statement\nYou are given a pattern and a text, and you need to find the first occurrence of the pattern in the text using the Rabin-Karp algorithm. Your implementation needs to handle a larger character set (including digits and speci...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8546, "level": 1, "question": "### Rabin-Karp Algorithm Enhancement\n\n#### Problem Statement\nYou are given a pattern and a text, and you need to find the first occurrence of the pattern in the text using the Rabin-Karp algorithm. Your implementation needs to handle a larger charac...
import resource def manage_cpu_limit_and_usage(new_cpu_limit: int): # Retrieve current RLIMIT_CPU limits current_soft, current_hard = resource.getrlimit(resource.RLIMIT_CPU) print(f"Current CPU limits: soft={current_soft}, hard={current_hard}") # Attempt to set the new CPU limit if new_cpu_limit >...
simplelr_Docs
[ { "content": "Question:\n### Coding Assessment: System Resource Management with the `resource` Module\n\n#### Objective:\nYour task is to implement a Python function that:\n1. Retrieves the current resource limits for CPU time.\n2. Sets a new resource limit for CPU time.\n3. Retrieves resource usage statistics ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8547, "level": 1, "question": "### Coding Assessment: System Resource Management with the `resource` Module\n\n#### Objective:\nYour task is to implement a Python function that:\n1. Retrieves the current resource limits for CPU time.\n2. Sets a new resource limit for CPU time.\n3. R...
def remove_duplicates(lst): unique_list = [] for item in lst: if item not in unique_list: unique_list.append(item) return unique_list
simplelr_Filter
[ { "content": "Question:\nGiven a list of elements, write a Python program to remove all duplicates from the list. You should not use any built-in functions or methods in Python that directly solve this problem, such as set(), to make the exercise more challenging.\nAnswer:\nLet's think step by step.\n", "ro...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8548, "level": 1, "question": "Given a list of elements, write a Python program to remove all duplicates from the list. You should not use any built-in functions or methods in Python that directly solve this problem, such as set(), to make the exercise more challenging.", "split":...
from typing import List, Tuple def max_tasks(tasks: List[Tuple[int, int]]) -> int: if not tasks: return 0 # Sort the tasks based on their end times tasks.sort(key=lambda x: x[1]) count = 0 last_end = -1 # Initialize with a time before the earliest possible start time for...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of tasks where each task is represented by a start and end time. Implement a function to find the maximum number of tasks that can be executed without overlapping. Each task's start time is inclusive, and the end time is exclusive. If `[start, end)` represents a tas...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8549, "level": 1, "question": "You are given a list of tasks where each task is represented by a start and end time. Implement a function to find the maximum number of tasks that can be executed without overlapping. Each task's start time is inclusive, and the end time is exclusive....
def sort_comma_separated_integers(input_str): parts = input_str.split(',') numbers = [] for part in parts: stripped_part = part.strip() try: num = int(stripped_part) numbers.append(num) except ValueError: raise ValueError(f"Non-numeric element '{st...
simplelr_Evol
[ { "content": "Question:\nCreate a Python function that receives a string consisting of comma-separated integers and returns a list of these integers sorted in ascending order. The function should handle input validation by ensuring all elements are numeric and should raise an appropriate exception if any non-nu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8550, "level": 1, "question": "Create a Python function that receives a string consisting of comma-separated integers and returns a list of these integers sorted in ascending order. The function should handle input validation by ensuring all elements are numeric and should raise an ...
def right_rotate(lst: list, k: int) -> list: """ Rotate the given list to the right by k positions. This function handles cases where the number of rotations exceeds the length of the list by using modulo arithmetic. """ # Handle the case where the list is empty or no rotation is needed if not ...
simplelr_Algorithm
[ { "content": "Question:\nExtend the List Rotation Functionality \n\n#### Objective:\nImplement a function that performs a right rotation on a list of integers. In addition to rotating the list, the function should handle cases where the number of rotations is greater than the length of the list by utilizing mod...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8551, "level": 1, "question": "Extend the List Rotation Functionality \n\n#### Objective:\nImplement a function that performs a right rotation on a list of integers. In addition to rotating the list, the function should handle cases where the number of rotations is greater than the ...
def can_form_palindrome(s): # Create a dictionary to hold character counts char_count = {} # Count each character's frequency for char in s: if char in char_count: char_count[char] += 1 else: char_count[char] = 1 # Count the number of characters with...
simplelr_Filter
[ { "content": "Question:\nI'll be using a fixed-sized array to work with permutations of a fixed-size string. In regards to your knowledge about computer programming, would you say iterating over all the permutations of the string and checking if the resulting string is a palindrome is a viable approach in terms...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8552, "level": 1, "question": "I'll be using a fixed-sized array to work with permutations of a fixed-size string. In regards to your knowledge about computer programming, would you say iterating over all the permutations of the string and checking if the resulting string is a palin...
def remove_first_occurrence(lst, value): if value in lst: lst.pop(lst.index(value)) return lst
simplelr_Filter
[ { "content": "Question:\nGiven a list of strings, write a Python function to remove the first occurrence of a specified string from the list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8553, "level": 1, "question": "Given a list of strings, write a Python function to remove the first occurrence of a specified string from the list.", "split": "train" }
def countBuildingsWithSunlight(N, A): if N == 0: return 0 count = 1 max_h = A[0] for i in range(1, N): if A[i] > max_h: count += 1 max_h = A[i] return count
simplelr_Taco
[ { "content": "Question:\nYou are given an array of N integers where each element represents the height of a building. If a building receives enough sunlight, it generates energy. A building receives sunlight if there are no taller buildings to its left. Write a function to find the total number of buildings tha...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8554, "level": 1, "question": "You are given an array of N integers where each element represents the height of a building. If a building receives enough sunlight, it generates energy. A building receives sunlight if there are no taller buildings to its left. Write a function to fin...
def get_time_series_data(timestamps, values, frequency): new_timestamps = timestamps[::frequency] new_values = values[::frequency] return (new_timestamps, new_values)
simplelr_Filter
[ { "content": "Question:\nHere is a Python problem for you: Write a Python function named `get_time_series_data` that will take in an array of integers representing timestamps, an array of integers representing values, and an integer `frequency` which signifies the desired output frequency. For example, if the i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8555, "level": 1, "question": "Here is a Python problem for you: Write a Python function named `get_time_series_data` that will take in an array of integers representing timestamps, an array of integers representing values, and an integer `frequency` which signifies the desired outp...
def sum_of_even_numbers(numbers): return sum(num for num in numbers if num % 2 == 0)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of numbers and returns the sum of all even numbers in that list. The function should handle large numbers efficiently and avoid unnecessary computations.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8556, "level": 1, "question": "Create a function that takes a list of numbers and returns the sum of all even numbers in that list. The function should handle large numbers efficiently and avoid unnecessary computations.", "split": "train" }
def find_largest_sum_subarray(arr): if not arr: return None # Assuming the function should return None for empty arrays if allowed max_ending_here = max_so_far = arr[0] for num in arr[1:]: max_ending_here = max(num, max_ending_here + num) max_so_far = max(max_so_far, max_ending_here...
simplelr_Apps
[ { "content": "Question:\nWrite a function `findLargestSumSubarray` or `find_largest_sum_subarray` that takes an array of integers as an argument and returns the largest sum of any continuous subarray within the given array.\n\nExample: \nFor the array `[-2, 1, -3, 4, -1, 2, 1, -5, 4]`, the function should retur...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8557, "level": 1, "question": "Write a function `findLargestSumSubarray` or `find_largest_sum_subarray` that takes an array of integers as an argument and returns the largest sum of any continuous subarray within the given array.\n\nExample: \nFor the array `[-2, 1, -3, 4, -1, 2, 1,...
def concatenate_lists(list1, list2): return list1 + list2
simplelr_Filter
[ { "content": "Question:\nHere's another Python challenge! Write a Python program that takes two lists as input and returns a concatenated list with all elements from the first list followed by all elements from the second list.\n\n**Example:**\nInput:\n\n```\n\nlist1 = [1, 2, 3]\nlist2 = [4, 5, 6]\n```\n\nOutpu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8558, "level": 1, "question": "Here's another Python challenge! Write a Python program that takes two lists as input and returns a concatenated list with all elements from the first list followed by all elements from the second list.\n\n**Example:**\nInput:\n\n```\n\nlist1 = [1, 2, ...
def split_path(path: str) -> (str, str): last_slash = path.rfind('/') directory = path[:last_slash] filename = path[last_slash + 1:] return (directory, filename)
simplelr_Data_Structure
[ { "content": "Question:\nYou are tasked with implementing a function that splits a given file path or URL into its directory and file components. This function is critical for a file management application that needs to accurately parse and manipulate both local file paths and web URLs.\n\n### Function Specific...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8559, "level": 1, "question": "You are tasked with implementing a function that splits a given file path or URL into its directory and file components. This function is critical for a file management application that needs to accurately parse and manipulate both local file paths and...
def climb_stairs(n): if n == 0: return 1 elif n == 1: return 1 a, b = 1, 1 for _ in range(2, n + 1): a, b = b, a + b return b
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the total number of steps required to climb a staircase with a given number of steps, where you can either take 1 or 2 steps at a time. This problem can be solved using dynamic programming.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8560, "level": 1, "question": "Write a function to calculate the total number of steps required to climb a staircase with a given number of steps, where you can either take 1 or 2 steps at a time. This problem can be solved using dynamic programming.", "split": "train" }
def contains(arr, target): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return True elif arr[mid] < target: low = mid + 1 else: high = mid - 1 return False
simplelr_Filter
[ { "content": "Question:\nGiven a sorted array of integers and an integer, write a Python function to check if the array contains the given integer.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8561, "level": 1, "question": "Given a sorted array of integers and an integer, write a Python function to check if the array contains the given integer.", "split": "train" }
def get_value_at_index(arr, index): if index < 0 or index >= len(arr): raise IndexError("Index out of range.") return arr[index]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an array of integers and an integer index as parameters. The function should check if the given index is valid for the array and return the value at that index if it is valid. If the index is not valid, the function should raise an appropriate exception.\nAn...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8562, "level": 1, "question": "Create a function that takes an array of integers and an integer index as parameters. The function should check if the given index is valid for the array and return the value at that index if it is valid. If the index is not valid, the function should ...
def update_position(x, y, directions): for direction in directions: if direction == "north": y += 1 elif direction == "east": x += 1 elif direction == "south": y -= 1 elif direction == "west": x -= 1 return x, y
simplelr_Filter
[ { "content": "Question:\nThis is part of my code:\n\n```python\ndef update_position(x, y, direction):\n if direction == \"north\":\n y += 1\n elif direction == \"east\":\n x += 1\n elif direction == \"south\":\n y -= 1\n elif direction == \"west\":\n x -= 1\n return x, y\n```\n\nThis function t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8563, "level": 1, "question": "This is part of my code:\n\n```python\ndef update_position(x, y, direction):\n if direction == \"north\":\n y += 1\n elif direction == \"east\":\n x += 1\n elif direction == \"south\":\n y -= 1\n elif direction == \"west\":\n x -= 1\n ...
import math def manhattan_distance(x1, y1, x2, y2): dx = abs(x1 - x2) dy = abs(y1 - y2) return dx + dy print(manhattan_distance(5, 2, 8, 4))
simplelr_Filter
[ { "content": "Question:\nHere is the code for calculating the distance between two points in Euclidean space using Python:\n\n```python\nimport math\n\ndef distance(x1, y1, x2, y2):\n dx = x1 - x2 \n dy = y1 - y2\n d = math.sqrt(dx*dx + dy*dy)\n return d\n\nprint(distance(5, 2, 8, 4))\n```\n\nHow do...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8564, "level": 1, "question": "Here is the code for calculating the distance between two points in Euclidean space using Python:\n\n```python\nimport math\n\ndef distance(x1, y1, x2, y2):\n dx = x1 - x2 \n dy = y1 - y2\n d = math.sqrt(dx*dx + dy*dy)\n return d\n\nprint(d...
def count_vowels_consonants(s): result = {'vowels': 0, 'consonants': 0} vowels = {'a', 'e', 'i', 'o', 'u'} for char in s: if char.isalpha(): lower_char = char.lower() if lower_char in vowels: result['vowels'] += 1 else: result['cons...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string and outputs a dictionary with two keys: 'vowels' and 'consonants'. The function should count the number of vowels and consonants in the string. Vowels are 'a', 'e', 'i', 'o', 'u' (both lowercase and uppercase). Consonants are all alphabetic characte...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8565, "level": 1, "question": "Create a function that takes a string and outputs a dictionary with two keys: 'vowels' and 'consonants'. The function should count the number of vowels and consonants in the string. Vowels are 'a', 'e', 'i', 'o', 'u' (both lowercase and uppercase). Con...
def exponentiation(base, exponent): if exponent == 0: return 1 elif exponent < 0: return 1 / power(base, -exponent) else: result = 1 for _ in range(exponent): result *= base return result
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the result of exponentiation of a base and an exponent without using any built-in python function for that task.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8566, "level": 1, "question": "Write a python function to find the result of exponentiation of a base and an exponent without using any built-in python function for that task.", "split": "train" }
def matrix_combination(A, B, k): """ Computes the combination of two matrices A and B as per the formula kA + (2k - 3)B. Args: A (list of lists): The first 2D matrix. B (list of lists): The second 2D matrix. k (float): The scalar coefficient. Returns: list of li...
simplelr_Filter
[ { "content": "Question:\nGiven two matrices A and B, and a scalar k, how can you construct a python function that computes a combination of kA+(2k-3)B, where A, B are 2D arrays and k is a float? You should return the result as a 2D list. Additionally, make sure your function can handle matrix operations correct...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8567, "level": 1, "question": "Given two matrices A and B, and a scalar k, how can you construct a python function that computes a combination of kA+(2k-3)B, where A, B are 2D arrays and k is a float? You should return the result as a 2D list. Additionally, make sure your function c...
import numpy as np def solve_polynomial(a, b, c): coefficients = [a, b, c] return np.roots(coefficients)
simplelr_Filter
[ { "content": "Question:\nAfter importing the necessary modules, define a function `solve_polynomial` that takes three arguments: `a`, `b`, and `c`, which represent coefficients of a quadratic equation of the form `ax^2 + bx + c = 0`. \n\nUsing the `numpy` library's `roots()` function, compute and return the roo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8568, "level": 1, "question": "After importing the necessary modules, define a function `solve_polynomial` that takes three arguments: `a`, `b`, and `c`, which represent coefficients of a quadratic equation of the form `ax^2 + bx + c = 0`. \n\nUsing the `numpy` library's `roots()` f...
def reverse_array(arr): start = 0 end = len(arr) - 1 while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1 return arr
simplelr_Filter
[ { "content": "Question:\nReverse the order of elements in an array without using any built-in functions or creating a new array. The solution should have a time complexity of O(n) and should not use extra space beyond a few variables. The array will contain integers ranging from -10^9 to 10^9.\nAnswer:\nLet's t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8569, "level": 1, "question": "Reverse the order of elements in an array without using any built-in functions or creating a new array. The solution should have a time complexity of O(n) and should not use extra space beyond a few variables. The array will contain integers ranging fr...
import string def word_frequencies(text: str) -> dict: # Convert the text to lowercase text_lower = text.lower() # Create a translation table to remove all punctuation except hyphens translator = str.maketrans('', '', ''.join([c for c in string.punctuation if c != '-'])) text_no_punct = text_l...
simplelr_Package
[ { "content": "Question:\nYou are asked to write a function named `word_frequencies` that takes a string containing an entire text document and returns a dictionary where the keys are words in the document and the values are the number of times each word appears. The function should ignore punctuation, be case-i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8570, "level": 1, "question": "You are asked to write a function named `word_frequencies` that takes a string containing an entire text document and returns a dictionary where the keys are words in the document and the values are the number of times each word appears. The function s...
def fibonacci_below_n(n): fibs = [] a, b = 0, 1 while a < n: fibs.append(a) a, b = b, a + b return fibs
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to print out all Fibonacci numbers below a certain number n.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8571, "level": 1, "question": "Write a python function to print out all Fibonacci numbers below a certain number n.", "split": "train" }
def multiply_and_shift(numbers, multiplier, shift): result = [] for num in numbers: multiplied = num * multiplier if shift == 0: shifted = multiplied else: if multiplied < 0: shifted = (abs(multiplied) >> shift) else: sh...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of numbers, a multiplier value, and a shifting value as inputs. The function should first multiply each element in the list by the multiplier. After multiplication, it should shift each element to the right by the specified shifting value, disca...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8572, "level": 1, "question": "Write a Python function that takes a list of numbers, a multiplier value, and a shifting value as inputs. The function should first multiply each element in the list by the multiplier. After multiplication, it should shift each element to the right by ...
def xor_cipher(text, key, mode='encrypt'): """ Encrypt or decrypt the given text using XOR cipher with the provided key. Args: text (str): The text to be encrypted or decrypted. key (str): The key used for encryption/decryption. mode (str, optional): 'encrypt' or 'decrypt'. Defaults...
simplelr_Filter
[ { "content": "Question:\nPlease provide a Python code to implement a simple encryption and decryption using XOR cipher with a key.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8573, "level": 1, "question": "Please provide a Python code to implement a simple encryption and decryption using XOR cipher with a key.", "split": "train" }
import shlex def process_shell_commands(commands: list) -> list: processed_commands = [] for command in commands: tokens = shlex.split(command, posix=True) processed_command = shlex.join(tokens) processed_commands.append(processed_command) return processed_commands
simplelr_Docs
[ { "content": "Question:\n**Objective:**\nImplement a Python function using the `shlex` module to safely parse and join shell-like command strings.\n\n**Problem Statement:**\n\nYou are given a script to parse and join shell command strings using the `shlex` module to prevent command injection vulnerabilities and...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8574, "level": 1, "question": "**Objective:**\nImplement a Python function using the `shlex` module to safely parse and join shell-like command strings.\n\n**Problem Statement:**\n\nYou are given a script to parse and join shell command strings using the `shlex` module to prevent co...
def sort_dict_by_values_desc(d): return dict(sorted(d.items(), key=lambda item: item[1], reverse=True))
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to sort the items in a given dictionary by their values in descending order. I'll provide the dictionary as an argument and get the sorted dictionary in return. Please include a brief explanation of your code.\nAnswer:\nLet's think step by step.\n", "role": "...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8575, "level": 1, "question": "Write a python function to sort the items in a given dictionary by their values in descending order. I'll provide the dictionary as an argument and get the sorted dictionary in return. Please include a brief explanation of your code.", "split": "trai...
def find_max(nums): if not nums: return None return max(nums)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of numbers as input and returns the maximum number from the list. If the list is empty, the function should return `None`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8576, "level": 1, "question": "Write a Python function that takes a list of numbers as input and returns the maximum number from the list. If the list is empty, the function should return `None`.", "split": "train" }
def reverse_list(lst): n = len(lst) for i in range(n // 2): lst[i], lst[n - 1 - i] = lst[n - 1 - i], lst[i] return lst
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to reverse the order of the elements in a list using an iterative approach.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8577, "level": 1, "question": "Write a python function to reverse the order of the elements in a list using an iterative approach.", "split": "train" }
from typing import List, Union, Tuple, Dict def fizzbuzz_adjacent(n: int) -> Tuple[List[Union[int, str]], Dict[str, int]]: counts = {'Fizz': 0, 'Buzz': 0, 'FizzBuzz': 0} result = [] for i in range(1, n + 1): if i % 3 == 0 and i % 5 == 0: result.append('FizzBuzz') counts['Fiz...
simplelr_Data_Structure
[ { "content": "Question:\n### FizzBuzz Adjacent Counting\n\n**Objective**: Develop a modified version of the classic FizzBuzz problem, called FizzBuzz Adjacent Counting.\n\n**Scenario**: In this variation, for each number, the rules for Fizz, Buzz, and FizzBuzz remain unchanged. However, after replacing values w...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8578, "level": 1, "question": "### FizzBuzz Adjacent Counting\n\n**Objective**: Develop a modified version of the classic FizzBuzz problem, called FizzBuzz Adjacent Counting.\n\n**Scenario**: In this variation, for each number, the rules for Fizz, Buzz, and FizzBuzz remain unchanged...
def trap(heights): left = 0 right = len(heights) - 1 max_left = max_right = 0 res = 0 while left <= right: if max_left < max_right: if heights[left] > max_left: max_left = heights[left] else: res += max_left - heights[left] ...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integer heights `heights` representing a terrain, where each index represents a different position on the terrain, and the value at each index represents the height at that position. Compute the maximum amount of water that can be trapped after raining, assuming that t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8579, "level": 1, "question": "Given an array of integer heights `heights` representing a terrain, where each index represents a different position on the terrain, and the value at each index represents the height at that position. Compute the maximum amount of water that can be tra...
from typing import List def compute_prime_factors(n: int) -> List[int]: factors = [] # Handle the factor 2 separately while n % 2 == 0: factors.append(2) n = n // 2 # Now n must be odd, start from 3 and check up to sqrt(n) i = 3 while i * i <= n: while n % i ==...
simplelr_Package
[ { "content": "Question:\nYou are tasked with writing a Python function named `compute_prime_factors` that computes the prime factors of a given positive integer. Prime factors of a number are the prime numbers that divide the number exactly without leaving a remainder. Each prime factor should appear in the out...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8580, "level": 1, "question": "You are tasked with writing a Python function named `compute_prime_factors` that computes the prime factors of a given positive integer. Prime factors of a number are the prime numbers that divide the number exactly without leaving a remainder. Each pr...
import json def parse_json_response(json_str, key_path): try: data = json.loads(json_str) except json.JSONDecodeError: return None current = data if not key_path: return current for key in key_path: if isinstance(current, dict): if isinstance(ke...
simplelr_Filter
[ { "content": "Question:\nDesign a Python function to parse a JSON response from a REST API. The function should take a JSON string as input and extract a specific piece of data, as specified by a key path provided as a list. For example, if the JSON is a nested structure and the key path is ['user', 'name'], th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8581, "level": 1, "question": "Design a Python function to parse a JSON response from a REST API. The function should take a JSON string as input and extract a specific piece of data, as specified by a key path provided as a list. For example, if the JSON is a nested structure and t...
def calculate_edit_distance(word_a: str, word_b: str) -> int: len_a = len(word_a) len_b = len(word_b) # Handle the special case where one of the words is empty if len_a == 0: return len_b if len_b == 0: return len_a # Initialize the previous row prev_row = [j for j ...
simplelr_Data_Structure
[ { "content": "Question:\n**Question**:\n\n### Scenario\nYou are working on a new feature for a spell checker that suggests the closest valid word for a given misspelled word. To achieve this, you need to calculate the minimum number of operations required to transform a misspelled word into a valid dictionary w...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8582, "level": 1, "question": "**Question**:\n\n### Scenario\nYou are working on a new feature for a spell checker that suggests the closest valid word for a given misspelled word. To achieve this, you need to calculate the minimum number of operations required to transform a misspe...
from typing import List def get_pascals_triangle_row(n: int) -> List[int]: """Returns the nth row of Pascal's Triangle.""" if n == 0: return [1] row = [1] for k in range(1, n + 1): next_val = row[-1] * (n - (k - 1)) // k row.append(next_val) return row
simplelr_Algorithm
[ { "content": "Question:\n## Question\n\nYour task is to implement a function that generates the `n`th row of Pascal's Triangle. Pascal's Triangle is a triangular array of the binomial coefficients. Given a non-negative index `n`, return the `n`th row of the triangle.\n\n### Function Signature\n```python\ndef ge...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8583, "level": 1, "question": "## Question\n\nYour task is to implement a function that generates the `n`th row of Pascal's Triangle. Pascal's Triangle is a triangular array of the binomial coefficients. Given a non-negative index `n`, return the `n`th row of the triangle.\n\n### Fu...
from collections import Counter def is_permutation(s1: str, s2: str) -> bool: """ Function to check if one string is a permutation of another. Args: s1 (str): The first string for permutation check. s2 (str): The second string for permutation check. Returns: bool: True if s1 is a ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Description\nYou are required to implement a function that checks if a given string `s1` is a permutation of another string `s2`. A permutation is defined as a rearrangement of the characters of a string to form another string. The strings are case-sensitive and whitespace i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8584, "level": 1, "question": "### Problem Description\nYou are required to implement a function that checks if a given string `s1` is a permutation of another string `s2`. A permutation is defined as a rearrangement of the characters of a string to form another string. The strings ...
def find_pair(arr, target_sum): seen = set() for num in arr: complement = target_sum - num if complement in seen: return [complement, num] seen.add(num) return None
simplelr_Filter
[ { "content": "Question:\nI have an array of integers and I want to find the first pair of elements that add up to a given sum. I want the function to return the pair of elements, or null if no such pair exists.\n\nHere's my implementation in Python:\n\n```python\ndef find_pair(arr, target_sum):\n for i in ra...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8585, "level": 1, "question": "I have an array of integers and I want to find the first pair of elements that add up to a given sum. I want the function to return the pair of elements, or null if no such pair exists.\n\nHere's my implementation in Python:\n\n```python\ndef find_pair...
def maxSublistSum(arr): if not arr: return 0 # Handles empty list case, though problem states at least one element max_current = max_global = arr[0] for num in arr[1:]: max_current = max(num, max_current + num) if max_current > max_global: max_global = max_curr...
simplelr_Taco
[ { "content": "Question:\nGiven a list of N integers, the task is to find the maximum sum of a sublist, where the sublist contains at least one element.\n\nExample 1:\nInput:\nN = 5\nlist = {-2, 1, -3, 4, -1, 2, 1, -5, 4}\nOutput:\n6\nExplanation: The sublist [4, -1, 2, 1] has the maximum sum 6.\n\nYour Task:\nY...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8586, "level": 1, "question": "Given a list of N integers, the task is to find the maximum sum of a sublist, where the sublist contains at least one element.\n\nExample 1:\nInput:\nN = 5\nlist = {-2, 1, -3, 4, -1, 2, 1, -5, 4}\nOutput:\n6\nExplanation: The sublist [4, -1, 2, 1] has ...
def min_deletions(word1: str, word2: str) -> int: m = len(word1) n = len(word2) # Create a DP table of (m+1) x (n+1) initialized to 0 dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if word1[i-1] == word2[j-1]: d...
simplelr_Data_Structure
[ { "content": "Question:\n### Question: Minimum Deletions to Make Strings Same\n\nYou are given two words, `word1` and `word2`. Write a function `min_deletions(word1, word2)` that finds the minimum number of steps required to make both words the same by only deleting characters in either of the words.\n\n#### In...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8587, "level": 1, "question": "### Question: Minimum Deletions to Make Strings Same\n\nYou are given two words, `word1` and `word2`. Write a function `min_deletions(word1, word2)` that finds the minimum number of steps required to make both words the same by only deleting characters...
from typing import List def validate_sorting(stack: List[int]) -> bool: if len(stack) <= 1: return True for i in range(len(stack) - 1): if stack[i] > stack[i+1]: return False return True
simplelr_Data_Structure
[ { "content": "Question:\n**Question: Validate Stack Sorting Using Functions**\n\nA software system maintains a stack when processing data. For an efficient operation, it's crucial to ensure that the stack is sorted in ascending order from bottom to top. Implement a function `validate_sorting` that validates the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8588, "level": 1, "question": "**Question: Validate Stack Sorting Using Functions**\n\nA software system maintains a stack when processing data. For an efficient operation, it's crucial to ensure that the stack is sorted in ascending order from bottom to top. Implement a function `v...
def max_or_sum(a, b): if a == b: return a + b else: if isinstance(a, complex) or isinstance(b, complex): m_a = abs(a) m_b = abs(b) if m_a > m_b: return a elif m_b > m_a: return b else: ret...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that returns the maximum of two numbers. If the numbers are equal, return their sum. If the numbers are complex, compare their magnitudes and return the one with the greater magnitude. If the magnitudes are equal, return their sum.\nAnswer:\nLet's think step by s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8589, "level": 1, "question": "Write a Python function that returns the maximum of two numbers. If the numbers are equal, return their sum. If the numbers are complex, compare their magnitudes and return the one with the greater magnitude. If the magnitudes are equal, return their s...
import os def modify_env_and_file_operations() -> str: # Environment variable handling try: existing_user = os.environ.get('USER') print(f"Current USER variable: {existing_user}") my_var_value = 'Hello, World!' os.environ['MY_VAR'] = my_var_value new_my_var = os...
simplelr_Docs
[ { "content": "Question:\n**Coding Assessment Question**\n\n### Objective:\nTo assess your understanding of environment variable manipulation and file handling in Python using the `os` module, which supersedes the `posix` module interface.\n\n### Problem Statement:\nYou are required to write a Python function th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8590, "level": 1, "question": "**Coding Assessment Question**\n\n### Objective:\nTo assess your understanding of environment variable manipulation and file handling in Python using the `os` module, which supersedes the `posix` module interface.\n\n### Problem Statement:\nYou are req...
def has_pair_with_sum(arr, x): seen = set() for num in arr: complement = x - num if complement in seen: return True seen.add(num) return False
simplelr_Leetcode
[ { "content": "Question:\nYou are given an integer array `arr` and an integer `x`. Your task is to determine if there exists a pair of elements in the array whose sum is equal to `x`. Return `true` if such a pair exists, otherwise return `false`. Note that each element in the array can only be used once in a pai...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8591, "level": 1, "question": "You are given an integer array `arr` and an integer `x`. Your task is to determine if there exists a pair of elements in the array whose sum is equal to `x`. Return `true` if such a pair exists, otherwise return `false`. Note that each element in the a...
def find_smallest_missing_positive(nums): current_expected = 1 for num in nums: if num < current_expected: continue elif num == current_expected: current_expected += 1 else: return current_expected return current_expected
simplelr_Code_Contests
[ { "content": "Question:\nYou are given an integer array nums sorted in non-decreasing order. Find the smallest positive integer that is not present in the array. The solution should have a time complexity of O(N) and use constant extra space.\n\nConstraints\n\n* 1 \\leq nums.length \\leq 10^5\n* -10^9 \\leq num...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8592, "level": 1, "question": "You are given an integer array nums sorted in non-decreasing order. Find the smallest positive integer that is not present in the array. The solution should have a time complexity of O(N) and use constant extra space.\n\nConstraints\n\n* 1 \\leq nums.l...
def rle_encode(data): if not data: return [] result = [] current_char = None count = 0 for char in data: if char == current_char: count += 1 else: if current_char is not None: result.append((current_char, count)) current_cha...
simplelr_Apps
[ { "content": "Question:\nYou are working on a project involving data compression and need to implement a simple Run-Length Encoding (RLE) algorithm. RLE is a lossless data compression technique where runs of data (consecutive identical elements) are stored as a single data value and count rather than as the ori...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8593, "level": 1, "question": "You are working on a project involving data compression and need to implement a simple Run-Length Encoding (RLE) algorithm. RLE is a lossless data compression technique where runs of data (consecutive identical elements) are stored as a single data val...
def min_repeats(A: str, B: str) -> int: n = len(A) m = len(B) # Check if all characters in B are present in A set_A = set(A) for c in B: if c not in set_A: return -1 # If B is empty, return 0 (though per problem statement, B is non-empty) if m == 0: retu...
simplelr_Data_Structure
[ { "content": "Question:\n#### Background\nIn fields like Bioinformatics, strings often need to be repeated and checked for substrings to identify genetic markers. As a practical application, imagine you need to find the minimum number of times a DNA sequence (string A) must be repeated such that another sequenc...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8594, "level": 1, "question": "#### Background\nIn fields like Bioinformatics, strings often need to be repeated and checked for substrings to identify genetic markers. As a practical application, imagine you need to find the minimum number of times a DNA sequence (string A) must be...
def find_nth_digit(n): start = 1 digits = 1 while n > 9 * start * digits: n -= 9 * start * digits start *= 10 digits += 1 number = start + (n - 1) // digits digit_index = (n - 1) % digits return int(str(number)[digit_index])
simplelr_Data_Structure
[ { "content": "Question:\n### Algorithm and Data Structure Assessment\n\n#### Context\nIn mathematical sequences or computing problems, it's sometimes necessary to find specific elements directly rather than generating or storing the whole sequence, which can be infeasible due to space or time constraints.\n\n##...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8595, "level": 1, "question": "### Algorithm and Data Structure Assessment\n\n#### Context\nIn mathematical sequences or computing problems, it's sometimes necessary to find specific elements directly rather than generating or storing the whole sequence, which can be infeasible due ...
def min_operations(str1, str2): m = len(str1) n = len(str2) # Create a DP table of (m+1) x (n+1) 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] = j # Fill the D...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the minimum number of operations required to convert a given string to another string by performing the following operations: insert, delete, or replace a character.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8596, "level": 1, "question": "Write a function to find the minimum number of operations required to convert a given string to another string by performing the following operations: insert, delete, or replace a character.", "split": "train" }
def is_palindrome(s: str) -> bool: # Process the string: keep only alphanumeric characters and convert to lowercase processed = ''.join([c.lower() for c in s if c.isalnum()]) # Check if the processed string is equal to its reverse return processed == processed[::-1]
simplelr_Filter
[ { "content": "Question:\nHow can I determine if a string in Python is a palindrome, ignoring case and non-alphanumeric characters?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8597, "level": 1, "question": "How can I determine if a string in Python is a palindrome, ignoring case and non-alphanumeric characters?", "split": "train" }
def compressString(s): if not s: return s res = [] current_char = s[0] count = 1 for i in range(1, len(s)): if s[i] == current_char: count += 1 else: if count == 1: res.append(current_char) else: re...
simplelr_Taco
[ { "content": "Question:\nYou are given a string S consisting of lowercase letters and you've been asked to compress this string by using the following method:\n\nFind all the contiguous substrings in the string that are composed of repeated characters. Replace each of these substrings with a single instance of ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8598, "level": 1, "question": "You are given a string S consisting of lowercase letters and you've been asked to compress this string by using the following method:\n\nFind all the contiguous substrings in the string that are composed of repeated characters. Replace each of these su...
from typing import List, Dict, Any def categorize_books(books: List[Dict[str, Any]]) -> Dict[str, Dict[str, List[str]]]: result = {} for book in books: genre = book['genre'] is_available = book['is_available'] status = 'available' if is_available else 'checked_out' title = book[...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\nYou are developing a software package for a library management system. As part of the system's functionality, you need to implement a feature that categorizes books based on their genres and availability status.\n\n#### Task\nWrite a function `categoriz...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8599, "level": 1, "question": "### Coding Assessment Question\n\nYou are developing a software package for a library management system. As part of the system's functionality, you need to implement a feature that categorizes books based on their genres and availability status.\n\n###...