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 longestSubstringWithKDistinct(s: str, k: int) -> str: if k == 0 or not s: return "" char_count = {} left = 0 max_length = 0 start = 0 for right in range(len(s)): char = s[right] if char in char_count: char_count[char] += 1 else: ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` and an integer `k`. You need to find the longest substring of `s` that contains at most `k` distinct characters. If there are multiple such substrings of the same length, return the one that appears first. Implement the method:\n\n```python\ndef longestSubstri...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9300, "level": 1, "question": "You are given a string `s` and an integer `k`. You need to find the longest substring of `s` that contains at most `k` distinct characters. If there are multiple such substrings of the same length, return the one that appears first. Implement the metho...
def factorial(n): if n < 0: raise ValueError("n must be a non-negative integer") elif n == 0 or n == 1: return 1 else: return n * factorial(n - 1)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that calculates the factorial of a given number using recursion. The function should take an integer as input and return the factorial of that integer. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.\nAnswer:\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9301, "level": 1, "question": "Create a function that calculates the factorial of a given number using recursion. The function should take an integer as input and return the factorial of that integer. The factorial of a non-negative integer n is the product of all positive integers ...
def transformString(s): frequency = {} order = [] for char in s: if char not in frequency: frequency[char] = 1 order.append(char) else: frequency[char] += 1 result = '' for char in order: result += char + str(frequency[char]) return res...
simplelr_Taco
[ { "content": "Question:\nGiven a string, transform it such that each character in the new string is followed by its frequency from the original string. \n\nExample 1:\nInput: \"aabbcc\"\nOutput: \"a2b2c2\"\nExplanation: Each character 'a', 'b', and 'c' appears twice in the input string, therefore the output str...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9302, "level": 1, "question": "Given a string, transform it such that each character in the new string is followed by its frequency from the original string. \n\nExample 1:\nInput: \"aabbcc\"\nOutput: \"a2b2c2\"\nExplanation: Each character 'a', 'b', and 'c' appears twice in the inp...
def maxProfit(prices): if not prices: return 0 sell0 = 0 buy1 = sell1 = buy2 = sell2 = float('-inf') for price in prices: buy1 = max(buy1, sell0 - price) sell1 = max(sell1, buy1 + price) buy2 = max(buy2, sell1 - price) sell2 = max(sell2, buy2 + price) return s...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the maximum profit you can achieve from selling and buying a stock multiple times. You are only allowed to complete at most two transactions (buy one and sell one, then buy one and sell one). The function should take a list of stock prices and return the ma...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9303, "level": 1, "question": "Write a function to calculate the maximum profit you can achieve from selling and buying a stock multiple times. You are only allowed to complete at most two transactions (buy one and sell one, then buy one and sell one). The function should take a lis...
def substring_index(main_str, sub_str): len_sub = len(sub_str) len_main = len(main_str) for i in range(len_main - len_sub + 1): if main_str[i:i + len_sub] == sub_str: return i return -1
simplelr_Filter
[ { "content": "Question:\nWrite a function that checks whether a substring is present in a given string, and if present, returns the starting index of the first occurrence of the substring. If the substring is not found, the function should return -1. The function should be case-sensitive.\nAnswer:\nLet's think ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9304, "level": 1, "question": "Write a function that checks whether a substring is present in a given string, and if present, returns the starting index of the first occurrence of the substring. If the substring is not found, the function should return -1. The function should be cas...
def threeSum(nums): nums.sort() res = [] n = len(nums) for i in range(n - 2): if i > 0 and nums[i] == nums[i - 1]: continue left = i + 1 right = n - 1 while left < right: current_sum = nums[i] + nums[left] + nums[right] if current_sum <...
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers nums, return all the triplets [nums[i], nums[j], nums[k]] such that i ≠ j, i ≠ k, and j ≠ k, and nums[i] + nums[j] + nums[k] == 0.\n\nNote: The solution set must not contain duplicate triplets.\n\nExample 1:\nInput: nums = [-1, 0, 1, 2, -1, -4]\nOutput: [[-1, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9305, "level": 1, "question": "Given an array of integers nums, return all the triplets [nums[i], nums[j], nums[k]] such that i ≠ j, i ≠ k, and j ≠ k, and nums[i] + nums[j] + nums[k] == 0.\n\nNote: The solution set must not contain duplicate triplets.\n\nExample 1:\nInput: nums = [-...
import csv def find_highest_average_temp(): city_data = {} with open('weather_data.csv', 'r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: city = row['City'] temp = float(row['Temperature']) if city in city_data: curren...
simplelr_Package
[ { "content": "Question:\nYou need to create a function `find_highest_average_temp` that reads a CSV file containing weather data and calculates the city with the highest average temperature. The CSV file, named `weather_data.csv`, will be in the same directory as your script.\n\nThe CSV file will contain the fo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9306, "level": 1, "question": "You need to create a function `find_highest_average_temp` that reads a CSV file containing weather data and calculates the city with the highest average temperature. The CSV file, named `weather_data.csv`, will be in the same directory as your script.\...
def longestPalindromicSubsequence(s: str) -> int: n = len(s) if n == 0: return 0 dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for length in range(2, n + 1): for i in range(n - length + 1): j = i + length - 1 if s[i] == s[j...
simplelr_Apps
[ { "content": "Question:\nGiven a string representing a sequence of numbers, determine the length of the longest palindromic subsequence. A palindromic subsequence is a sequence that reads the same backward as forward and can be formed by deleting some (or none) of the characters of the original string without c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9307, "level": 1, "question": "Given a string representing a sequence of numbers, determine the length of the longest palindromic subsequence. A palindromic subsequence is a sequence that reads the same backward as forward and can be formed by deleting some (or none) of the characte...
def min_cost_path(grid): m = len(grid) if m == 0: return 0 n = len(grid[0]) dp = [[0 for _ in range(n)] for _ in range(m)] dp[0][0] = grid[0][0] for i in range(m): for j in range(n): if i == 0 and j == 0: continue if i == 0: ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a two-dimensional grid of integers, where each cell in the grid contains a value that represents the cost to step on that cell. You are initially positioned at the top-left corner of the grid and you want to reach the bottom-right corner of the grid. You can only move eith...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9308, "level": 1, "question": "You are given a two-dimensional grid of integers, where each cell in the grid contains a value that represents the cost to step on that cell. You are initially positioned at the top-left corner of the grid and you want to reach the bottom-right corner ...
def longest_alternating_subsequence(nums): n = len(nums) if n == 0: return 0 up = [1] * n down = [1] * n for i in range(1, n): for j in range(i): if nums[i] > nums[j]: up[i] = max(up[i], down[j] + 1) elif nums[i] < nums[j]: down...
simplelr_Filter
[ { "content": "Question:\nI made the following Python code:\n\n```python\ndef longest_alternating_subsequence(nums):\n n = len(nums)\n if n == 0:\n return 0\n dp = [1] * n\n for i in range(1, n):\n for j in range(i):\n if (nums[i] > nums[j] and dp[i] < dp[j] + 1) or (nums[i] < nums[j] and dp[i] < ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9309, "level": 1, "question": "I made the following Python code:\n\n```python\ndef longest_alternating_subsequence(nums):\n n = len(nums)\n if n == 0:\n return 0\n dp = [1] * n\n for i in range(1, n):\n for j in range(i):\n if (nums[i] > nums[j] and dp[i] < dp[j] + 1)...
def smallest_unrepresentable_sum(lst): lst = sorted(lst) sum_so_far = 0 for num in lst: if num > sum_so_far + 1: return sum_so_far + 1 sum_so_far += num return sum_so_far + 1
simplelr_Leetcode
[ { "content": "Question:\nGiven an unsorted list of integers, write a function to find the smallest positive integer that cannot be represented as a sum of any subset of the list. For example, given the list [1, 2, 3, 8, 9], the smallest positive integer that cannot be represented as a sum of any subset of this ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9310, "level": 1, "question": "Given an unsorted list of integers, write a function to find the smallest positive integer that cannot be represented as a sum of any subset of the list. For example, given the list [1, 2, 3, 8, 9], the smallest positive integer that cannot be represen...
def square_elements(numbers): return [x ** 2 for x in numbers]
simplelr_Evol
[ { "content": "Question:\nDesign a Python function that takes a list of integers as input and returns a new list where each element is the square of the corresponding element in the input list. The function should handle an empty list appropriately and return an empty list in such a case.\nAnswer:\nLet's think s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9311, "level": 1, "question": "Design a Python function that takes a list of integers as input and returns a new list where each element is the square of the corresponding element in the input list. The function should handle an empty list appropriately and return an empty list in s...
def longest_mountain(arr): n = len(arr) if n < 3: return 0 up = [1] * n for i in range(1, n): if arr[i] > arr[i-1]: up[i] = up[i-1] + 1 down = [1] * n for i in range(n-2, -1, -1): if arr[i] > arr[i+1]: down[i] = down[i+1] + 1 max...
simplelr_Algorithm
[ { "content": "Question:\n### Algorithm Question: Finding the Longest Mountain in an Array\n\nA mountain is defined as a subarray that satisfies the following conditions:\n1. It has at least 3 elements.\n2. There exists some index \\(i\\) with \\(0 < i < k - 1\\) such that:\n - `arr[0] < arr[1] < ... < arr[i]...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9312, "level": 1, "question": "### Algorithm Question: Finding the Longest Mountain in an Array\n\nA mountain is defined as a subarray that satisfies the following conditions:\n1. It has at least 3 elements.\n2. There exists some index \\(i\\) with \\(0 < i < k - 1\\) such that:\n ...
def classify_tweet_sentiment(tweet, vocabulary): total = 0 words = tweet.split() for word in words: processed_word = ''.join([c for c in word if c.isalpha()]).lower() if processed_word in vocabulary: total += vocabulary[processed_word] if total > 0: return 'positive' ...
simplelr_Algorithm
[ { "content": "Question:\n### Twitter Sentiment Analysis\n\nYou are working on developing a Twitter sentiment analysis tool that can classify tweets as positive, negative, or neutral. For this task, you need to implement a basic version of the sentiment analysis algorithm using the Bag of Words (BoW) model. The ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9313, "level": 1, "question": "### Twitter Sentiment Analysis\n\nYou are working on developing a Twitter sentiment analysis tool that can classify tweets as positive, negative, or neutral. For this task, you need to implement a basic version of the sentiment analysis algorithm using...
def computeFactorial(n): # Check if n is a valid integer if not (isinstance(n, int) or (isinstance(n, float) and n.is_integer())): return "Invalid input" n = int(n) # Check for negative numbers if n < 0: return "Invalid input" # Base cases if n == 0 or n == 1: return ...
simplelr_Filter
[ { "content": "Question:\nWrite a function called computeFactorial that takes a numeric value as input and returns the factorial of that number. The function should return the string \"Number too large\" if the factorial of the number is greater than 10^100. The function should handle input numbers up to 1000. T...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9314, "level": 1, "question": "Write a function called computeFactorial that takes a numeric value as input and returns the factorial of that number. The function should return the string \"Number too large\" if the factorial of the number is greater than 10^100. The function should...
def calculate_total_cost(books): total = 0.0 for book in books: total += book['price'] * book['quantity'] return round(total, 2)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that calculates the total cost of a list of books where each book has a title, price, and quantity. The function should return the total cost, formatted to two decimal places.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9315, "level": 1, "question": "Write a Python function that calculates the total cost of a list of books where each book has a title, price, and quantity. The function should return the total cost, formatted to two decimal places.", "split": "train" }
def find_nth_digit(n: int) -> int: digits = 1 count = 9 start = 1 while n > digits * count: n -= digits * count digits += 1 count = 9 * (10 ** (digits - 1)) start = 10 ** (digits - 1) number = start + (n - 1) // digits digit_index = (n - 1) % digits ...
simplelr_Data_Structure
[ { "content": "Question:\n### Problem Description\nIn the infinite sequence of decimal digits formed by concatenating positive integers (123456789101112...), write a function that efficiently finds and returns the nth digit.\n\n## Function Signature\n```python\ndef find_nth_digit(n: int) -> int:\n```\n\n### Inpu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9316, "level": 1, "question": "### Problem Description\nIn the infinite sequence of decimal digits formed by concatenating positive integers (123456789101112...), write a function that efficiently finds and returns the nth digit.\n\n## Function Signature\n```python\ndef find_nth_dig...
def net_balance(transactions): balance_dict = {} for transaction in transactions: buyer, seller, amount = transaction if buyer in balance_dict: balance_dict[buyer] -= amount else: balance_dict[buyer] = -amount if seller in balance_dict: balance...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a 2D integer array `transactions` where `transactions[i] = [buyerId, sellerId, amount]`, representing a transaction where the buyer with `buyerId` pays the seller with `sellerId` an `amount` of money. Your task is to determine the net balance of each person. Return a 2D in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9317, "level": 1, "question": "You are given a 2D integer array `transactions` where `transactions[i] = [buyerId, sellerId, amount]`, representing a transaction where the buyer with `buyerId` pays the seller with `sellerId` an `amount` of money. Your task is to determine the net bal...
def prime_factors(n): factors = {} # Handle the factor 2 separately count = 0 while n % 2 == 0: count += 1 n = n // 2 if count > 0: factors[2] = count # Check for odd factors starting from 3 i = 3 while i * i <= n: count = 0 while n % i == 0: ...
simplelr_Taco
[ { "content": "Question:\nA prime factorization of a number involves breaking down the number into its prime components. For instance, the prime factorization of 28 is 2 * 2 * 7. We can represent this more formally as:\n\n28 = 2^2 * 7^1\n\nWrite a function `prime_factors` that takes an integer `n` (where n > 1) ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9318, "level": 1, "question": "A prime factorization of a number involves breaking down the number into its prime components. For instance, the prime factorization of 28 is 2 * 2 * 7. We can represent this more formally as:\n\n28 = 2^2 * 7^1\n\nWrite a function `prime_factors` that ...
def find_kth_largest(k, nums): sorted_nums = sorted(nums, reverse=True) return sorted_nums[k-1]
simplelr_Apps
[ { "content": "Question:\nCreate a function `find_kth_largest` that takes an integer `k` and a list of integers as parameters. The function should return the kth largest element in the list. Note that it is the kth largest element in the sorted order, not the kth distinct element.\n\nFor example:\n```python\nfin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9319, "level": 1, "question": "Create a function `find_kth_largest` that takes an integer `k` and a list of integers as parameters. The function should return the kth largest element in the list. Note that it is the kth largest element in the sorted order, not the kth distinct eleme...
def min_difference(arr): total = sum(arr) if total == 0: return 0 target = total // 2 dp = [False] * (target + 1) dp[0] = True for num in arr: for j in range(target, num - 1, -1): if dp[j - num]: dp[j] = True max_sum = 0 for j in range(target, ...
simplelr_Codeforces
[ { "content": "Question:\nYou are given an array of integers where each element represents the number of candies in a box. Your goal is to distribute these boxes into two groups such that the absolute difference between the total candies in each group is minimized.\n\nYou are allowed to:\n1. Select any subset of...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9320, "level": 1, "question": "You are given an array of integers where each element represents the number of candies in a box. Your goal is to distribute these boxes into two groups such that the absolute difference between the total candies in each group is minimized.\n\nYou are a...
def reverse_words_in_sentences(sentences): return [' '.join(reversed(sentence.split())) for sentence in sentences]
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that takes a list of strings, each representing a sentence, and returns a list of sentences where each sentence has its words in reverse order. The words in each sentence are separated by spaces.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9321, "level": 1, "question": "Create a Python function that takes a list of strings, each representing a sentence, and returns a list of sentences where each sentence has its words in reverse order. The words in each sentence are separated by spaces.", "split": "train" }
def contains_duplicates(numbers: list[int]) -> bool: return len(numbers) != len(set(numbers))
simplelr_Algorithm
[ { "content": "Question:\n### Question Description\nYou are required to implement a function that checks if a given list of integers contains any duplicates. This exercise will validate your understanding of data structures and efficient search algorithms.\n\n### Function Signature\n```python\ndef contains_dupli...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9322, "level": 1, "question": "### Question Description\nYou are required to implement a function that checks if a given list of integers contains any duplicates. This exercise will validate your understanding of data structures and efficient search algorithms.\n\n### Function Signa...
def multiply_elements_by_index(lst): result = [] for index, element in enumerate(lst): result.append(element * index) return result
simplelr_Evol
[ { "content": "Question:\nYou are given a list of integers. Write a Python function that returns a new list which contains each element of the original list multiplied by its index position. Ensure that your solution handles edge cases such as an empty list or a list with negative integers. \n\nFor example:\n```...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9323, "level": 1, "question": "You are given a list of integers. Write a Python function that returns a new list which contains each element of the original list multiplied by its index position. Ensure that your solution handles edge cases such as an empty list or a list with negat...
def search_user_id(user_ids, search_id): for index, id in enumerate(user_ids): if id == search_id: return index return -1
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario\nYou are a software engineer at a startup that manages a large database of user records. You frequently need to search for specific user records based on unique identifiers (ids). The user ids are stored in an array that gets updated regularly, but it is not sorted. Your ta...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9324, "level": 1, "question": "### Scenario\nYou are a software engineer at a startup that manages a large database of user records. You frequently need to search for specific user records based on unique identifiers (ids). The user ids are stored in an array that gets updated regul...
import re def is_valid_mac_address(address): pattern = r'^([0-9A-Fa-f]{2}[:|-]){5}[0-9A-Fa-f]{2}$' return bool(re.fullmatch(pattern, address))
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that checks if a given string is a valid MAC address. A MAC address is valid if it follows the format of six groups of two hexadecimal digits, separated by colons (:) or hyphens (-). For example, \"01:23:45:67:89:AB\" and \"01-23-45-67-89-AB\" are valid. The func...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9325, "level": 1, "question": "Write a Python function that checks if a given string is a valid MAC address. A MAC address is valid if it follows the format of six groups of two hexadecimal digits, separated by colons (:) or hyphens (-). For example, \"01:23:45:67:89:AB\" and \"01-2...
def print_sum(a, b): print(a + b) # Example usage: print_sum(5, 7) # Outputs: 12
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes 2 numbers and prints the sum of these numbers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9326, "level": 1, "question": "Create a function that takes 2 numbers and prints the sum of these numbers.", "split": "train" }
def reverse_number(n): reversed_num = 0 while n > 0: last_digit = n % 10 reversed_num = reversed_num * 10 + last_digit n = n // 10 return reversed_num
simplelr_Filter
[ { "content": "Question:\nUse python to create a function that takes in a positive integer and returns it as a reversed whole number, stripping any leading zeros. For instance, if the input is 100, the output should be 1 (not 001). Address any potential issues resulting from integer overflow and prevent direct r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9327, "level": 1, "question": "Use python to create a function that takes in a positive integer and returns it as a reversed whole number, stripping any leading zeros. For instance, if the input is 100, the output should be 1 (not 001). Address any potential issues resulting from in...
def reverse_long_words(s): words = s.split() for i in range(len(words)): if len(words[i]) >= 5: words[i] = words[i][::-1] return ' '.join(words)
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a string of words separated by spaces, and returns the same string with all words that are five letters or longer reversed. \n\nExamples:\n\n- `\"Welcome to the coding challenge\"` would become `\"emocleW to the gnidoc egnellahc\"`\n- `\"This is an example of...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9328, "level": 1, "question": "Write a function that takes a string of words separated by spaces, and returns the same string with all words that are five letters or longer reversed. \n\nExamples:\n\n- `\"Welcome to the coding challenge\"` would become `\"emocleW to the gnidoc egnel...
def print_message(message): print(message) # Example usage print_message("Hello, World!")
simplelr_Prefill
[ { "content": "Question:\nWrite a function to print a message to the console.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9329, "level": 1, "question": "Write a function to print a message to the console.", "split": "train" }
from collections import defaultdict def find_pairs_with_sum(nums, target): seen = defaultdict(int) result = set() for num in nums: complement = target - num if seen[complement] > 0: pair = tuple(sorted((complement, num))) result.add(pair) seen[num] += 1 r...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find all pairs of elements in a list of integers that sum exactly to a given value. You should also handle cases where the list may contain duplicates and negative numbers. Your function should return a set of unique pairs (i.e., each pair should appear only o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9330, "level": 1, "question": "Write a python function to find all pairs of elements in a list of integers that sum exactly to a given value. You should also handle cases where the list may contain duplicates and negative numbers. Your function should return a set of unique pairs (i...
def is_prime(n): if n <= 1: return False elif n == 2: return True elif n % 2 == 0: return False max_divisor = int(n ** 0.5) + 1 for d in range(3, max_divisor, 2): if n % d == 0: return False return True
simplelr_Prefill
[ { "content": "Question:\nCreate a function that returns true if the input number is a prime number.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9331, "level": 1, "question": "Create a function that returns true if the input number is a prime number.", "split": "train" }
def product_of_numbers(s): if not s.strip(): return "Invalid input" parts = s.split(',') numbers = [] for part in parts: stripped = part.strip() if not stripped: return "Invalid input" try: num = int(stripped) except ValueError: ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in a string of numbers separated by commas and returns the product of all numbers in the string. The function should handle any number of numbers entered, and the string can contain both positive and negative integers. The function should return \"Invalid in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9332, "level": 1, "question": "Create a function that takes in a string of numbers separated by commas and returns the product of all numbers in the string. The function should handle any number of numbers entered, and the string can contain both positive and negative integers. The ...
def longest_common_subsequence(s: str, t: str) -> str: """ This function returns the longest common subsequence of two input strings using dynamic programming. Args: s (str): The first input string. t (str): The second input string. Returns: str: The longest common subs...
simplelr_Filter
[ { "content": "Question:\nHere is the question:\nString s = \"abcde\";\nString t = \"ace\";\nCreate a function that returns the longest common subsequence of s and t.\n\nHere is my current solution:\n```python\ndef longest_common_subsequence(s: str, t: str) -> str:\n \"\"\"\n This function returns the long...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9333, "level": 1, "question": "Here is the question:\nString s = \"abcde\";\nString t = \"ace\";\nCreate a function that returns the longest common subsequence of s and t.\n\nHere is my current solution:\n```python\ndef longest_common_subsequence(s: str, t: str) -> str:\n \"\"\"\...
def sum_intervals(intervals): if not intervals: return 0 # Sort the intervals based on their start values sorted_intervals = sorted(intervals, key=lambda x: x[0]) # Initialize the merged list with the first interval converted to a list for modification merged = [list(sorted_intervals[0])] ...
simplelr_Taco
[ { "content": "Question:\n### Description\nWrite a function that takes a list of integer intervals and returns the sum of the lengths of these intervals. Intervals may overlap, and if they do, they should only be counted once.\n\nThe input will be a list of tuples, where each tuple represents an interval with a ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9334, "level": 1, "question": "### Description\nWrite a function that takes a list of integer intervals and returns the sum of the lengths of these intervals. Intervals may overlap, and if they do, they should only be counted once.\n\nThe input will be a list of tuples, where each t...
def find_mode(lst): if not lst: return None freq = {} for num in lst: freq[num] = freq.get(num, 0) + 1 max_count = max(freq.values()) if max_count == 1: return None for num in lst: if freq[num] == max_count: return num
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of numbers as input and returns the number that appears most frequently in the list. If there is no mode (i.e., no number appears more than once), the function should return None.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9335, "level": 1, "question": "Create a function that takes a list of numbers as input and returns the number that appears most frequently in the list. If there is no mode (i.e., no number appears more than once), the function should return None.", "split": "train" }
from typing import List def merge_sorted_arrays(array1: List[int], array2: List[int]) -> List[int]: i = j = 0 merged = [] while i < len(array1) and j < len(array2): if array1[i] <= array2[j]: merged.append(array1[i]) i += 1 else: merged.append(array2[j]) ...
simplelr_Package
[ { "content": "Question:\nCreate a function called `merge_sorted_arrays` that merges two pre-sorted arrays into a single sorted array without using any built-in sorting function. \n\n### Function Specification:\n```python\ndef merge_sorted_arrays(array1: List[int], array2: List[int]) -> List[int]:\n \"\"\"\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9336, "level": 1, "question": "Create a function called `merge_sorted_arrays` that merges two pre-sorted arrays into a single sorted array without using any built-in sorting function. \n\n### Function Specification:\n```python\ndef merge_sorted_arrays(array1: List[int], array2: List...
from collections import deque def is_consecutive_sequence(stack: list[int]) -> bool: if len(stack) <= 1: return True dq = deque(stack) prev = dq.popleft() for num in dq: if num != prev + 1: return False prev = num return True
simplelr_Data_Structure
[ { "content": "Question:\n### Consecutive Sequence Validator\n\nAs a systems developer, you are tasked with developing a function to verify that a stack of integers maintains a sequence of consecutive numbers starting from the bottom of the stack to the top. Given that stacks operate in a Last In First Out (LIFO...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9337, "level": 1, "question": "### Consecutive Sequence Validator\n\nAs a systems developer, you are tasked with developing a function to verify that a stack of integers maintains a sequence of consecutive numbers starting from the bottom of the stack to the top. Given that stacks o...
def pairWithTargetSum(arr, target): seen = {} for i, num in enumerate(arr): complement = target - num if complement in seen: return [seen[complement], i] seen[num] = i return []
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers and a target integer, find two distinct elements in the array such that their sum is equal to the target. Return the indices of the two elements in ascending order. If there are multiple pairs, return the pair with the smallest index first. If no such pair exi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9338, "level": 1, "question": "Given an array of integers and a target integer, find two distinct elements in the array such that their sum is equal to the target. Return the indices of the two elements in ascending order. If there are multiple pairs, return the pair with the smalle...
def increase_ascii_by_one(s): return ''.join(chr(ord(c) + 1) for c in s)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as input and returns a new string with each character's ASCII value increased by 1. For example, if the input is \"hello\", the output should be \"ifmmp\".\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9339, "level": 1, "question": "Create a function that takes a string as input and returns a new string with each character's ASCII value increased by 1. For example, if the input is \"hello\", the output should be \"ifmmp\".", "split": "train" }
def find_substring(main_str, substr): return main_str.find(substr)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to identify the first occurrence of a substring within a string and return its index. If the substring is not found, return -1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9340, "level": 1, "question": "Write a python function to identify the first occurrence of a substring within a string and return its index. If the substring is not found, return -1.", "split": "train" }
from typing import List def maximum_value(weights: List[int], values: List[int], capacity: int) -> int: if capacity == 0 or not weights: return 0 n = len(weights) dp = [[0] * (capacity + 1) for _ in range(n + 1)] for i in range(1, n + 1): weight = weights[i-1] value = values[i-1...
simplelr_Algorithm
[ { "content": "Question:\n### Knapsack Problem Variant\n\n#### Problem Statement\n\nImplement a function `maximum_value` that calculates the maximum value that can be obtained by selecting items with given weight and value constraints to fit into a knapsack of a specified capacity. The function should solve the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9341, "level": 1, "question": "### Knapsack Problem Variant\n\n#### Problem Statement\n\nImplement a function `maximum_value` that calculates the maximum value that can be obtained by selecting items with given weight and value constraints to fit into a knapsack of a specified capac...
def two_sum(nums, target): seen = {} for i, num in enumerate(nums): complement = target - num if complement in seen: return [seen[complement], i] seen[num] = i return []
simplelr_Filter
[ { "content": "Question:\nThis problem requires a solution using dynamic programming.\n\n Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\n\n You may assume that each input would have exactly one solution, and you may not use the same elem...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9342, "level": 1, "question": "This problem requires a solution using dynamic programming.\n\n Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\n\n You may assume that each input would have exactly one solution...
def find_first_pair(arr1, arr2, target): i = 0 j = len(arr2) - 1 while i < len(arr1) and j >= 0: current_sum = arr1[i] + arr2[j] if current_sum == target: return (arr1[i], arr2[j]) elif current_sum < target: i += 1 else: j -= 1 return N...
simplelr_Filter
[ { "content": "Question:\nI have two sorted array of integers and I want to find the first pair of elements, one from each array, whose sum is equal to a given target.\n\nHere is a simple solution:\n```python\ndef find_first_pair(arr1, arr2, target):\n for i in range(len(arr1)):\n for j in range(len(ar...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9343, "level": 1, "question": "I have two sorted array of integers and I want to find the first pair of elements, one from each array, whose sum is equal to a given target.\n\nHere is a simple solution:\n```python\ndef find_first_pair(arr1, arr2, target):\n for i in range(len(arr...
import os import posix def update_environment_variable(var_name: str, new_value: str) -> str: """ Fetches the value of the given environment variable, updates it to the new value using the `os` module, and confirms the update using both `os` and `posix` modules. Parameters: var_name (str): The nam...
simplelr_Docs
[ { "content": "Question:\n#### Objective\nWrite a Python function that demonstrates the use of the `posix` module to access environment variables, and then illustrates how the `os` module can be used to update these variables effectively. The function should fetch a specific environment variable, update its valu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9344, "level": 1, "question": "#### Objective\nWrite a Python function that demonstrates the use of the `posix` module to access environment variables, and then illustrates how the `os` module can be used to update these variables effectively. The function should fetch a specific en...
from collections import defaultdict def smallestDistinctSubstring(s): uniqueCount = len(set(s)) if uniqueCount == 0: return 0 counts = defaultdict(int) have = 0 min_length = float('inf') left = 0 for right in range(len(s)): char = s[right] counts[char] += 1 i...
simplelr_Taco
[ { "content": "Question:\nGiven a string, find the length of the smallest contiguous substring that contains all the distinct characters of the original string at least once.\n\nExample 1:\nInput:\ns = \"aabcbcdbca\"\nOutput:\n4\nExplanation:\nThe substring \"dbca\" contains all the distinct characters (a, b, c,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9345, "level": 1, "question": "Given a string, find the length of the smallest contiguous substring that contains all the distinct characters of the original string at least once.\n\nExample 1:\nInput:\ns = \"aabcbcdbca\"\nOutput:\n4\nExplanation:\nThe substring \"dbca\" contains al...
def rotate_matrix(matrix): n = len(matrix) # Transpose the matrix 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 for row in matrix: row.reverse()
simplelr_Taco
[ { "content": "Question:\n### Mirror Image\n\nYou are given a square matrix of size `n x n`. Write a function that rotates the matrix 90 degrees clockwise. The rotation should be done in-place, which means you have to modify the input matrix directly.\n\n#### Function Signature\n```python\ndef rotate_matrix(matr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9346, "level": 1, "question": "### Mirror Image\n\nYou are given a square matrix of size `n x n`. Write a function that rotates the matrix 90 degrees clockwise. The rotation should be done in-place, which means you have to modify the input matrix directly.\n\n#### Function Signature...
def PrimeFactorization(M): factors = {} # Handle the factor 2 separately while M % 2 == 0: factors[2] = factors.get(2, 0) + 1 M = M // 2 # Now M must be odd, start from 3 i = 3 while i * i <= M: while M % i == 0: factors[i] = factors.get(i, 0) + 1 ...
simplelr_Taco
[ { "content": "Question:\nWrite a function `PrimeFactorization` that takes an integer `M` as input and returns a dictionary where the keys are the prime factors of `M` and the values are their corresponding powers in the prime factorization of `M`.\n\nFor instance, given `M = 360`, the prime factorization is `36...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9347, "level": 1, "question": "Write a function `PrimeFactorization` that takes an integer `M` as input and returns a dictionary where the keys are the prime factors of `M` and the values are their corresponding powers in the prime factorization of `M`.\n\nFor instance, given `M = 3...
def reverse_hex_string(hex_string): return hex_string[::-1]
simplelr_Filter
[ { "content": "Question:\nWrite a function that takes a hexadecimal string as an argument and returns the string in reverse order.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9348, "level": 1, "question": "Write a function that takes a hexadecimal string as an argument and returns the string in reverse order.", "split": "train" }
from sklearn.metrics import precision_recall_curve, average_precision_score import matplotlib.pyplot as plt def evaluate_classifier(y_true, y_probs, title=None): # Calculate precision, recall, and thresholds precision, recall, thresholds = precision_recall_curve(y_true, y_probs) # Calculate the average pre...
simplelr_Package
[ { "content": "Question:\nYou are tasked to write a function `evaluate_classifier` that calculates and visualizes the precision-recall curve for a binary classifier using `matplotlib` and `sklearn`. The function should take predicted probabilities and true labels, and should also support the calculation of the a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9349, "level": 1, "question": "You are tasked to write a function `evaluate_classifier` that calculates and visualizes the precision-recall curve for a binary classifier using `matplotlib` and `sklearn`. The function should take predicted probabilities and true labels, and should al...
def custom_library_sort(book_titles: list) -> list: n = len(book_titles) if n <= 1: return book_titles swapped = True while swapped: swapped = False # Left to right pass for i in range(n - 1): if book_titles[i] > book_titles[i + 1]: ...
simplelr_Data_Structure
[ { "content": "Question:\n#### Question: Implement a Custom Sort for Library System\n\n**Scenario**: \nYou are developing a library management system where the primary requirement is to sort the books based on titles in alphabetical order. The system should be efficient enough to handle frequent dynamic updates,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9350, "level": 1, "question": "#### Question: Implement a Custom Sort for Library System\n\n**Scenario**: \nYou are developing a library management system where the primary requirement is to sort the books based on titles in alphabetical order. The system should be efficient enough ...
def sieve_of_eratosthenes(n): """ Returns a list of all prime numbers less than n using the Sieve of Eratosthenes algorithm. Args: n (int): The upper limit (exclusive) up to which we find prime numbers. Returns: list: A list of prime numbers less than n. """ # If n...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes an integer input and returns a list of prime numbers less than that integer. Make sure to use the Sieve of Eratosthenes algorithm to efficiently find prime numbers. Also, add comments in the code to explain the steps involved in the algorithm.\nAnswer:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9351, "level": 1, "question": "Write a Python function that takes an integer input and returns a list of prime numbers less than that integer. Make sure to use the Sieve of Eratosthenes algorithm to efficiently find prime numbers. Also, add comments in the code to explain the steps ...
def generate_triangle(n): if n < 1: return "" triangle = [] row = [1] triangle.append(row) for i in range(1, n): new_row = [1] for j in range(1, len(row)): new_element = row[j-1] + row[j] new_row.append(new_element) new_row.append(1) tr...
simplelr_Taco
[ { "content": "Question:\n### Task:\n\nYou have to write a function `generate_triangle` which returns Pascal's Triangle as a string in formatted manner. In a Pascal's Triangle, each number is the sum of the two numbers directly above it.\n\n#### Parameters:\n \n generate_triangle( n );\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9352, "level": 1, "question": "### Task:\n\nYou have to write a function `generate_triangle` which returns Pascal's Triangle as a string in formatted manner. In a Pascal's Triangle, each number is the sum of the two numbers directly above it.\n\n#### Parameters:\n \n generate_...
def longest_increasing_subsequence(nums): if not nums: return [] n = len(nums) dp = [1] * n prev = [-1] * n for i in range(1, n): for j in range(i): if nums[j] < nums[i]: if dp[j] + 1 > dp[i]: dp[i] = dp[j] + 1 ...
simplelr_Evol
[ { "content": "Question:\nCreate a program that finds the longest increasing subsequence in a list of integers.\n[5, 2, 8, 6, 3, 6, 9, 7]\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9353, "level": 1, "question": "Create a program that finds the longest increasing subsequence in a list of integers.\n[5, 2, 8, 6, 3, 6, 9, 7]", "split": "train" }
def is_palindrome(n): if n < 0: return False s = str(n) return s == s[::-1]
simplelr_Filter
[ { "content": "Question:\nYou have been asked to implement a function that checks if a given number is a palindrome, i.e., it remains the same when its digits are reversed. For example, 12321 is a palindrome but 123456 is not. The function should take one argument, which is the number to check. It should return ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9354, "level": 1, "question": "You have been asked to implement a function that checks if a given number is a palindrome, i.e., it remains the same when its digits are reversed. For example, 12321 is a palindrome but 123456 is not. The function should take one argument, which is the...
def is_divisible_by_2_and_3(num): return num % 6 == 0
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check if the given number is divisible by both 2 and 3.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9355, "level": 1, "question": "Write a python function to check if the given number is divisible by both 2 and 3.", "split": "train" }
def cumulative_sum(lst): cum_sum = 0 result = [] for num in lst: new_num = num + cum_sum result.append(new_num) cum_sum += num return result
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes a list of integers and returns a new list with each integer increased by the sum of all elements preceding it in the original list (cumulative sum). For example, if the input list is [1, 2, 3], the output should be [1, 3, 6]. If the list is empty, the output ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9356, "level": 1, "question": "Write a function that takes a list of integers and returns a new list with each integer increased by the sum of all elements preceding it in the original list (cumulative sum). For example, if the input list is [1, 2, 3], the output should be [1, 3, 6]...
def shortest_string(lst): if not lst: return None min_length = len(lst[0]) min_string = lst[0] for s in lst[1:]: if len(s) < min_length: min_length = len(s) min_string = s return min_string
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of strings and returns the shortest string in the list. If there are multiple strings with the same shortest length, return the first one encountered.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9357, "level": 1, "question": "Create a function that takes a list of strings and returns the shortest string in the list. If there are multiple strings with the same shortest length, return the first one encountered.", "split": "train" }
def even_occurrences(numbers): # Build a dictionary to count occurrences counts = {} for num in numbers: if num in counts: counts[num] += 1 else: counts[num] = 1 # Collect elements with even counts in the order of their first occurrence added = set() ...
simplelr_Filter
[ { "content": "Question:\nObjective: Implement a Python function which takes a list of integers as input and returns a new list containing only the elements that appear an even number of times in the input list.\n\n\n Example:\n\n```python\nnumbers = [1, 2, 2, 3, 4, 4, 5, 5, 5]\nresult = even_occurrences(numbers...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9358, "level": 1, "question": "Objective: Implement a Python function which takes a list of integers as input and returns a new list containing only the elements that appear an even number of times in the input list.\n\n\n Example:\n\n```python\nnumbers = [1, 2, 2, 3, 4, 4, 5, 5, 5]...
def merge_sorted_arrays(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:]) result.extend(right[j...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to solve the problem of merging two sorted arrays into one sorted array using the merge algorithm from merge sort.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9359, "level": 1, "question": "Write a python function to solve the problem of merging two sorted arrays into one sorted array using the merge algorithm from merge sort.", "split": "train" }
from collections import Counter def count_letters(s): return Counter(c for c in s if c != ' ')
simplelr_Code_Contests
[ { "content": "Question:\nYou are given a string containing lowercase letters and spaces. Your task is to implement a function that counts the occurrences of each letter in the string and returns a dictionary where keys are letters, and values are the counts. Spaces should be ignored.\n\nInput\n\nA single line w...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9360, "level": 1, "question": "You are given a string containing lowercase letters and spaces. Your task is to implement a function that counts the occurrences of each letter in the string and returns a dictionary where keys are letters, and values are the counts. Spaces should be i...
def reverse_array(arr): left = 0 right = len(arr) - 1 while left < right: # Swap elements at left and right pointers arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 return arr # Example usage: array = [1, 2, 3, 4, 5] print(reverse_array(array)) # Outp...
simplelr_Filter
[ { "content": "Question:\nWhat is an algorithm to reverse the order of elements in a given array?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9361, "level": 1, "question": "What is an algorithm to reverse the order of elements in a given array?", "split": "train" }
def max_subarray_sum(arr): if not arr: return 0 current_max = global_max = arr[0] for num in arr[1:]: current_max = max(num, current_max + num) if current_max > global_max: global_max = current_max return global_max
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the maximum sum of a subarray. Given an array of integers, this function should return the maximum sum of a subarray within the given array, where a subarray is a contiguous segment of the array. For instance, given the list `[1, -3, 2, 1, -1]`, the funct...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9362, "level": 1, "question": "Write a python function to find the maximum sum of a subarray. Given an array of integers, this function should return the maximum sum of a subarray within the given array, where a subarray is a contiguous segment of the array. For instance, given the ...
def can_partition_pairs(arr, k): mod = [x % k for x in arr] from collections import defaultdict freq = defaultdict(int) for m in mod: freq[m] += 1 # Check if count of remainder 0 is even if freq.get(0, 0) % 2 != 0: return False # Check other remainders for r in range(1, k...
simplelr_Apps
[ { "content": "Question:\nGiven an array of integers, determine if it is possible to partition the array into pairs such that the sum of each pair is divisible by a given integer k. Return true if such a partitioning is possible, otherwise return false.\n\nExample 1:\nInput: arr = [9, 7, 5, 3], k = 6\nOutput: tr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9363, "level": 1, "question": "Given an array of integers, determine if it is possible to partition the array into pairs such that the sum of each pair is divisible by a given integer k. Return true if such a partitioning is possible, otherwise return false.\n\nExample 1:\nInput: ar...
def average(numbers): if not numbers: return None return sum(numbers) / len(numbers)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to calculate the average of numbers in a list. How can I handle cases where the list might be empty, and what should I return in such cases?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9364, "level": 1, "question": "Write a python function to calculate the average of numbers in a list. How can I handle cases where the list might be empty, and what should I return in such cases?", "split": "train" }
def sort_array(arr): if len(arr) <= 1: return arr pivot_index = len(arr) // 2 pivot = arr[pivot_index] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] left_sorted = sort_array(left) right_sorted = sort_array(right...
simplelr_Filter
[ { "content": "Question:\nI cannot use \"ibm\" as part of any of the words in my solution, as it is a registered trademark. I have an array of integers and I need to sort them in ascending order. Here is what I have so far, but I cannot figure out how to implement the recursive calls. \n\n```python\ndef sort_arr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9365, "level": 1, "question": "I cannot use \"ibm\" as part of any of the words in my solution, as it is a registered trademark. I have an array of integers and I need to sort them in ascending order. Here is what I have so far, but I cannot figure out how to implement the recursive...
def int_to_roman(n: any) -> str: """ Convert and return the Roman numeral representation of an integer within the range [1, 3999]. :param n: Any type of input to validate :return: Roman numeral representation of the integer :raises ValueError: If input is not an integer within the specified...
simplelr_Algorithm
[ { "content": "Question:\n### Question: Implement a Decimal to Roman Numeral Converter\n\n**Scenario**:\nYou are developing a feature for a historic dates display system that requires converting decimal integers to Roman numerals. To fulfill this requirement, you need to write a function capable of accurately tr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9366, "level": 1, "question": "### Question: Implement a Decimal to Roman Numeral Converter\n\n**Scenario**:\nYou are developing a feature for a historic dates display system that requires converting decimal integers to Roman numerals. To fulfill this requirement, you need to write ...
def hiking_summary(altitudes): result = [] for i in range(len(altitudes) - 1): current = altitudes[i] next_alt = altitudes[i + 1] if next_alt > current: result.append("Uphill") elif next_alt < current: result.append("Downhill") else: re...
simplelr_Apps
[ { "content": "Question:\nBob is an avid hiker. He likes to plan his hiking activities and make sure he's well-prepared for the terrain he will be encountering. Bob has a map with altitude information of his hiking trail.\n\nHe needs to know when he will encounter an uphill, a downhill, or flat ground, based on ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9367, "level": 1, "question": "Bob is an avid hiker. He likes to plan his hiking activities and make sure he's well-prepared for the terrain he will be encountering. Bob has a map with altitude information of his hiking trail.\n\nHe needs to know when he will encounter an uphill, a ...
def longest_balanced_substring(s: str) -> int: stack = [-1] # Initialize stack with base index max_length = 0 for i, char in enumerate(s): if char == '(': stack.append(i) else: stack.pop() if not stack: stack.append(i) else: ...
simplelr_Taco
[ { "content": "Question:\nWrite a function `longest_balanced_substring(s: str) -> int` that takes a string `s` consisting of only opening and closing parentheses '(' and ')', and returns the length of the longest balanced substring.\n\nA balanced substring is one where the number of opening and closing parenthes...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9368, "level": 1, "question": "Write a function `longest_balanced_substring(s: str) -> int` that takes a string `s` consisting of only opening and closing parentheses '(' and ')', and returns the length of the longest balanced substring.\n\nA balanced substring is one where the numb...
import numpy as np from typing import Union def gauss_seidel( a: Union[list[list[float]], np.ndarray], b: Union[list[float], np.ndarray], initial_guess: Union[list[float], np.ndarray], tolerance: float, max_iterations: int ) -> np.ndarray: # Convert inputs to numpy arrays a = np.array(a, dt...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement:\nYou are tasked with implementing a function to solve a system of linear equations using the Gauss-Seidel iterative method. The Gauss-Seidel method is an iterative technique for solving a square system of linear equations.\n\n### Requirements:\n1. Implement a meth...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9369, "level": 1, "question": "### Problem Statement:\nYou are tasked with implementing a function to solve a system of linear equations using the Gauss-Seidel iterative method. The Gauss-Seidel method is an iterative technique for solving a square system of linear equations.\n\n###...
def string_lengths(strings): return [len(s) for s in strings]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of strings and returns a list of integers where each integer is the length of the corresponding string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9370, "level": 1, "question": "Create a function that takes a list of strings and returns a list of integers where each integer is the length of the corresponding string.", "split": "train" }
def reverse_end_characters(s, n): if n <= 0: return '' elif n >= len(s): return s[::-1] else: return s[-n:][::-1]
simplelr_Filter
[ { "content": "Question:\nCreate a function that takes a string and a number n, then return the n characters from the end of the string in reverse order. Additionally, ensure the function handles n being larger than the length of the string by returning the entire string in reverse order.\nAnswer:\nLet's think s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9371, "level": 1, "question": "Create a function that takes a string and a number n, then return the n characters from the end of the string in reverse order. Additionally, ensure the function handles n being larger than the length of the string by returning the entire string in rev...
def max_difference(arr): if len(arr) < 2: return 0 # Return 0 if the array has fewer than two elements min_so_far = arr[0] max_diff = float('-inf') for element in arr[1:]: current_diff = element - min_so_far if current_diff > max_diff: max_diff = current_diff ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the maximum difference between two elements in an array such that the larger element comes after the smaller one in the array. Here is the array: arr = [2, 3, 10, 6, 4, 8, 1]\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9372, "level": 1, "question": "Write a python function to find the maximum difference between two elements in an array such that the larger element comes after the smaller one in the array. Here is the array: arr = [2, 3, 10, 6, 4, 8, 1]", "split": "train" }
def caesar_cipher(text: str) -> str: result = "" for char in text: if char.islower(): original = ord(char) - ord('a') shifted = (original + 3) % 26 new_char = chr(shifted + ord('a')) result += new_char elif char.isupper(): original = or...
simplelr_Filter
[ { "content": "Question:\nHere's a simple substitution cipher that replaces each letter with the letter three positions ahead of it in the alphabet. Here's a brief example:\n \na -> d\nb -> e\nc -> f\nd -> g\n\nAnd so on. \n\nThis particular cipher is called the Caesar Cipher, named after Julius Caesar, who alle...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9373, "level": 1, "question": "Here's a simple substitution cipher that replaces each letter with the letter three positions ahead of it in the alphabet. Here's a brief example:\n \na -> d\nb -> e\nc -> f\nd -> g\n\nAnd so on. \n\nThis particular cipher is called the Caesar Cipher, ...
def rotate(arr, k): n = len(arr) if n == 0 or k == 0: return arr.copy() effective_k = k % n return arr[-effective_k:] + arr[:-effective_k]
simplelr_Taco
[ { "content": "Question:\n## Task\n\nYou are given an array of integers and a number `k`. Your task is to rotate the array `k` times to the right.\n\nHere's how the rotation works:\n\n- If `k` is 3 and the array is [1,2,3,4,5], the steps would be:\n - [5, 1, 2, 3, 4] (1st rotation)\n - [4, 5, 1, 2, 3] (2nd rot...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9374, "level": 1, "question": "## Task\n\nYou are given an array of integers and a number `k`. Your task is to rotate the array `k` times to the right.\n\nHere's how the rotation works:\n\n- If `k` is 3 and the array is [1,2,3,4,5], the steps would be:\n - [5, 1, 2, 3, 4] (1st rota...
from collections import Counter def process_data(data: list) -> list: counts = Counter(data) result = [] for index, number in enumerate(data): result.append((number, index, counts[number])) return result
simplelr_Filter
[ { "content": "Question:\nGiven a Python function `process_data` with the following signature: \n`process_data(data: list) -> list` which processes a given list of integers, \nand returns a new list where each element is a tuple containing the original \ninteger, its index in the input list, and the count of its...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9375, "level": 1, "question": "Given a Python function `process_data` with the following signature: \n`process_data(data: list) -> list` which processes a given list of integers, \nand returns a new list where each element is a tuple containing the original \ninteger, its index in t...
def sum_of_digits(n): n = abs(n) total = 0 for digit in str(n): total += int(digit) return total
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to sum the digits of an integer. For example, if the input is 123, the function should return 6 (1+2+3).\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9376, "level": 1, "question": "Write a python function to sum the digits of an integer. For example, if the input is 123, the function should return 6 (1+2+3).", "split": "train" }
def is_rotated(str1, str2): if len(str1) != len(str2): return False if not str1: return True doubled = str2 + str2 return str1 in doubled
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes two string inputs, `str1` and `str2`. The function will check if `str1` is a rotated version of `str2`. A rotated string is a string that can be obtained by taking a substring from the start of the original string and moving it to the end.\nAnswer:\nLet's th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9377, "level": 1, "question": "Create a function that takes two string inputs, `str1` and `str2`. The function will check if `str1` is a rotated version of `str2`. A rotated string is a string that can be obtained by taking a substring from the start of the original string and movin...
def replace_f_with_t(dataset, columns): new_dataset = [] for row in dataset: new_row = row.copy() for col in columns: value = new_row.get(col) if value == 'F': new_row[col] = 'T' new_dataset.append(new_row) return new_dataset
simplelr_Filter
[ { "content": "Question:\nDesign a Python function that, given a dataset and a set of columns, replaces all occurrences of \"F\" with \"T\" in the specified columns. The dataset is represented as a list of dictionaries, where each dictionary corresponds to a row in the dataset, and the keys are column names. The...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9378, "level": 1, "question": "Design a Python function that, given a dataset and a set of columns, replaces all occurrences of \"F\" with \"T\" in the specified columns. The dataset is represented as a list of dictionaries, where each dictionary corresponds to a row in the dataset,...
def findPairWithSum(arr, target): seen = set() for num in arr: complement = target - num if complement in seen: return (complement, num) seen.add(num) return None
simplelr_Apps
[ { "content": "Question:\nImplement a function `findPairWithSum` that accepts an array of integers (the first argument) and a target sum (the second argument). The function should return a tuple of two integers from the array that add up to the target sum. If no such pair exists, return `null`. \n\nA few cases:\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9379, "level": 1, "question": "Implement a function `findPairWithSum` that accepts an array of integers (the first argument) and a target sum (the second argument). The function should return a tuple of two integers from the array that add up to the target sum. If no such pair exist...
from typing import List def compute_prefix_sums(arr: List[int]) -> List[int]: prefix = [] current_sum = 0 for num in arr: current_sum += num prefix.append(current_sum) return prefix
simplelr_Algorithm
[ { "content": "Question:\n### Context:\nYou are developing a software that requires frequent calculations of prefix sums for a given list of integers. A prefix sum is the sum of all elements of the list up to a certain index. To optimize your software, you need a function that precomputes the prefix sums to effi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9380, "level": 1, "question": "### Context:\nYou are developing a software that requires frequent calculations of prefix sums for a given list of integers. A prefix sum is the sum of all elements of the list up to a certain index. To optimize your software, you need a function that ...
def collect_odds(numbers): return [num for num in numbers if num % 2 != 0]
simplelr_Filter
[ { "content": "Question:\nWrite a function to collect all the odd numbers in a list using Python.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9381, "level": 1, "question": "Write a function to collect all the odd numbers in a list using Python.", "split": "train" }
def sliding_operations(nums, k): for _ in range(k): current_min = min(nums) index = nums.index(current_min) nums.pop(index) nums.append(current_min) return nums
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of `n` integers `nums` and an integer `k` representing the number of sliding operations. Your goal is to perform exactly `k` sliding operations on the array, where each sliding operation consists of removing the smallest element from the array and appending it to ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9382, "level": 1, "question": "You are given an array of `n` integers `nums` and an integer `k` representing the number of sliding operations. Your goal is to perform exactly `k` sliding operations on the array, where each sliding operation consists of removing the smallest element ...
def exponentiate(base, exponent): if exponent == 0: return 1 result = 1 for _ in range(exponent): result *= base return result
simplelr_Filter
[ { "content": "Question:\nCan you help me with a Python function to calculate the exponentiation of a number, but using a loop instead of the built-in power operator or a math library function? I want to understand the underlying process better. For example, if I want to calculate 2 to the power of 3, the functi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9383, "level": 1, "question": "Can you help me with a Python function to calculate the exponentiation of a number, but using a loop instead of the built-in power operator or a math library function? I want to understand the underlying process better. For example, if I want to calcul...
def find_unsorted_subarray_length(arr): sorted_arr = sorted(arr) left = 0 while left < len(arr) and arr[left] == sorted_arr[left]: left += 1 if left == len(arr): return 0 right = len(arr) - 1 while right >= 0 and arr[right] == sorted_arr[right]: right -= 1 return righ...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `arr`, find and return the length of the **shortest subarray** that, if sorted, results in the entire array being sorted in non-decreasing order. If the array is already sorted, return `0`.\n\nFor example:\n- If the input is `arr = [2, 6, 4, 8, 10, 9, 15]`, th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9384, "level": 1, "question": "Given an array of integers `arr`, find and return the length of the **shortest subarray** that, if sorted, results in the entire array being sorted in non-decreasing order. If the array is already sorted, return `0`.\n\nFor example:\n- If the input is ...
import re def validate_email(email): """ Validate an email address using a regular expression. Args: email (str): The email address to validate. Returns: bool: True if the email is valid, False otherwise. """ pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$...
simplelr_Filter
[ { "content": "Question:\nWrite a python function to validate email addresses using regular expressions that checks if the email is in the format \"username@domain.com\". What are the key parts to consider when validating an email address?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9385, "level": 1, "question": "Write a python function to validate email addresses using regular expressions that checks if the email is in the format \"username@domain.com\". What are the key parts to consider when validating an email address?", "split": "train" }
def odd_factors(n): if n < 1: return [] factors = set() for i in range(1, int(n ** 0.5) + 1): if n % i == 0: factors.add(i) factors.add(n // i) # Filter out 1 and even numbers, then sort odd_factors = [x for x in factors if x > 1 and x % 2 != 0] odd_factor...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an integer as input and returns a list containing the factors of the integer. Additionally, the function should filter out any even numbers and return the list of only odd factors (excluding 1). If the integer is less than 1, return an empty list.\nAnswer:\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9386, "level": 1, "question": "Create a function that takes an integer as input and returns a list containing the factors of the integer. Additionally, the function should filter out any even numbers and return the list of only odd factors (excluding 1). If the integer is less than ...
def solution(numbers): return sum(x**2 for x in numbers if x % 2 != 0)
simplelr_Filter
[ { "content": "Question:\nThis code does not meet the requirements\n\n```python\ndef solution(numbers):\n return sum(numbers)\n\n```\n\nMy task is to\n\n1. **Filter out even numbers**.\n2. **Square the remaining odd numbers**.\n3. **Sum the squared odd numbers**.\n\nHere is a list of numbers for testing:\n\n`...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9387, "level": 1, "question": "This code does not meet the requirements\n\n```python\ndef solution(numbers):\n return sum(numbers)\n\n```\n\nMy task is to\n\n1. **Filter out even numbers**.\n2. **Square the remaining odd numbers**.\n3. **Sum the squared odd numbers**.\n\nHere is ...
def sum_of_divisibles(n): k = (n - 1) // 15 return 15 * k * (k + 1) // 2
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the sum of all the positive integers less than a given number `n` that are divisible by both 3 and 5.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9388, "level": 1, "question": "Write a python function to find the sum of all the positive integers less than a given number `n` that are divisible by both 3 and 5.", "split": "train" }
def calculate_score(s: str) -> int: total = 0 for c in s: if c.isalpha(): total += ord(c.lower()) - ord('a') + 1 return total
simplelr_Taco
[ { "content": "Question:\n## Problem Statement\nRaelyn is working on a text-based puzzle game that involves calculating scores based on the value of characters. Each character in the English alphabet is assigned a specific value: 'a' is worth 1 point, 'b' is worth 2 points, ..., 'z' is worth 26 points. Uppercase...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9389, "level": 1, "question": "## Problem Statement\nRaelyn is working on a text-based puzzle game that involves calculating scores based on the value of characters. Each character in the English alphabet is assigned a specific value: 'a' is worth 1 point, 'b' is worth 2 points, ......
from itertools import permutations def unique_string_permutations(s: str, max_length: int) -> list: max_k = min(max_length, len(s)) unique_perms = set() for k in range(1, max_k + 1): for p in permutations(s, k): perm_str = ''.join(p) unique_perms.add(perm_str) ...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Question: String Permutations with Constraints\n\n#### Scenario\nYou are working on a text processing tool that needs to generate all distinct permutations of a given string under certain constraints. The string can include alphabetical characters, digits, and special charact...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9390, "level": 1, "question": "### Coding Question: String Permutations with Constraints\n\n#### Scenario\nYou are working on a text processing tool that needs to generate all distinct permutations of a given string under certain constraints. The string can include alphabetical char...
def contains_duplicate(nums): return len(nums) != len(set(nums))
simplelr_Evol
[ { "content": "Question:\nGiven an array of integers, write a function to determine if it contains any duplicate elements. If any value appears at least twice in the array, return `true`. If every element is distinct, return `false`.\n\nExample:\n- Input: [1, 2, 3, 1]\n- Output: true\n\n- Input: [1, 2, 3, 4]\n- ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9391, "level": 1, "question": "Given an array of integers, write a function to determine if it contains any duplicate elements. If any value appears at least twice in the array, return `true`. If every element is distinct, return `false`.\n\nExample:\n- Input: [1, 2, 3, 1]\n- Output...
def find_smallest_missing_positive(nums): if not nums: return 1 n = len(nums) present = [False] * (n + 1) for num in nums: if 1 <= num <= n: present[num] = True for i in range(1, n + 1): if not present[i]: return i return n + 1
simplelr_Filter
[ { "content": "Question:\ndef find_smallest_missing_positive(nums):\n if not nums:\n return 1\n\n n = len(nums)\n present = [False] * (n + 1)\n \n for num in nums:\n if 1 <= num <= n:\n present[num] = True\n \n for i in range(1, n + 1):\n if not present[i]:\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9392, "level": 1, "question": "def find_smallest_missing_positive(nums):\n if not nums:\n return 1\n\n n = len(nums)\n present = [False] * (n + 1)\n \n for num in nums:\n if 1 <= num <= n:\n present[num] = True\n \n for i in range(1, n +...
def plus_one(digits): carry = 1 i = len(digits) - 1 while i >= 0 and carry: total = digits[i] + carry if total == 10: digits[i] = 0 carry = 1 else: digits[i] = total carry = 0 i -= 1 if carry: digits.insert(0, 1) ...
simplelr_Data_Structure
[ { "content": "Question:\n### Problem Description\n\nYou are given a non-negative integer represented as a list of digits, where each element in the list corresponds to a single digit. The digits are stored in a big-endian format, with the most significant digit at the head of the list. Implement a function `plu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9393, "level": 1, "question": "### Problem Description\n\nYou are given a non-negative integer represented as a list of digits, where each element in the list corresponds to a single digit. The digits are stored in a big-endian format, with the most significant digit at the head of ...
def calculateSpan(prices, n): stack = [] spans = [] for i in range(n): while stack and prices[stack[-1]] <= prices[i]: stack.pop() if not stack: spans.append(i + 1) else: spans.append(i - stack[-1]) stack.append(i) return spans
simplelr_Taco
[ { "content": "Question:\nThe stock span problem is a financial problem where we need to calculate the span of stock's price for all n days. The span is defined as the maximum number of consecutive days (including the current day) the price of a stock has been less than or equal to the price on that day.\n\nMore...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9394, "level": 1, "question": "The stock span problem is a financial problem where we need to calculate the span of stock's price for all n days. The span is defined as the maximum number of consecutive days (including the current day) the price of a stock has been less than or equa...
def can_form_sentence(s, words): if not words: return s == '' sum_lengths = sum(words) required_length = sum_lengths + (len(words) - 1) if len(s) != required_length: return False split_parts = s.split(' ') valid_split = [part for part in split_parts if part] ...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` which represents a **sentence** consisting of lowercase letters and spaces, and an integer array `words` where each element is the length of a word that should appear in the sentence. Each word in the `words` array must be separated by exactly one space. Return `true`...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9395, "level": 1, "question": "Given a string `s` which represents a **sentence** consisting of lowercase letters and spaces, and an integer array `words` where each element is the length of a word that should appear in the sentence. Each word in the `words` array must be separated ...
from collections import Counter def topKFrequent(nums, k): count = Counter(nums) # Sort the items by frequency descending, then by number ascending sorted_counts = sorted(count.items(), key=lambda x: (-x[1], x[0])) # Extract the top k elements' keys return [x[0] for x in sorted_counts[:k]] # Examp...
simplelr_Filter
[ { "content": "Question:\nimport heapq\nfrom collections import Counter\n\ndef topKFrequent(nums, k):\n count = Counter(nums)\n return [item[0] for item in heapq.nlargest(k, count.items(), key=lambda x: x[1])]\n\n# test the function\nnums = [1,1,1,2,2,3]\nk = 2\nprint(topKFrequent(nums, k))\n# Output: [1,2...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9396, "level": 1, "question": "import heapq\nfrom collections import Counter\n\ndef topKFrequent(nums, k):\n count = Counter(nums)\n return [item[0] for item in heapq.nlargest(k, count.items(), key=lambda x: x[1])]\n\n# test the function\nnums = [1,1,1,2,2,3]\nk = 2\nprint(top...
def find_minimized_difference(buildings): total = sum(buildings) target = total // 2 dp = [False] * (target + 1) dp[0] = True for num in buildings: if num > target: continue for s in range(target, num - 1, -1): if dp[s - num]: dp[s] = True...
simplelr_Apps
[ { "content": "Question:\nIn a city, there are various blocks and each block has a different number of buildings. You are given a list where each entry represents the number of buildings in a block. Your task is to split these blocks into two groups such that the difference in the total number of buildings in th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9397, "level": 1, "question": "In a city, there are various blocks and each block has a different number of buildings. You are given a list where each entry represents the number of buildings in a block. Your task is to split these blocks into two groups such that the difference in ...
def evaluate_postfix(expression: str) -> float: if not expression: return 0.0 tokens = expression.split() stack = [] for token in tokens: if token in '+-*/': b = stack.pop() a = stack.pop() if token == '+': res = a + b elif ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are asked to implement a function that evaluates a postfix (Reverse Polish Notation) expression. A postfix expression is a mathematical notation in which every operator follows all of its operands. This format does not need any parentheses as long as operators...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9398, "level": 1, "question": "### Problem Statement\nYou are asked to implement a function that evaluates a postfix (Reverse Polish Notation) expression. A postfix expression is a mathematical notation in which every operator follows all of its operands. This format does not need a...
from typing import List, Dict def organize_files(files: List[str]) -> Dict[str, List[str]]: result = {} for file in files: last_dot = file.rfind('.') if last_dot == -1 or last_dot == len(file) - 1: key = 'no_extension' else: ext = file[last_dot + 1:] ...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nYou are working on a file management system that needs a function to organize files into folders based on their extensions. This utility is crucial for maintaining an organized file structure in a large-scale project with numerous files o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9399, "level": 1, "question": "### Coding Assessment Question\n\n#### Scenario\nYou are working on a file management system that needs a function to organize files into folders based on their extensions. This utility is crucial for maintaining an organized file structure in a large-...