target
stringlengths
29
3.65k
data_source
stringclasses
12 values
prompt
listlengths
1
1
ability
stringclasses
1 value
reward_model
dict
extra_info
dict
from collections import Counter def is_balanced(s): freq = Counter(s) n = len(s) m = len(freq) if n % m != 0: return False target = n // m for count in freq.values(): if count != target: return False return True
simplelr_Apps
[ { "content": "Question:\n# Task\nA string is considered 'balanced' if all characters appear the same number of times. Write a function that determines whether a given string is balanced.\n\n# Example\n\nFor `s = \"aabbcc\"`, the result should be `True`.\n\nFor `s = \"aabbccc\"`, the result should be `False`.\n\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3500, "level": 1, "question": "# Task\nA string is considered 'balanced' if all characters appear the same number of times. Write a function that determines whether a given string is balanced.\n\n# Example\n\nFor `s = \"aabbcc\"`, the result should be `True`.\n\nFor `s = \"aabbccc\"...
def is_rotated(s1: str, s2: str) -> bool: if len(s1) != len(s2): return False return s2 in (s1 + s1)
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario\nImagine you are a software engineer tasked with developing a feature for a text-processing application. One of the requirements is to determine whether a given string is a rotated version of another string. This feature will be used to detect rotated phrases in a document ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3501, "level": 1, "question": "### Scenario\nImagine you are a software engineer tasked with developing a feature for a text-processing application. One of the requirements is to determine whether a given string is a rotated version of another string. This feature will be used to de...
import subprocess def create_source_distribution(include_patterns: list, exclude_patterns: list, formats: str = "gztar"): """ Creates a source distribution for a Python package. Parameters: - include_patterns: List of strings, each string is a pattern of files to include (e.g., ["*.py", "*.txt"]). ...
simplelr_Docs
[ { "content": "Question:\n### Source Distribution Automation\n\nYou are required to automate the process of creating a source distribution for a Python package. Your task involves writing a function to generate a `MANIFEST.in` file and using the `sdist` command to create the source distribution archive in the de...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3502, "level": 1, "question": "### Source Distribution Automation\n\nYou are required to automate the process of creating a source distribution for a Python package. Your task involves writing a function to generate a `MANIFEST.in` file and using the `sdist` command to create the so...
def min_operations(word_a: str, word_b: str) -> int: m = len(word_a) n = len(word_b) # Initialize the DP table with (m+1) rows and (n+1) columns dp = [[0] * (n + 1) for _ in range(m + 1)] # Fill the DP table for i in range(m + 1): for j in range(n + 1): if i == 0: ...
simplelr_Data_Structure
[ { "content": "Question:\n### Edit Distance Calculation\n\nGiven two words `A` and `B`, your task is to write a function `min_operations` to compute the minimum number of operations required to transform word `A` into word `B`. An operation is defined as insertion, deletion, or substitution of a single character...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3503, "level": 1, "question": "### Edit Distance Calculation\n\nGiven two words `A` and `B`, your task is to write a function `min_operations` to compute the minimum number of operations required to transform word `A` into word `B`. An operation is defined as insertion, deletion, or...
def caesar_cipher(s, shift=3): alphabet = 'abcdefghijklmnopqrstuvwxyz' effective_shift = shift % 26 shifted_alphabet = ''.join([alphabet[(i + effective_shift) % 26] for i in range(26)]) table = str.maketrans(alphabet, shifted_alphabet) return s.translate(table)
simplelr_Filter
[ { "content": "Question:\nGiven a string, replace every letter with its corresponding letter three positions ahead of it in the alphabet, wrapping around to the beginning of the alphabet if necessary. This is known as a Caesar Cipher.\n\nFor example, for the string \"xyz\", the output should be \"abc\".\n\nHere ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3504, "level": 1, "question": "Given a string, replace every letter with its corresponding letter three positions ahead of it in the alphabet, wrapping around to the beginning of the alphabet if necessary. This is known as a Caesar Cipher.\n\nFor example, for the string \"xyz\", the...
def total_cost(number_of_items, price_per_item, shipping_cost): total = (number_of_items * price_per_item) + shipping_cost return total
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to calculate the total cost of purchasing a certain number of items. Each item costs a fixed price, and there is an additional shipping cost that applies regardless of the quantity of items purchased. The function should take the number of items, the price per it...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3505, "level": 1, "question": "Write a python function to calculate the total cost of purchasing a certain number of items. Each item costs a fixed price, and there is an additional shipping cost that applies regardless of the quantity of items purchased. The function should take th...
def print_dict_contents(dictionary, sort_keys=False): """ Prints the contents of a dictionary with string keys and integer values. Args: dictionary: The dictionary to be printed. sort_keys (bool): Optional parameter to specify if the output should be sorted by keys. Defaults to False. ...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to print the contents of a dictionary where the keys are strings and the values are integers. The function should also accept a parameter to specify if the output should be sorted by the keys. If the `sort_keys` parameter is `True`, the function should print the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3506, "level": 1, "question": "Write a Python function to print the contents of a dictionary where the keys are strings and the values are integers. The function should also accept a parameter to specify if the output should be sorted by the keys. If the `sort_keys` parameter is `Tr...
def has_zero_sum_subarray(arr): prefix_sums = {0} current_sum = 0 for num in arr: current_sum += num if current_sum in prefix_sums: return True prefix_sums.add(current_sum) return False
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of `n` integers, determine whether there exists a subarray (contiguous segment) whose elements sum up to zero. Return `true` if such a subarray exists, otherwise return `false`.\n\nFor example, given the array `[4, 2, -3, 1, 6]`, there exists a subarray `[2, -3, 1]` that ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3507, "level": 1, "question": "Given an array of `n` integers, determine whether there exists a subarray (contiguous segment) whose elements sum up to zero. Return `true` if such a subarray exists, otherwise return `false`.\n\nFor example, given the array `[4, 2, -3, 1, 6]`, there e...
def binary_search(lst, target): left = 0 right = len(lst) - 1 while left <= right: mid = (left + right) // 2 if lst[mid] == target: return mid elif target < lst[mid]: right = mid - 1 else: left = mid + 1 return -1
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that implements a binary search algorithm. The function should take a sorted list of integers and a target integer as input and return the index of the target if it exists in the list, or -1 if the target is not found.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3508, "level": 1, "question": "Create a Python function that implements a binary search algorithm. The function should take a sorted list of integers and a target integer as input and return the index of the target if it exists in the list, or -1 if the target is not found.", "spl...
def max_profit(prices): if len(prices) < 2: return 0 min_price = prices[0] max_profit = 0 for price in prices[1:]: current_profit = price - min_price if current_profit > max_profit: max_profit = current_profit if price < min_price: min_price = pric...
simplelr_Apps
[ { "content": "Question:\n# Task\nYou are given a series of stock prices for consecutive days. You need to write a function that determines the maximum profit that could have been made by buying and then later selling one share of the stock.\n\nYour function should return the maximum difference between two price...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3509, "level": 1, "question": "# Task\nYou are given a series of stock prices for consecutive days. You need to write a function that determines the maximum profit that could have been made by buying and then later selling one share of the stock.\n\nYour function should return the m...
def convert_number(n): return { "binary": format(n, 'b'), "octal": format(n, 'o'), "hexadecimal": format(n, 'x') }
simplelr_Filter
[ { "content": "Question:\nImplement a function that converts a decimal number to binary, octal, and hexadecimal representations. The function should take a single integer input and return a dictionary with keys \"binary\", \"octal\", and \"hexadecimal\", each containing the corresponding string representation of...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3510, "level": 1, "question": "Implement a function that converts a decimal number to binary, octal, and hexadecimal representations. The function should take a single integer input and return a dictionary with keys \"binary\", \"octal\", and \"hexadecimal\", each containing the cor...
def first_n_elements(lst, n): return lst[:n]
simplelr_Filter
[ { "content": "Question:\nHow can I create a function that returns the first n elements of a list in Python? If the list has fewer than n elements, it should return the entire list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3511, "level": 1, "question": "How can I create a function that returns the first n elements of a list in Python? If the list has fewer than n elements, it should return the entire list.", "split": "train" }
from typing import List def find_two_sum_indices(numbers: List[int], target: int) -> List[int]: left = 0 right = len(numbers) - 1 while left < right: current_sum = numbers[left] + numbers[right] if current_sum == target: return [left + 1, right + 1] elif current_sum < ta...
simplelr_Data_Structure
[ { "content": "Question:\n#### Two Sum Target Problem\n\n#### Scenario\nYou are tasked with creating a utility for an e-commerce platform that validates certain transaction constraints. Specifically, given a list of transaction amounts that is sorted in ascending order, find two amounts that sum to a specific ta...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3512, "level": 1, "question": "#### Two Sum Target Problem\n\n#### Scenario\nYou are tasked with creating a utility for an e-commerce platform that validates certain transaction constraints. Specifically, given a list of transaction amounts that is sorted in ascending order, find tw...
def triangle_area(x1, y1, x2, y2, x3, y3): ab_x = x2 - x1 ab_y = y2 - y1 ac_x = x3 - x1 ac_y = y3 - y1 determinant = ab_x * ac_y - ab_y * ac_x return 0.5 * abs(determinant) # Example test cases print(triangle_area(0, 0, 0, 2, 3, 0)) # Output: 3.0 print(triangle_area(1, 1, 4, 5, 7, 2)) # Outpu...
simplelr_Filter
[ { "content": "Question:\nWrite a Python code to calculate the area of a triangle given the coordinates of its three vertices: A(x1, y1), B(x2, y2), and C(x3, y3). Test the function using the provided data points.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3513, "level": 1, "question": "Write a Python code to calculate the area of a triangle given the coordinates of its three vertices: A(x1, y1), B(x2, y2), and C(x3, y3). Test the function using the provided data points.", "split": "train" }
def can_transform_with_substring_operations(s1, s2): return sorted(s1) == sorted(s2)
simplelr_Leetcode
[ { "content": "Question:\nYou are given two strings `s1` and `s2` of equal length consisting of lowercase English letters. Determine whether it is possible to transform `s1` into `s2` using the following operation any number of times:\n\n- Choose a **non-empty** substring of `s1` and reverse its order.\n\nReturn...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3514, "level": 1, "question": "You are given two strings `s1` and `s2` of equal length consisting of lowercase English letters. Determine whether it is possible to transform `s1` into `s2` using the following operation any number of times:\n\n- Choose a **non-empty** substring of `s...
def two_sum(nums, target): seen = {} for index, num in enumerate(nums): complement = target - num if complement in seen: return (seen[complement], index) seen[num] = index return None
simplelr_Apps
[ { "content": "Question:\n## Description:\nWrite a function that takes an array of integers and an integer `target`. Your task is to find two distinct integers in the array that add up to the target. Return their indices as a tuple `(index1, index2)` where `index1` is less than `index2`.\n\n**Constraints:**\n- E...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3515, "level": 1, "question": "## Description:\nWrite a function that takes an array of integers and an integer `target`. Your task is to find two distinct integers in the array that add up to the target. Return their indices as a tuple `(index1, index2)` where `index1` is less than...
def longest_valid_parentheses(s): stack = [-1] # Initialize stack with -1 to handle base case max_len = 0 for i, char in enumerate(s): if char == '(': stack.append(i) else: stack.pop() # Pop the top element if not stack: stack.append(i) ...
simplelr_Leetcode
[ { "content": "Question:\nWrite a function that takes in a string `s` consisting of only `'('` and `')'` characters. You need to determine the longest substring of `s` that is valid in terms of balanced parentheses. A valid substring is defined as one that has an equal number of `'('` and `')'` characters and in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3516, "level": 1, "question": "Write a function that takes in a string `s` consisting of only `'('` and `')'` characters. You need to determine the longest substring of `s` that is valid in terms of balanced parentheses. A valid substring is defined as one that has an equal number o...
def longest_common_subsequence(s1, s2): m = len(s1) n = len(s2) # Create a matrix with (m+1) rows and (n+1) columns dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if s1[i - 1] == s2[j - 1]: dp[i][j] = dp[i - 1][...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the length of the longest common subsequence between two input strings. Your input will be two strings. The output will be an integer representing the length of the longest common subsequence.\nAnswer:\nLet's think step by step.\n", "role": "user" }...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3517, "level": 1, "question": "Write a python function to find the length of the longest common subsequence between two input strings. Your input will be two strings. The output will be an integer representing the length of the longest common subsequence.", "split": "train" }
def find_longest_word(s): words = s.split() if not words: return "" return max(words, key=len)
simplelr_Filter
[ { "content": "Question:\nCreate a Python function named `find_longest_word` which takes a string as an argument and returns the longest word in the string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3518, "level": 1, "question": "Create a Python function named `find_longest_word` which takes a string as an argument and returns the longest word in the string.", "split": "train" }
def count_partitions(n): dp = [0] * (n + 1) dp[0] = 1 # Base case: one way to make 0 for k in range(1, n + 1): for j in range(k, n + 1): dp[j] += dp[j - k] return dp[n]
simplelr_Data_Structure
[ { "content": "Question:\n### Integer Partition Problem\n\n#### Problem Statement\nYou are given a positive integer `n`, and your task is to write a function that computes the number of distinct partitions of `n` into positive integers. A partition of `n` is a way of writing `n` as a sum of positive integers, di...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3519, "level": 1, "question": "### Integer Partition Problem\n\n#### Problem Statement\nYou are given a positive integer `n`, and your task is to write a function that computes the number of distinct partitions of `n` into positive integers. A partition of `n` is a way of writing `n...
def parse_http_response_header(header_str): content_type = None date = None lines = header_str.split('\r\n') for line in lines: line = line.strip() if not line: continue parts = line.split(':', 1) if len(parts) < 2: continue key = parts[0]....
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to parse an HTTP response header and return the values of `Content-Type` and `Date`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3520, "level": 1, "question": "Write a python function to parse an HTTP response header and return the values of `Content-Type` and `Date`.", "split": "train" }
from collections import defaultdict def find_anagrams(s, words): len_to_freqs = defaultdict(set) for word in words: L = len(word) freq = [0] * 26 for c in word: freq[ord(c) - ord('a')] += 1 len_to_freqs[L].add(tuple(freq)) result = set() for L in len_to_...
simplelr_Filter
[ { "content": "Question:\nYou are given a string s and a list of words words. You need to return all the starting indices of s that are beginnings of anagrams of the words in the words list.\n\nInput:\n\n s: \"cbaebabacd\"\n words: [\"abc\",\"bcd\",\"cba\"]\n\nOutput:\n [0,6]\n\nExplanation:\n\nStarting at index...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3521, "level": 1, "question": "You are given a string s and a list of words words. You need to return all the starting indices of s that are beginnings of anagrams of the words in the words list.\n\nInput:\n\n s: \"cbaebabacd\"\n words: [\"abc\",\"bcd\",\"cba\"]\n\nOutput:\n [0,6]\n...
def is_isomorphic(s: str, t: str) -> bool: if len(s) != len(t): return False s_map = {} t_map = {} for s_char, t_char in zip(s, t): if s_char in s_map: if s_map[s_char] != t_char: return False else: s_map[s_char] = t_char ...
simplelr_Data_Structure
[ { "content": "Question:\n### Isomorphic Strings Check\n\n#### Scenario:\nYou are developing a tool that checks if two given words are structurally identical in terms of character mapping. Specifically, you must ensure that if you can transform the first word into the second word, then each character of the firs...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3522, "level": 1, "question": "### Isomorphic Strings Check\n\n#### Scenario:\nYou are developing a tool that checks if two given words are structurally identical in terms of character mapping. Specifically, you must ensure that if you can transform the first word into the second wo...
import itertools def generate_combinations(s, n): unique_chars = sorted(list(set(s))) if len(unique_chars) < n: return [] perms = itertools.permutations(unique_chars, n) perm_strings = [''.join(p) for p in perms] return perm_strings
simplelr_Filter
[ { "content": "Question:\nCreate an array of strings, such that it contains strings of all possible combinations of n characters from a given string of characters, considering the order of characters matters and no character is repeated in a single string. Then, sort the created strings in lexicographical order....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3523, "level": 1, "question": "Create an array of strings, such that it contains strings of all possible combinations of n characters from a given string of characters, considering the order of characters matters and no character is repeated in a single string. Then, sort the create...
def wordBreak(s, wordDict): word_set = set(wordDict) max_len = max(len(word) for word in word_set) if word_set else 0 dp = [False] * (len(s) + 1) dp[0] = True # Empty string can be segmented for i in range(1, len(s) + 1): # Check all possible starting points j for the current ending i ...
simplelr_Filter
[ { "content": "Question:\nThis is a coding challenge from LeetCode:\n\n**Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.**\n\n**Note:**\nThe same word in the dictionary may be reused multiple times in the segmentati...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3524, "level": 1, "question": "This is a coding challenge from LeetCode:\n\n**Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.**\n\n**Note:**\nThe same word in the dictionary may be reus...
def average(a, b): a_valid = isinstance(a, (int, float)) and not isinstance(a, bool) b_valid = isinstance(b, (int, float)) and not isinstance(b, bool) if a_valid and b_valid: return (a + b) / 2 else: return None
simplelr_Filter
[ { "content": "Question:\nI need to create a Python function that calculates the average of two numbers. However, I want to ensure that the function can handle cases where one or both of the inputs are not numbers (integers or floats). If any of the inputs are not numbers, the function should return `None`. How ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3525, "level": 1, "question": "I need to create a Python function that calculates the average of two numbers. However, I want to ensure that the function can handle cases where one or both of the inputs are not numbers (integers or floats). If any of the inputs are not numbers, the ...
import math def findPythagoreanTriplet(N, arr): elements = set(arr) for i in range(N): for j in range(i + 1, N): a = arr[i] b = arr[j] s = a ** 2 + b ** 2 c = math.isqrt(s) if c * c == s and c in elements: return True retur...
simplelr_Taco
[ { "content": "Question:\nGiven an array of N distinct integers, write a function to find if there exists a triplet (a, b, c) that satisfies a^2 + b^2 = c^2.\n\nExample 1:\nInput:\nN = 5\narr = [3, 1, 4, 6, 5]\nOutput: True\nExplanation:\nThere is a triplet (3, 4, 5) which satisfies 3^2 + 4^2 = 5^2.\n\nExample 2...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3526, "level": 1, "question": "Given an array of N distinct integers, write a function to find if there exists a triplet (a, b, c) that satisfies a^2 + b^2 = c^2.\n\nExample 1:\nInput:\nN = 5\narr = [3, 1, 4, 6, 5]\nOutput: True\nExplanation:\nThere is a triplet (3, 4, 5) which sati...
def minDistance(S, T): m = len(S) n = len(T) # Create a DP table with (m+1) rows and (n+1) columns dp = [[0] * (n + 1) for _ in range(m + 1)] # Initialize the base cases for i in range(m + 1): dp[i][0] = i # Need to delete i characters for j in range(n + 1): dp[0][j] = ...
simplelr_Taco
[ { "content": "Question:\nGiven two strings S and T, your task is to find the minimum number of operations required to convert string S into string T. You can perform the following operations on string S:\n1. Insert a character\n2. Delete a character\n3. Replace a character with another character\n\nExample 1:\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3527, "level": 1, "question": "Given two strings S and T, your task is to find the minimum number of operations required to convert string S into string T. You can perform the following operations on string S:\n1. Insert a character\n2. Delete a character\n3. Replace a character wit...
def reverse_words_in_sentence(s): return ' '.join(word[::-1] for word in s.split())
simplelr_Filter
[ { "content": "Question:\nCan you help me with a coding challenge I'm stuck on? I need to reverse the words in a sentence in Python but keep the order of the words the same. For example, if I input \"Hello world\", I want to get \"olleH dlrow\". How can I achieve this?\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3528, "level": 1, "question": "Can you help me with a coding challenge I'm stuck on? I need to reverse the words in a sentence in Python but keep the order of the words the same. For example, if I input \"Hello world\", I want to get \"olleH dlrow\". How can I achieve this?", "spl...
def is_odd_or_even(lst): return [num % 2 != 0 for num in lst]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers and returns a list of boolean values, where each boolean value indicates whether the corresponding integer in the input list is odd or even. For example, if the input list is [1, 2, 3, 4, 5], the output list should be [true, false, true, f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3529, "level": 1, "question": "Create a function that takes a list of integers and returns a list of boolean values, where each boolean value indicates whether the corresponding integer in the input list is odd or even. For example, if the input list is [1, 2, 3, 4, 5], the output l...
def find_unique_element(arr: list[int]) -> int: xor_result = 0 for num in arr: xor_result ^= num return xor_result
simplelr_Algorithm
[ { "content": "Question:\n### Find the Unique Element in an Array of Pairs\n\nYou are given an array of integers where every element appears exactly twice except for one element which appears only once. Implement a function that finds and returns the element that appears only once.\n\n### Function Signature\n```...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3530, "level": 1, "question": "### Find the Unique Element in an Array of Pairs\n\nYou are given an array of integers where every element appears exactly twice except for one element which appears only once. Implement a function that finds and returns the element that appears only o...
import itertools import operator def flatten_and_sort(lst): # Flatten the list using itertools flat_list = itertools.chain.from_iterable(lst) # Convert to a list for sorting flat_list = list(flat_list) # Sort based on the second element of each inner list sorted_list = sorted(flat_list, key=ope...
simplelr_Filter
[ { "content": "Question:\nI have a list of lists where the inner lists are variable in length. The elements in the inner lists are also lists of two integers. I want to flatten this list and sort it based on the second element of the innermost lists. \n\nFor example: \n[[[1, 2], [3, 4]], [[5, 6], [7, 8], [9, 10]...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3531, "level": 1, "question": "I have a list of lists where the inner lists are variable in length. The elements in the inner lists are also lists of two integers. I want to flatten this list and sort it based on the second element of the innermost lists. \n\nFor example: \n[[[1, 2]...
def categorize_by_type(lst): result = {'int': [], 'float': [], 'str': []} for item in lst: item_type = type(item).__name__ if item_type == 'int': result['int'].append(item) elif item_type == 'float': result['float'].append(item) elif item_type == 'str': ...
simplelr_Evol
[ { "content": "Question:\nCreate a function that, given a list of mixed datatypes (integers, floats, and strings) as input, returns a dictionary categorizing each item in the list by its datatype. The keys of the dictionary should be the datatypes ('int', 'float', 'str'), and the values should be lists containin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3532, "level": 1, "question": "Create a function that, given a list of mixed datatypes (integers, floats, and strings) as input, returns a dictionary categorizing each item in the list by its datatype. The keys of the dictionary should be the datatypes ('int', 'float', 'str'), and t...
from typing import List def max_robbery(values: List[int]) -> int: if not values: return 0 n = len(values) if n == 1: return values[0] if n == 2: return max(values[0], values[1]) prev_prev = values[0] prev = max(values[0], values[1]) for i in range(2, n): ...
simplelr_Algorithm
[ { "content": "Question:\n### Warehouse Robbery Maximum Profit Calculation\n\nYou're helping a warehouse owner optimize their security measures against potential robberies. The warehouse is arranged in a linear fashion with a row of boxes, each containing a certain amount of valuable items. A robber must skip at...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3533, "level": 1, "question": "### Warehouse Robbery Maximum Profit Calculation\n\nYou're helping a warehouse owner optimize their security measures against potential robberies. The warehouse is arranged in a linear fashion with a row of boxes, each containing a certain amount of va...
def factorial(n): if not isinstance(n, int): return "Factorial is defined only for non-negative integers." if n < 0: return "Factorial of negative number is not defined" elif n == 0 or n == 1: return 1 else: return n * factorial(n - 1) # Test cases print("Test case 1: fa...
simplelr_Filter
[ { "content": "Question:\nYou are given a task to write a Python function that calculates the factorial of a given number using recursion. The function should be named `factorial` and should take a single argument `n`, which is a non-negative integer. The function should return the factorial of `n`. If `n` is 0,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3534, "level": 1, "question": "You are given a task to write a Python function that calculates the factorial of a given number using recursion. The function should be named `factorial` and should take a single argument `n`, which is a non-negative integer. The function should return...
import re from collections import Counter def calculate_highest_frequency_word(file_path: str) -> str: with open(file_path, 'r') as f: text = f.read().lower() words = re.findall(r"[a-z']+", text) processed_words = [] for word in words: stripped = word.strip("'") if str...
simplelr_Package
[ { "content": "Question:\n**Create a function `calculate_highest_frequency_word(file_path)` that reads a text file, calculates the frequency of each word, and identifies the word with the highest frequency. The function should also handle ties in word frequency by returning the alphabetically smallest word among...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3535, "level": 1, "question": "**Create a function `calculate_highest_frequency_word(file_path)` that reads a text file, calculates the frequency of each word, and identifies the word with the highest frequency. The function should also handle ties in word frequency by returning the...
def has_subarray_sum(S, target): prefix_sums = {0} current_sum = 0 for num in S: current_sum += num if (current_sum - target) in prefix_sums: return True prefix_sums.add(current_sum) return False
simplelr_Filter
[ { "content": "Question:\nA person named Maya has a set of integers, denoted by the variable S.\n\nShe wants to determine whether there exists a subarray within S whose elements sum to a target integer, denoted by the variable 'target'.\n\nAssume S contains only positive integers and the target value is also pos...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3536, "level": 1, "question": "A person named Maya has a set of integers, denoted by the variable S.\n\nShe wants to determine whether there exists a subarray within S whose elements sum to a target integer, denoted by the variable 'target'.\n\nAssume S contains only positive intege...
def longest_common_subsequence(X, Y): m = len(X) n = len(Y) # Create a table with (m+1) rows and (n+1) columns 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 X[i-1] == Y[j-1]: dp[i][j] = dp[i-1][j-1]...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the length of the longest common sub sequence between two strings.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3537, "level": 1, "question": "Write a python function to find the length of the longest common sub sequence between two strings.", "split": "train" }
def find_lcs_length(dna1: str, dna2: str) -> int: m = len(dna1) n = len(dna2) # Create a (m+1) x (n+1) DP table initialized with zeros dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if dna1[i-1] == dna2[j-1]: dp...
simplelr_Data_Structure
[ { "content": "Question:\n**Scenario**:\n\nYou are given two DNA sequences represented as strings that consist of lowercase letters. Your task is to determine the length of the longest common subsequence (LCS) between these two sequences. The LCS is the longest sequence that can be derived from both strings by d...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3538, "level": 1, "question": "**Scenario**:\n\nYou are given two DNA sequences represented as strings that consist of lowercase letters. Your task is to determine the length of the longest common subsequence (LCS) between these two sequences. The LCS is the longest sequence that ca...
def filter_strings_starting_with_a(strings): result = [] for s in strings: if s and s[0].lower() == 'a': result.append(s) return result
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of strings and returns a new list containing only the strings that start with the letter 'a'. This function should be case-insensitive.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3539, "level": 1, "question": "Write a Python function that takes a list of strings and returns a new list containing only the strings that start with the letter 'a'. This function should be case-insensitive.", "split": "train" }
def enhanced_gnome_sort(arr): # Handle edge cases arr = list(arr) # Create a copy to avoid modifying the original list n = len(arr) if n <= 1: return arr last_swap_pos = n - 1 # Initialize the last swap position to the end of the array while True: swapped = False ...
simplelr_Data_Structure
[ { "content": "Question:\n### Gnome Sort Enhancement and Analysis\n\nGnome Sort is a simple sorting algorithm, characterized by repeatedly comparing each element with its predecessor and swapping them if they are out of order. The algorithm continues from the beginning if needed, resembling a \"drunken baboon\" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3540, "level": 1, "question": "### Gnome Sort Enhancement and Analysis\n\nGnome Sort is a simple sorting algorithm, characterized by repeatedly comparing each element with its predecessor and swapping them if they are out of order. The algorithm continues from the beginning if neede...
def calculate_area(length, width): if type(length) in (int, float) and type(width) in (int, float): return length * width else: return "Error: Both length and width must be numbers."
simplelr_Filter
[ { "content": "Question:\nYou've been tasked with writing a function to calculate the area of a rectangle. The function should take two parameters: length and width. The function should return the area of the rectangle. \n\nHowever, there is a twist! The function should also be able to handle cases where the len...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3541, "level": 1, "question": "You've been tasked with writing a function to calculate the area of a rectangle. The function should take two parameters: length and width. The function should return the area of the rectangle. \n\nHowever, there is a twist! The function should also be...
def repeatString(s, n): return s * n
simplelr_Taco
[ { "content": "Question:\nGiven a string s and an integer n, write a function that returns a string which is a concatenation of n copies of s. \nExample 1:\nInput: s = \"abc\", n = 3\nOutput: \"abcabcabc\"\n\nExample 2:\nInput: s = \"xyz\", n = 5\nOutput: \"xyzxyzxyzxyzxyz\"\n\nYour Task:\nYou don't need to inpu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3542, "level": 1, "question": "Given a string s and an integer n, write a function that returns a string which is a concatenation of n copies of s. \nExample 1:\nInput: s = \"abc\", n = 3\nOutput: \"abcabcabc\"\n\nExample 2:\nInput: s = \"xyz\", n = 5\nOutput: \"xyzxyzxyzxyzxyz\"\n\...
def is_match(s: str, p: str) -> bool: len_s, len_p = len(s), len(p) dp = [[False] * (len_p + 1) for _ in range(len_s + 1)] dp[0][0] = True # Empty string matches empty pattern for i in range(len_s + 1): for j in range(1, len_p + 1): if j == 1 and p[j-1] == '*': dp[i...
simplelr_Data_Structure
[ { "content": "Question:\nYou are tasked with creating a regular expression matcher that supports the special characters '.' (dot) and '*' (asterisk). The dot matches any single character, and the asterisk matches zero or more of the preceding element. The function must return whether the entire input string mat...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3543, "level": 1, "question": "You are tasked with creating a regular expression matcher that supports the special characters '.' (dot) and '*' (asterisk). The dot matches any single character, and the asterisk matches zero or more of the preceding element. The function must return ...
def square_elements(numbers): """ This function takes a list of numbers and returns a new list containing the squares of each number. Args: numbers (list): A list of integers or floating-point numbers. Returns: list: A new list where each element is the square of the correspond...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of numbers as input and returns a list containing the squares of those numbers. The function should support handling both positive and negative numbers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3544, "level": 1, "question": "Create a function that takes a list of numbers as input and returns a list containing the squares of those numbers. The function should support handling both positive and negative numbers.", "split": "train" }
from typing import List def max_profit(n: int, prices: List[int]) -> int: if n < 2: return 0 min_price = prices[0] max_profit = 0 for price in prices[1:]: current_profit = price - min_price if current_profit > max_profit: max_profit = current_profit if price ...
simplelr_Codeforces
[ { "content": "Question:\nAlex is participating in a Programming Olympiad that has a variety of interesting problems. One of these problems involves analyzing stock prices over a given period of time.\n\nAlex needs your help to determine some metrics related to the stock prices. Given the daily closing prices fo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3545, "level": 1, "question": "Alex is participating in a Programming Olympiad that has a variety of interesting problems. One of these problems involves analyzing stock prices over a given period of time.\n\nAlex needs your help to determine some metrics related to the stock prices...
def remove_vowels(s): vowels = 'aeiouAEIOU' return ''.join([char for char in s if char not in vowels])
simplelr_Filter
[ { "content": "Question:\nYou are given the following task: to write a program that takes a string as input and returns the string with all vowels removed. Write the program in Python.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3546, "level": 1, "question": "You are given the following task: to write a program that takes a string as input and returns the string with all vowels removed. Write the program in Python.", "split": "train" }
def max_subarray_sum(arr): if not arr: return 0 # Return 0 for an empty array case max_current = max_so_far = arr[0] for num in arr[1:]: max_current = max(num, max_current + num) if max_current > max_so_far: max_so_far = max_current return max_so_far
simplelr_Prefill
[ { "content": "Question:\nCreate a function that will take an integer array of any length and return the maximum subarray sum of that array using Kadane's Algorithm.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3547, "level": 1, "question": "Create a function that will take an integer array of any length and return the maximum subarray sum of that array using Kadane's Algorithm.", "split": "train" }
def running_sum(sequence): current_sum = 0 result = [] for num in sequence: current_sum += num result.append(current_sum) return result
simplelr_Evol
[ { "content": "Question:\nDesign a function that accepts a sequence of integers and returns a new sequence where each integer is replaced by a running sum of the original sequence up to that point. The function should handle negative numbers and sequences of varying lengths, including empty sequences.\n\nFor exa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3548, "level": 1, "question": "Design a function that accepts a sequence of integers and returns a new sequence where each integer is replaced by a running sum of the original sequence up to that point. The function should handle negative numbers and sequences of varying lengths, in...
def partition_string(s): if not s: return 0 count = 1 for i in range(1, len(s)): if s[i] != s[i-1]: count += 1 return count
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` consisting of lowercase alphabets. You need to partition the string into as few parts as possible so that each substring contains only one distinct character. Return _the number of parts the string can be partitioned into_.\n\nFor example, if `s = \"aaabbaac\"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3549, "level": 1, "question": "You are given a string `s` consisting of lowercase alphabets. You need to partition the string into as few parts as possible so that each substring contains only one distinct character. Return _the number of parts the string can be partitioned into_.\n...
def group_anagrams(words): anagram_map = {} for word in words: key = ''.join(sorted(word)) if key in anagram_map: anagram_map[key].append(word) else: anagram_map[key] = [word] return list(anagram_map.values())
simplelr_Algorithm
[ { "content": "Question:\nAnagram Grouping with Preserved Word Order\n\n#### Problem Statement:\nIn this task, the goal is to group a list of words into anagrams, maintaining the original order of their first occurrence. An anagram is a word formed by rearranging the letters of another, using all the original le...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3550, "level": 1, "question": "Anagram Grouping with Preserved Word Order\n\n#### Problem Statement:\nIn this task, the goal is to group a list of words into anagrams, maintaining the original order of their first occurrence. An anagram is a word formed by rearranging the letters of...
def max_subarray_sum(arr): if not arr: return 0 # Handle empty array case 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_current return max_global
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the maximum sum of a subarray within a given array of integers. Implement your function using Kadane's Algorithm, which is efficient with a time complexity of O(n).\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3551, "level": 1, "question": "Write a function to find the maximum sum of a subarray within a given array of integers. Implement your function using Kadane's Algorithm, which is efficient with a time complexity of O(n).", "split": "train" }
def find_pair_with_sum(numbers, target): seen = set() for number in numbers: complement = target - number if complement in seen: return (complement, number) seen.add(number) return None
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of numbers and a target sum. The function should return a pair of distinct numbers from the list that add up to the target sum. If no such pair exists, the function should return None. Optimize the solution to run in O(n) time complexity.\nAnswe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3552, "level": 1, "question": "Write a Python function that takes a list of numbers and a target sum. The function should return a pair of distinct numbers from the list that add up to the target sum. If no such pair exists, the function should return None. Optimize the solution to ...
def rotate_list(nums: list[int], k: int) -> list[int]: if not nums: return [] n = len(nums) effective_k = k % n if effective_k == 0: return list(nums) return nums[-effective_k:] + nums[:-effective_k]
simplelr_Algorithm
[ { "content": "Question:\n### Question\n**Problem Statement**:\n\nYou are given a list of integers and an integer `k`. Your task is to rotate the list to the right by `k` steps.\n\n#### Function Signature:\n```python\ndef rotate_list(nums: list[int], k: int) -> list[int]:\n pass\n```\n\n#### Input:\n- `nums`:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3553, "level": 1, "question": "### Question\n**Problem Statement**:\n\nYou are given a list of integers and an integer `k`. Your task is to rotate the list to the right by `k` steps.\n\n#### Function Signature:\n```python\ndef rotate_list(nums: list[int], k: int) -> list[int]:\n ...
def find_first_occurrence(nums, target): for i in range(len(nums)): if nums[i] == target: return i elif nums[i] > target: break return -1
simplelr_Filter
[ { "content": "Question:\nGiven a sorted array of integers, write a function that finds the index of the first occurrence of a given target value. If the target value does not exist in the array, the function should return -1.\n\nExample:\nInput: nums = [1,2,3,4,5,6,7,8,9], target = 5\nOutput: 4\n\nInput: nums =...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3554, "level": 1, "question": "Given a sorted array of integers, write a function that finds the index of the first occurrence of a given target value. If the target value does not exist in the array, the function should return -1.\n\nExample:\nInput: nums = [1,2,3,4,5,6,7,8,9], tar...
def are_anagrams(s, t): # Clean both strings: remove non-alphabet characters and convert to lowercase s_clean = [c.lower() for c in s if c.isalpha()] t_clean = [c.lower() for c in t if c.isalpha()] # Compare the sorted cleaned strings return sorted(s_clean) == sorted(t_clean)
simplelr_Leetcode
[ { "content": "Question:\nGiven two strings `s` and `t`, _determine if they are anagrams of each other_. Two strings are anagrams if they contain the same characters with the same frequencies. You need to return `true` if `s` and `t` are anagrams, and `false` otherwise. The function should be case-insensitive an...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3555, "level": 1, "question": "Given two strings `s` and `t`, _determine if they are anagrams of each other_. Two strings are anagrams if they contain the same characters with the same frequencies. You need to return `true` if `s` and `t` are anagrams, and `false` otherwise. The fun...
def maxMonstersDefeated(n: int, p: int, t: int, d: int, h: list) -> int: sorted_h = sorted(h) count = 0 for i in range(n): required = p - i * t * d if sorted_h[i] > required: break count += 1 return count
simplelr_Code_Contests
[ { "content": "Question:\nA coding wizard named Harry is participating in a tournament where he confronts n powerful monsters, each with unique health points. Harry has a unique spell that can defeat any monster instantly, but it takes t seconds to cast the spell and his spell power decreases by a factor of d fo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3556, "level": 1, "question": "A coding wizard named Harry is participating in a tournament where he confronts n powerful monsters, each with unique health points. Harry has a unique spell that can defeat any monster instantly, but it takes t seconds to cast the spell and his spell ...
def fibonacci_series(n): if not isinstance(n, int) or n < 0: return [] if n == 0: return [] fibs = [] a, b = 0, 1 for _ in range(n): fibs.append(a) a, b = b, a + b return fibs
simplelr_Evol
[ { "content": "Question:\nWrite a Python function called `fibonacci_series(n)` that takes in an integer `n` and returns a list of the first `n` numbers in the Fibonacci sequence, starting from 0. For example, `fibonacci_series(5)` should return `[0, 1, 1, 2, 3]`. Ensure that your function handles the case where ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3557, "level": 1, "question": "Write a Python function called `fibonacci_series(n)` that takes in an integer `n` and returns a list of the first `n` numbers in the Fibonacci sequence, starting from 0. For example, `fibonacci_series(5)` should return `[0, 1, 1, 2, 3]`. Ensure that yo...
from collections import Counter def can_form_palindrome(s): s = s.lower().replace(" ", "") counts = Counter(s) odd_counts = sum(1 for count in counts.values() if count % 2 != 0) return odd_counts <= 1
simplelr_Taco
[ { "content": "Question:\nPalindrome Permutation\n---------------------\n\nGiven a string, write a function to check if it could be rearranged to form a palindrome. Ignore spaces and assume the string consists of only the English alphabet and is case insensitive.\n\nFor the output, return `True` if the string ca...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3558, "level": 1, "question": "Palindrome Permutation\n---------------------\n\nGiven a string, write a function to check if it could be rearranged to form a palindrome. Ignore spaces and assume the string consists of only the English alphabet and is case insensitive.\n\nFor the out...
def kth_smallest(matrix, k): n = len(matrix) low = matrix[0][0] high = matrix[n-1][n-1] while low < high: mid = (low + high) // 2 count = 0 j = n - 1 for i in range(n): while j >= 0 and matrix[i][j] > mid: j -= 1 count...
simplelr_Leetcode
[ { "content": "Question:\nGiven an `n x n` matrix where each of the rows and columns is sorted in ascending order, find the k-th smallest element in the matrix. Note that it is the k-th smallest element in the sorted order, not the k-th distinct element. Ensure to design an algorithm that runs in `O(n log n)` ti...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3559, "level": 1, "question": "Given an `n x n` matrix where each of the rows and columns is sorted in ascending order, find the k-th smallest element in the matrix. Note that it is the k-th smallest element in the sorted order, not the k-th distinct element. Ensure to design an alg...
def sum_of_unique_prime_factors(n): if n <= 1: return 0 factors = set() # Handle the case for 2 separately if n % 2 == 0: factors.add(2) while n % 2 == 0: n = n // 2 # Now check for odd factors starting from 3 i = 3 while i * i <= n: ...
simplelr_Apps
[ { "content": "Question:\nWrite a function that takes an integer `n` and returns the sum of all unique prime factors of `n`. Prime factors are the prime numbers that divide `n` without leaving a remainder. For example, the number 28 has the prime factors 2 and 7, so the function should return 9 (2+7). If the inp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3560, "level": 1, "question": "Write a function that takes an integer `n` and returns the sum of all unique prime factors of `n`. Prime factors are the prime numbers that divide `n` without leaving a remainder. For example, the number 28 has the prime factors 2 and 7, so the functio...
def reverse_digits_in_string(s): digits = [c for c in s if c.isdigit()] reversed_digits = digits[::-1] result = [] i = 0 for c in s: if c.isdigit(): result.append(reversed_digits[i]) i += 1 else: result.append(c) return ''.join(result)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as input and returns the string in reverse order. If the string contains digits, reverse only the digits in the string, leaving all other characters in their original positions. For example, if the input is \"abc123def\", the output should be \"abc3...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3561, "level": 1, "question": "Create a function that takes a string as input and returns the string in reverse order. If the string contains digits, reverse only the digits in the string, leaving all other characters in their original positions. For example, if the input is \"abc12...
import re from collections import Counter def word_frequency(sentence): sentence = sentence.lower() words = re.findall(r'[a-zA-Z]+', sentence) return dict(Counter(words))
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a sentence as input and returns a dictionary with the frequency of each word in the sentence. The function should be case-insensitive and ignore any punctuation. The keys of the dictionary should be the words, and the values should be the number of times each...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3562, "level": 1, "question": "Write a function that takes a sentence as input and returns a dictionary with the frequency of each word in the sentence. The function should be case-insensitive and ignore any punctuation. The keys of the dictionary should be the words, and the values...
def is_palindrome(input_str): if not isinstance(input_str, str) or not input_str: raise ValueError('Input must be a non-empty string') filtered_str = ''.join(char.lower() for char in input_str if char.isalnum()) return filtered_str == filtered_str[::-1]
simplelr_Evol
[ { "content": "Question:\nCreate a function that determines if an input string is a palindrome, ignoring any non-alphanumeric characters and treating uppercase and lowercase letters as equivalent. A palindrome is a word, phrase, or sequence that reads the same backward as forward. The function must also check th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3563, "level": 1, "question": "Create a function that determines if an input string is a palindrome, ignoring any non-alphanumeric characters and treating uppercase and lowercase letters as equivalent. A palindrome is a word, phrase, or sequence that reads the same backward as forwa...
def max_sum_strictly_increasing_subarray(nums): if not nums: return 0 n = len(nums) if n == 1: return nums[0] max_sum = current_sum = nums[0] for i in range(1, n): if nums[i] > nums[i-1]: current_sum += nums[i] else: current_sum = nums[i] ...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array `nums` of positive integers, return the maximum sum of any strictly increasing subarray of `nums`. A strictly increasing subarray is defined as a contiguous portion of the array where each element is strictly greater than the one before it. If the array is empty or consis...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3564, "level": 1, "question": "Given an array `nums` of positive integers, return the maximum sum of any strictly increasing subarray of `nums`. A strictly increasing subarray is defined as a contiguous portion of the array where each element is strictly greater than the one before ...
def three_sum(nums, target): nums.sort() res = [] n = len(nums) for i in range(n - 2): if i > 0 and nums[i] == nums[i - 1]: continue a = nums[i] left = i + 1 right = n - 1 while left < right: current_sum = a + nums[left] + nums[right] ...
simplelr_Apps
[ { "content": "Question:\nGiven an integer array nums, find and return all the triplets [nums[i], nums[j], nums[k]] (i ≠ j ≠ k), such that the triplets sum up to a given target value. Note that the result should not contain duplicate triplets.\n\nExample 1:\nInput: nums = [-1,0,1,2,-1,-4], target = 0\nOutput: [[...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3565, "level": 1, "question": "Given an integer array nums, find and return all the triplets [nums[i], nums[j], nums[k]] (i ≠ j ≠ k), such that the triplets sum up to a given target value. Note that the result should not contain duplicate triplets.\n\nExample 1:\nInput: nums = [-1,0...
def longest_subsequence(nums): max_dp = {} result = 0 for num in nums: current_max = 0 for dx in (-1, 0, 1): key = num + dx if key in max_dp and max_dp[key] > current_max: current_max = max_dp[key] current_dp = current_max + 1 if num in...
simplelr_Leetcode
[ { "content": "Question:\nGiven a list of integers `nums`, find the length of the longest subsequence such that the difference between the consecutive elements is either `-1`, `0`, or `1`. A subsequence is derived from another list by deleting some or no elements without changing the order of the remaining eleme...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3566, "level": 1, "question": "Given a list of integers `nums`, find the length of the longest subsequence such that the difference between the consecutive elements is either `-1`, `0`, or `1`. A subsequence is derived from another list by deleting some or no elements without changi...
from collections import defaultdict def longest_substring_with_k_distinct(s, k): count_map = defaultdict(int) max_len = 0 left = 0 for right in range(len(s)): char = s[right] count_map[char] += 1 while len(count_map) > k: left_char = s[left] ...
simplelr_Filter
[ { "content": "Question:\nGiven a string str, find the length of the longest substring that contains at most K distinct characters.\n\nExample 1:\nInput: str = \"araaci\", K = 2\nOutput: 4\nExplanation: The longest substring \"araa\" contains 2 distinct characters.\n\nExample 2:\nInput: str = \"abcba\", K = 2\nO...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3567, "level": 1, "question": "Given a string str, find the length of the longest substring that contains at most K distinct characters.\n\nExample 1:\nInput: str = \"araaci\", K = 2\nOutput: 4\nExplanation: The longest substring \"araa\" contains 2 distinct characters.\n\nExample 2...
from collections import defaultdict def rearrange_array(arr, k): if k == 0: return arr # Assuming k is a positive integer as per problem constraints groups = defaultdict(list) for num in arr: r = num % k groups[r].append(num) # Check for 0 and k/2 remainders if len(gr...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `arr`, determine if it is possible to rearrange the elements of `arr` such that the sum of any two adjacent elements is not divisible by a given integer `k`. If such a rearrangement is possible, return the rearranged array; otherwise, return an empty array.\nA...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3568, "level": 1, "question": "Given an array of integers `arr`, determine if it is possible to rearrange the elements of `arr` such that the sum of any two adjacent elements is not divisible by a given integer `k`. If such a rearrangement is possible, return the rearranged array; o...
def total_work_hours(logs): employee_dict = {} for log in logs: name = log['employee'] hours = log['hours'] if name in employee_dict: employee_dict[name] += hours else: employee_dict[name] = hours result = [{'employee': emp, 'total_hours': total} ...
simplelr_Taco
[ { "content": "Question:\nA company is organizing a system for recording and processing employee work logs. Each employee can log their work hours for different projects they are involved in. The goal is to find out the total hours worked by each employee across all projects.\n\nWrite a function to compute and l...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3569, "level": 1, "question": "A company is organizing a system for recording and processing employee work logs. Each employee can log their work hours for different projects they are involved in. The goal is to find out the total hours worked by each employee across all projects.\n...
def isUniqueString(s): return len(set(s)) == len(s)
simplelr_Taco
[ { "content": "Question:\nYour task is to write a function `isUniqueString`.\n\nThis function should take a single argument `s`, which is a string, and return `True` if all the characters in the string are unique and `False` if there are any duplicate characters.\n\nFor example:\n\n```isUniqueString(\"apple\")``...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3570, "level": 1, "question": "Your task is to write a function `isUniqueString`.\n\nThis function should take a single argument `s`, which is a string, and return `True` if all the characters in the string are unique and `False` if there are any duplicate characters.\n\nFor example...
def fraction_to_decimal(numerator, denominator): if numerator == 0: return "0" sign = '-' if (numerator < 0) ^ (denominator < 0) else '' numerator = abs(numerator) denominator = abs(denominator) integer_part = numerator // denominator remainder = numerator % denominator ...
simplelr_Taco
[ { "content": "Question:\nWrite a function called `fraction_to_decimal` that converts a fraction given as two integers (numerator and denominator) into a string representing its decimal form. If the decimal is repeating, enclose the repeating part in parentheses.\n\nFor example, given numerator = 1 and denominat...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3571, "level": 1, "question": "Write a function called `fraction_to_decimal` that converts a fraction given as two integers (numerator and denominator) into a string representing its decimal form. If the decimal is repeating, enclose the repeating part in parentheses.\n\nFor example...
import pandas as pd import os def generate_statistics_report(csv_filename): # Read the CSV file into a DataFrame df = pd.read_csv(csv_filename) # Select numeric columns only (int64 and float64) numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns if len(numeric_cols) == 0: ...
simplelr_Package
[ { "content": "Question:\nYou are asked to implement a Python function named `generate_statistics_report` that processes data from a given CSV file and outputs basic statistical measures for each numeric column in the file. The function should:\n\n1. Read the provided CSV file into a pandas DataFrame.\n2. Calcul...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3572, "level": 1, "question": "You are asked to implement a Python function named `generate_statistics_report` that processes data from a given CSV file and outputs basic statistical measures for each numeric column in the file. The function should:\n\n1. Read the provided CSV file ...
def remove_substring(text, substring): if not substring: return text return text.replace(substring, '')
simplelr_Prefill
[ { "content": "Question:\nWrite a function to remove all instances of a given string `substring` from `text`. The function should return the resulting string after all instances have been removed.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3573, "level": 1, "question": "Write a function to remove all instances of a given string `substring` from `text`. The function should return the resulting string after all instances have been removed.", "split": "train" }
def merge_sorted_lists(list1: list[int], list2: list[int]) -> list[int]: if not list1: return list2 if not list2: return list1 i = j = 0 result = [] while i < len(list1) and j < len(list2): if list1[i] <= list2[j]: result.append(list1[i]) i += 1 ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement:\nCreate a function `merge_sorted_lists` that takes two sorted lists of integers and merges them into a single sorted list. The function should handle merging efficiently, leveraging the sorted property of the input lists.\n\n**Function Signature**:\n```python\ndef...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3574, "level": 1, "question": "### Problem Statement:\nCreate a function `merge_sorted_lists` that takes two sorted lists of integers and merges them into a single sorted list. The function should handle merging efficiently, leveraging the sorted property of the input lists.\n\n**Fu...
def quick_sort(arr: list) -> list: if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] 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] return quick_sort(left) + middle + quick_sort(right)
simplelr_Algorithm
[ { "content": "Question:\n### Quick Sort Implementation\n\n#### Scenario:\nYou are given an array of integers that you need to sort using the Quick Sort algorithm. Quick Sort is a divide-and-conquer algorithm that selects a 'pivot' element from the array and partitions the other elements into two sub-arrays, acc...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3575, "level": 1, "question": "### Quick Sort Implementation\n\n#### Scenario:\nYou are given an array of integers that you need to sort using the Quick Sort algorithm. Quick Sort is a divide-and-conquer algorithm that selects a 'pivot' element from the array and partitions the othe...
import heapq from collections import defaultdict def safest_path(rooms): # Build the graph graph = defaultdict(list) for room_number in range(len(rooms)): room_data = rooms[room_number] for door in room_data.values(): for target, danger in door: if target < len(r...
simplelr_Taco
[ { "content": "Question:\nYou are playing a board game with your friends that involves navigating through a series of rooms. Each room has a number of doors leading to other rooms, and each door has a trap with a numerical danger level.\n\nTo win, you need to find the safest path from the starting room (Room 0) ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3576, "level": 1, "question": "You are playing a board game with your friends that involves navigating through a series of rooms. Each room has a number of doors leading to other rooms, and each door has a trap with a numerical danger level.\n\nTo win, you need to find the safest pa...
import subprocess def run_shell_command(command): result = subprocess.run( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) return (result.stdout, result.stderr)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that utilizes the `subprocess` module to execute a shell command and capture its output. The function should handle both standard output and standard error streams, and it should return the output and any errors as a tuple.\nAnswer:\nLet's think step by step.\n",...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3577, "level": 1, "question": "Write a Python function that utilizes the `subprocess` module to execute a shell command and capture its output. The function should handle both standard output and standard error streams, and it should return the output and any errors as a tuple.", ...
def is_palindrome_number(n): if n < 0: return False original_num = n reversed_num = 0 while n > 0: last_digit = n % 10 reversed_num = reversed_num * 10 + last_digit n = n // 10 return original_num == reversed_num
simplelr_Filter
[ { "content": "Question:\nCould you provide a Python function that checks if a number is a palindrome without converting it to a string?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3578, "level": 1, "question": "Could you provide a Python function that checks if a number is a palindrome without converting it to a string?", "split": "train" }
def sum_corresponding_elements(list1, list2): result = [] max_length = max(len(list1), len(list2)) for i in range(max_length): # Process element from list1 a = list1[i] if i < len(list1) else 0 if not (isinstance(a, (int, float)) and not isinstance(a, bool)): a = 0 ...
simplelr_Filter
[ { "content": "Question:\nPlease write a function in Python to generate a list containing the sum of corresponding elements given two lists. However, the function should also handle cases where the lengths of the two input lists are not equal. In such cases, the function should continue adding the remaining elem...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3579, "level": 1, "question": "Please write a function in Python to generate a list containing the sum of corresponding elements given two lists. However, the function should also handle cases where the lengths of the two input lists are not equal. In such cases, the function should...
def sum_of_elements(lst): return sum(lst)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the sum of all elements in a list using Python. The function should take a list of integers as input and return the sum of all the elements in the list. If the list is empty, the function should return 0.\nAnswer:\nLet's think step by step.\n", "role": ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3580, "level": 1, "question": "Write a function to calculate the sum of all elements in a list using Python. The function should take a list of integers as input and return the sum of all the elements in the list. If the list is empty, the function should return 0.", "split": "tra...
def rotate_array_right(arr): if len(arr) <= 1: return arr return [arr[-1]] + arr[:-1]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to rotate an array one position to the right.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3581, "level": 1, "question": "Write a python function to rotate an array one position to the right.", "split": "train" }
def reverse_string(s): stack = [] for char in s: stack.append(char) reversed_s = '' while stack: reversed_s += stack.pop() return reversed_s
simplelr_Prefill
[ { "content": "Question:\nWrite a function to reverse a string in Python without using slicing. Use a stack data structure to achieve this.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3582, "level": 1, "question": "Write a function to reverse a string in Python without using slicing. Use a stack data structure to achieve this.", "split": "train" }
def find_single_number(nums): result = 0 for num in nums: result ^= num return result
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the single number in a non-empty array of integers where every other number appears twice. The function should return the unique number without using any extra space and in O(n) time complexity.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3583, "level": 1, "question": "Write a python function to find the single number in a non-empty array of integers where every other number appears twice. The function should return the unique number without using any extra space and in O(n) time complexity.", "split": "train" }
def max_distinct_timestamps(log: str, k: int) -> int: timestamps = list(map(int, log.split(','))) n = len(timestamps) max_global = 0 for i in range(n): seen = set() seen.add(timestamps[i]) current_min = timestamps[i] current_max = timestamps[i] current_distinct = ...
simplelr_Taco
[ { "content": "Question:\nA company uses a sophisticated computer system to monitor network traffic. To investigate potential issues, data packets are logged with a series of timestamps. A timestamp is a positive integer representing seconds since an arbitrary epoch. The logs are represented as a string of times...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3584, "level": 1, "question": "A company uses a sophisticated computer system to monitor network traffic. To investigate potential issues, data packets are logged with a series of timestamps. A timestamp is a positive integer representing seconds since an arbitrary epoch. The logs a...
def count_overlapping_occurrences(main_string, substring): sub_length = len(substring) count = 0 for i in range(len(main_string) - sub_length + 1): if main_string[i:i+sub_length] == substring: count += 1 return count
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to count the number of occurrences of a substring within a string, considering overlapping occurrences as well. For example, the string \"abababa\" contains 3 occurrences of the substring \"aba\" when counting overlaps.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3585, "level": 1, "question": "Write a python function to count the number of occurrences of a substring within a string, considering overlapping occurrences as well. For example, the string \"abababa\" contains 3 occurrences of the substring \"aba\" when counting overlaps.", "spl...
import itertools def all_subsets(lst): return [subset for r in range(len(lst)+1) for subset in itertools.combinations(lst, r)]
simplelr_Filter
[ { "content": "Question:\nIn Python, how can I create a program that generates all possible subsets of a given list of numbers, including the empty set and the set itself? This is similar to finding combinations of all sizes in a list?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3586, "level": 1, "question": "In Python, how can I create a program that generates all possible subsets of a given list of numbers, including the empty set and the set itself? This is similar to finding combinations of all sizes in a list?", "split": "train" }
def two_sum(nums: list[int], target: int) -> list[int]: seen = {} for index, num in enumerate(nums): complement = target - num if complement in seen: return [seen[complement], index] seen[num] = index return []
simplelr_Algorithm
[ { "content": "Question:\n### Context\nYou are developing a system that processes large datasets of numbers and needs to efficiently find the two numbers that add up to a specific target. Your task is to implement a function that identifies these two numbers from a given list.\n\n### Problem Statement\nImplement...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3587, "level": 1, "question": "### Context\nYou are developing a system that processes large datasets of numbers and needs to efficiently find the two numbers that add up to a specific target. Your task is to implement a function that identifies these two numbers from a given list.\...
def is_valid_password(password): return password == "Password123!"
simplelr_Filter
[ { "content": "Question:\nPassword Protection\n\nWe'd like to create a password-protected system. When the application starts, it prompts the user for a password. If the password is correct, the system lets the user in. If the password is incorrect, it keeps asking for the password until the user guesses correct...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3588, "level": 1, "question": "Password Protection\n\nWe'd like to create a password-protected system. When the application starts, it prompts the user for a password. If the password is correct, the system lets the user in. If the password is incorrect, it keeps asking for the pass...
import subprocess import argparse import os def convert_ps_to_pdf(input_file, output_file): """ Convert a PostScript file to PDF using Ghostscript. Args: input_file (str): Path to the input PostScript file. output_file (str): Path to the output PDF file. Returns: bool:...
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python script that allows me to convert PostScript (PS) files into PDF files on a Windows system?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3589, "level": 1, "question": "Can you provide a Python script that allows me to convert PostScript (PS) files into PDF files on a Windows system?", "split": "train" }
def count_characters(input_string): # Convert the string to lowercase to ignore case sensitivity lower_string = input_string.lower() # Initialize an empty dictionary to store character counts char_count = {} # Iterate over each character in the lowercase string for c in lower_string: ...
simplelr_Filter
[ { "content": "Question:\nPlease create a Python code snippet that counts the number of occurrences of each character in a given string, ignoring case sensitivity and excluding any whitespace characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3590, "level": 1, "question": "Please create a Python code snippet that counts the number of occurrences of each character in a given string, ignoring case sensitivity and excluding any whitespace characters.", "split": "train" }
from typing import List def rotate_matrix(matrix: List[List[int]]) -> None: 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_Algorithm
[ { "content": "Question:\n### Rotate 2D Matrix Clockwise\n\nYou are given a square 2D matrix of integers. Write a function to rotate the matrix by 90 degrees clockwise in-place.\n\n**Function Signature**: `def rotate_matrix(matrix: List[List[int]]) -> None`\n\n**Inputs**:\n1. `matrix` (List[List[int]]): A non-em...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3591, "level": 1, "question": "### Rotate 2D Matrix Clockwise\n\nYou are given a square 2D matrix of integers. Write a function to rotate the matrix by 90 degrees clockwise in-place.\n\n**Function Signature**: `def rotate_matrix(matrix: List[List[int]]) -> None`\n\n**Inputs**:\n1. `...
def parse_person(file_path): people = [] with open(file_path, 'r') as file: lines = file.readlines() for i in range(0, len(lines), 5): person_info = lines[i:i+5] if len(person_info) < 5: break person = { 'name': person_info[0].s...
simplelr_Filter
[ { "content": "Question:\nI have a text file containing information about a person. The text file contains their name, age, occupation, phone number, and address. The file is formatted something like this:\n\nJohn Doe\n25\nSalesman\n123-456-7890\n123 Main St, Anytown, USA 12345\n\nThe file contains one person pe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3592, "level": 1, "question": "I have a text file containing information about a person. The text file contains their name, age, occupation, phone number, and address. The file is formatted something like this:\n\nJohn Doe\n25\nSalesman\n123-456-7890\n123 Main St, Anytown, USA 12345...
def is_symmetric(matrix: list[list[int]]) -> bool: n = len(matrix) for i in range(n): for j in range(i + 1, n): if matrix[i][j] != matrix[j][i]: return False return True
simplelr_Algorithm
[ { "content": "Question:\n### Matrix Transposition and Symmetry Check\n\n#### Context:\nIn many computational problems, matrices are utilized extensively, and it is often necessary to transpose them and check for certain properties, such as symmetry, which is useful in fields like linear algebra, data science, a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3593, "level": 1, "question": "### Matrix Transposition and Symmetry Check\n\n#### Context:\nIn many computational problems, matrices are utilized extensively, and it is often necessary to transpose them and check for certain properties, such as symmetry, which is useful in fields l...
from collections import defaultdict def process_transactions(transactions): sums_dict = defaultdict(int) for transaction in transactions: unique_id = transaction['id'] amount = transaction['amount'] sums_dict[unique_id] += amount return dict(sums_dict)
simplelr_Evol
[ { "content": "Question:\nDesign an algorithm that processes a list of transactions, where each transaction includes a unique identifier, a timestamp, and an amount. Group these transactions by their unique identifiers and calculate the sum of amounts for each identifier. Return a dictionary where the keys are t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3594, "level": 1, "question": "Design an algorithm that processes a list of transactions, where each transaction includes a unique identifier, a timestamp, and an amount. Group these transactions by their unique identifiers and calculate the sum of amounts for each identifier. Retur...
def bubble_sort(lst): n = len(lst) for i in range(n - 1): swapped = False # Flag to check if any swap occurred for j in range(n - i - 1): if lst[j] > lst[j + 1]: # Swap elements lst[j], lst[j + 1] = lst[j + 1], lst[j] swapped = True ...
simplelr_Filter
[ { "content": "Question:\nDetailed Implementation of a simple Bubble Sort algorithm in Python with explanation.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3595, "level": 1, "question": "Detailed Implementation of a simple Bubble Sort algorithm in Python with explanation.", "split": "train" }
def calculate_mean(numbers): if not numbers: return 0 return sum(numbers) / len(numbers)
simplelr_Filter
[ { "content": "Question:\nDesign an algorithm in Python to calculate the mean of a list of numbers. Make sure to handle the case where the list might be empty to avoid division by zero.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3596, "level": 1, "question": "Design an algorithm in Python to calculate the mean of a list of numbers. Make sure to handle the case where the list might be empty to avoid division by zero.", "split": "train" }
def encode(s): if not s: return "" result = "" current_char = s[0] count = 1 for char in s[1:]: if char == current_char: count += 1 else: result += current_char + str(count) current_char = char count = 1 result += current_ch...
simplelr_Taco
[ { "content": "Question:\nGiven a string, encode it by counting repeated characters. The encoding should be done in a format where each character is followed by the number of times it appears consecutively. If the character does not repeat, it should be followed by just '1'. For example, the string \"aaabbc\" sh...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3597, "level": 1, "question": "Given a string, encode it by counting repeated characters. The encoding should be done in a format where each character is followed by the number of times it appears consecutively. If the character does not repeat, it should be followed by just '1'. Fo...
from collections import Counter from typing import List def sum_of_unique_elements(arr: List[int]) -> int: """ Find the sum of all elements that appear exactly once in the array. Args: arr (List[int]): List of integers. Returns: int: The sum of all unique elements in the array. ""...
simplelr_Algorithm
[ { "content": "Question:\n**Sum of Unique Elements**\n\nYou are given an array of integers, where some elements may appear multiple times. Your task is to find the sum of all elements in the array that appear exactly once.\n\nImplement the function `sum_of_unique_elements(arr: List[int]) -> int` that returns the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3598, "level": 1, "question": "**Sum of Unique Elements**\n\nYou are given an array of integers, where some elements may appear multiple times. Your task is to find the sum of all elements in the array that appear exactly once.\n\nImplement the function `sum_of_unique_elements(arr: ...
def canPartition(arr, N): total = sum(arr) if total % 2 != 0: return False target = total // 2 dp = [False] * (target + 1) dp[0] = True # Base case: sum 0 is always possible for num in arr: for j in range(target, num - 1, -1): if dp[j - num]: ...
simplelr_Taco
[ { "content": "Question:\nNina has a collection of N unique bottles, each with a distinct amount of liquid. She loves to experiment and wants to divide the liquid into two groups with equal sum using any subset of the bottles. However, with each bottle's capacity being unique, this might not be straightforward. ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3599, "level": 1, "question": "Nina has a collection of N unique bottles, each with a distinct amount of liquid. She loves to experiment and wants to divide the liquid into two groups with equal sum using any subset of the bottles. However, with each bottle's capacity being unique, ...