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 run_length_encoding(data: str) -> str: if not data: return "" result = "" current_char = data[0] count = 1 for char in data[1:]: if char == current_char: count += 1 else: # Process the current group while count > 0: ...
simplelr_Algorithm
[ { "content": "Question:\n### Context:\nIn data processing and analysis, it's common to encounter situations where you need to compress sequences of data by grouping identical elements. RLE (Run Length Encoding) is a simple and effective compression method for sequences with repeating elements. Understanding how...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9600, "level": 1, "question": "### Context:\nIn data processing and analysis, it's common to encounter situations where you need to compress sequences of data by grouping identical elements. RLE (Run Length Encoding) is a simple and effective compression method for sequences with re...
def calculate_frequencies(lst): freq = {} for num in lst: if num in freq: freq[num] += 1 else: freq[num] = 1 return freq
simplelr_Filter
[ { "content": "Question:\nYou are a code writer and you want to write a function in Python that takes a list of integers and returns a dictionary containing the frequency of each integer in the list. How would you write this function?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9601, "level": 1, "question": "You are a code writer and you want to write a function in Python that takes a list of integers and returns a dictionary containing the frequency of each integer in the list. How would you write this function?", "split": "train" }
def is_palindrome(s): # Remove all non-alphanumeric characters and convert to lowercase cleaned_s = ''.join([c.lower() for c in s if c.isalnum()]) # Check if the cleaned string is a palindrome return cleaned_s == cleaned_s[::-1] # Example usage if __name__ == "__main__": input_str = input("Ent...
simplelr_Filter
[ { "content": "Question:\nHow can I create a basic string manipulation program in Python that checks if a given string is a palindrome?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9602, "level": 1, "question": "How can I create a basic string manipulation program in Python that checks if a given string is a palindrome?", "split": "train" }
def findElement(n, m, M, k): for i in range(n): for j in range(m): if M[i][j] == k: return (i, j) return (-1, -1)
simplelr_Taco
[ { "content": "Question:\nGiven a matrix `M` of size `n x m` filled with distinct integers, you need to find the position (row and column indices) of the integer `k` in the matrix. If `k` is present in the matrix, return a pair of integers representing the row and column indices (starting from 0). If `k` is not ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9603, "level": 1, "question": "Given a matrix `M` of size `n x m` filled with distinct integers, you need to find the position (row and column indices) of the integer `k` in the matrix. If `k` is present in the matrix, return a pair of integers representing the row and column indice...
def rearrange_columns(df, new_order): return df[new_order] # Example usage: # df = DataFrame(columns=['A', 'B', 'C', 'D']) # new_order = ['C', 'B', 'D', 'A'] # df = reorder_columns(df, new_order)
simplelr_Filter
[ { "content": "Question:\nI have been asked to create a code that can rearrange the columns of a given DataFrame. The column names are stored in a list, and I need to rearrange them in a specific order. \n\nFor example, if the DataFrame `df` has columns `['A', 'B', 'C', 'D']`, and the list of column names in the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9604, "level": 1, "question": "I have been asked to create a code that can rearrange the columns of a given DataFrame. The column names are stored in a list, and I need to rearrange them in a specific order. \n\nFor example, if the DataFrame `df` has columns `['A', 'B', 'C', 'D']`, ...
import fcntl def lock_manager(file_path: str, command: str) -> str: if command not in {'LOCK_SH_NON_BLOCK', 'LOCK_EX', 'LOCK_UN'}: return "Invalid command" try: with open(file_path, 'r+') as f: fd = f.fileno() if command == 'LOCK_SH_NON_BLOCK': fcntl...
simplelr_Docs
[ { "content": "Question:\n### File Descriptor Lock Manager\n\nYour task is to implement a function called `lock_manager` that uses the `fcntl` module to manage file descriptor locks in a Unix-like operating system. The function will take a file path and a command as input and perform the specified locking operat...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9605, "level": 1, "question": "### File Descriptor Lock Manager\n\nYour task is to implement a function called `lock_manager` that uses the `fcntl` module to manage file descriptor locks in a Unix-like operating system. The function will take a file path and a command as input and p...
import numpy as np def calculate_euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float: difference = point1 - point2 return np.linalg.norm(difference)
simplelr_Algorithm
[ { "content": "Question:\nEuclidean Distance Calculation\n\nEuclidean distance is a measure of the straight-line distance between two points in Euclidean space. In this task, you will implement a function that calculates the Euclidean distance between two points in a given n-dimensional space.\n\nThe Euclidean d...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9606, "level": 1, "question": "Euclidean Distance Calculation\n\nEuclidean distance is a measure of the straight-line distance between two points in Euclidean space. In this task, you will implement a function that calculates the Euclidean distance between two points in a given n-di...
def most_expensive_items(records): category_max = {} for record in records: name, category, price, qty = record if qty <= 0: continue if category not in category_max: category_max[category] = (price, name) else: current_price, current_name = ca...
simplelr_Taco
[ { "content": "Question:\nMaria is an aspiring software engineer and is working on developing a relational database. She needs to design an efficient query to retrieve information from a set of records about different items in a store. Each record contains the item's name, category, price, and quantity in stock....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9607, "level": 1, "question": "Maria is an aspiring software engineer and is working on developing a relational database. She needs to design an efficient query to retrieve information from a set of records about different items in a store. Each record contains the item's name, cate...
def find_non_duplicate(nums): result = 0 for num in nums: result ^= num return result
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to find the non-duplicate number in a list of integers where every other number appears twice except for one. The list is not sorted and the numbers can be in any order.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9608, "level": 1, "question": "Write a Python function to find the non-duplicate number in a list of integers where every other number appears twice except for one. The list is not sorted and the numbers can be in any order.", "split": "train" }
def is_sorted(stack): """ Determines if the given stack's elements are in ascending order from bottom to top. Parameters: stack (list): A list of integers representing the stack (with the first element as the bottom). Returns: bool: True if the stack is sorted in ascending order from b...
simplelr_Data_Structure
[ { "content": "Question:\n**Scenario**: \nYou're assisting the production team in validating the sorted batches of products lined up for quality inspection. Each batch is represented as a stack of product IDs. Your task is to implement a function that verifies if any given stack of IDs is sorted in ascending ord...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9609, "level": 1, "question": "**Scenario**: \nYou're assisting the production team in validating the sorted batches of products lined up for quality inspection. Each batch is represented as a stack of product IDs. Your task is to implement a function that verifies if any given stac...
def find_pattern_indices(text: str, pattern: str) -> list: if not pattern: return [] m = len(pattern) n = len(text) if m > n: return [] # Compute the LPS array for the pattern lps = [0] * m length = 0 # Length of the previous longest prefix suffix for...
simplelr_Algorithm
[ { "content": "Question:\n### String Pattern Matching Challenge\n\nYou are working on a text analysis tool that needs to detect patterns in strings. You have been tasked with implementing a function that locates all starting indices of a specified pattern within a given text.\n\n#### Task\n\n1. Implement the fol...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9610, "level": 1, "question": "### String Pattern Matching Challenge\n\nYou are working on a text analysis tool that needs to detect patterns in strings. You have been tasked with implementing a function that locates all starting indices of a specified pattern within a given text.\n...
def total_wood_collected(heights, cut_height): return sum(h - cut_height for h in heights if h > cut_height)
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of `n` integers, `heights`, where each integer represents the height of a tree. You are also given an integer `cut_height`. You need to cut down all trees that are taller than `cut_height` so that their new height becomes `cut_height`. After performing the operation...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9611, "level": 1, "question": "You are given a list of `n` integers, `heights`, where each integer represents the height of a tree. You are also given an integer `cut_height`. You need to cut down all trees that are taller than `cut_height` so that their new height becomes `cut_heig...
def calculate_trapped_water(heights): if not heights or len(heights) < 2: return 0 n = len(heights) left_max = [0] * n right_max = [0] * n for i in range(1, n): left_max[i] = max(left_max[i-1], heights[i-1]) for i in range(n-2, -1, -1): right_max[i] = max(ri...
simplelr_Evol
[ { "content": "Question:\nGiven a list of non-negative integers representing the heights of terrain in sequential order, you are required to calculate the maximum amount of water that can be trapped between the terrains after a rainfall. The list will contain at least two heights and water trapped at index i is ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9612, "level": 1, "question": "Given a list of non-negative integers representing the heights of terrain in sequential order, you are required to calculate the maximum amount of water that can be trapped between the terrains after a rainfall. The list will contain at least two heigh...
def count_string_components(s): uppercase = 0 lowercase = 0 digits = 0 special = 0 for char in s: if char.isupper(): uppercase += 1 elif char.islower(): lowercase += 1 elif char.isdigit(): digits += 1 else: special += 1 ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as input and returns the number of uppercase letters, lowercase letters, digits, and special characters in the string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9613, "level": 1, "question": "Create a function that takes a string as input and returns the number of uppercase letters, lowercase letters, digits, and special characters in the string.", "split": "train" }
def next_permutation(lst: list) -> None: n = len(lst) i = n - 2 # Step 1: Find the largest index `i` such that lst[i] < lst[i + 1] while i >= 0 and lst[i] >= lst[i + 1]: i -= 1 if i == -1: # If no such index found, the list is in descending order; reverse the entire list ls...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nWrite a function `next_permutation` that takes a list of integers and rearranges them into the lexicographically next greater permutation of numbers. If no such permutation is possible, it rearranges it in the lowest possible order (i.e., sorted in ascending order...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9614, "level": 1, "question": "### Problem Statement\nWrite a function `next_permutation` that takes a list of integers and rearranges them into the lexicographically next greater permutation of numbers. If no such permutation is possible, it rearranges it in the lowest possible ord...
import heapq def shortest_path(n: int, edges: list[tuple[int, int, int]], source: int, targets: list[int]) -> list[int]: # Build adjacency list adj = [[] for _ in range(n)] for u, v, w in edges: adj[u].append((v, w)) # Initialize distances INF = 10**18 distance = [INF] * n dist...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Challenge: Shortest Path in Weighted Graph\n\n#### Scenario:\nYou are tasked with developing a routing system for a delivery company. The system must calculate the shortest route for a delivery truck to travel from a distribution center to various delivery locations. The road...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9615, "level": 1, "question": "### Coding Challenge: Shortest Path in Weighted Graph\n\n#### Scenario:\nYou are tasked with developing a routing system for a delivery company. The system must calculate the shortest route for a delivery truck to travel from a distribution center to v...
def book_filter(records, criteria): result = [] books = records.split(';') for book in books: parts = book.split(', ') if len(parts) < 2: continue # skip malformed records, though problem states they are well-formed # Extract title, genre, and year title_part = p...
simplelr_Apps
[ { "content": "Question:\nA bookstore keeps a record of books and their related information in a list, where each book's data is a string in the format: `\"Title by Author in Genre, published: YYYY, pages: nnn\"`. Sometimes, the store receives customer's requests to provide books based on genre or year of public...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9616, "level": 1, "question": "A bookstore keeps a record of books and their related information in a list, where each book's data is a string in the format: `\"Title by Author in Genre, published: YYYY, pages: nnn\"`. Sometimes, the store receives customer's requests to provide boo...
def length_of_longest_substring_k_distinct(s, k): if k == 0: return -1 # Assuming k=0 is invalid as per problem constraints max_len = -1 freq = {} left = 0 distinct = 0 for right in range(len(s)): char = s[right] # If the character is new or its count was zero,...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` consisting of lowercase English letters, find the length of the longest contiguous substring with exactly `k` distinct characters. If there is no such substring, return `-1`.\n\nFor example, given the string `s = \"eceba\"` and `k = 2`, the longest contiguous substrin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9617, "level": 1, "question": "Given a string `s` consisting of lowercase English letters, find the length of the longest contiguous substring with exactly `k` distinct characters. If there is no such substring, return `-1`.\n\nFor example, given the string `s = \"eceba\"` and `k = ...
import keyword import re def clean_variable_names(var_str): # Get the list of reserved keywords reserved_keywords = set(keyword.kwlist) # Regular expression pattern for valid Python identifiers pattern = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$') # Split the input string by commas and proces...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string of variable names, separates them by commas and removes any that match either a list of reserved keywords or are not valid Python identifiers. You should consider using regular expressions to match the variable names.\nAnswer:\nLet's think step by s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9618, "level": 1, "question": "Create a function that takes a string of variable names, separates them by commas and removes any that match either a list of reserved keywords or are not valid Python identifiers. You should consider using regular expressions to match the variable nam...
def count_unique_characters(s): s_lower = s.lower() unique_chars = set(s_lower) return len(unique_chars)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the total number of unique characters in a given string, treating uppercase and lowercase letters as identical. For example, the string \"HelloWorld\" would have 7 unique characters, considering 'H' and 'h' as the same.\nAnswer:\nLet's think step by step.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9619, "level": 1, "question": "Write a function to calculate the total number of unique characters in a given string, treating uppercase and lowercase letters as identical. For example, the string \"HelloWorld\" would have 7 unique characters, considering 'H' and 'h' as the same.", ...
def date_to_string(month, day): months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] month_name = months[month - 1] if 11 <= (day % 100) <= 13: suffix = 'th' else: last_digit = day % 10 ...
simplelr_Filter
[ { "content": "Question:\nI'll provide you with some test cases, and you should write a Python function to pass all of them. Here are the test cases:\n\nTest Case 1:\nInput: month = 1, day = 1\nOutput: [\"January\", \"1st\"]\n\nTest Case 2:\nInput: month = 12, day = 31\nOutput: [\"December\", \"31st\"]\n\nTest C...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9620, "level": 1, "question": "I'll provide you with some test cases, and you should write a Python function to pass all of them. Here are the test cases:\n\nTest Case 1:\nInput: month = 1, day = 1\nOutput: [\"January\", \"1st\"]\n\nTest Case 2:\nInput: month = 12, day = 31\nOutput:...
from typing import List def longest_increasing_subsequence(arr: List[int]) -> int: n = len(arr) dp = [1] * n # Initialize each element's LIS length to 1 for i in range(n): for j in range(i): if arr[j] < arr[i]: dp[i] = max(dp[i], dp[j] + 1) return max(dp)
simplelr_Code_Contests
[ { "content": "Question:\nGiven an integer array `arr`, construct a function `longest_increasing_subsequence` that finds the length of the longest increasing subsequence in the array.\n\nA subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the ord...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9621, "level": 1, "question": "Given an integer array `arr`, construct a function `longest_increasing_subsequence` that finds the length of the longest increasing subsequence in the array.\n\nA subsequence is a sequence that can be derived from another sequence by deleting some or n...
from typing import List, Tuple def topDishes(orders: List[Tuple[str, int]], N: int) -> List[str]: # Count the frequency of each dish freq = {} for dish, _ in orders: if dish in freq: freq[dish] += 1 else: freq[dish] = 1 # Sort the dishes by frequency descend...
simplelr_Taco
[ { "content": "Question:\nJim is developing a new feature in his restaurant's order management system. He wants to track the most frequently ordered dishes over a certain period to identify the best-selling items. To achieve this, he needs a function that identifies the top N most frequent dishes from customer o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9622, "level": 1, "question": "Jim is developing a new feature in his restaurant's order management system. He wants to track the most frequently ordered dishes over a certain period to identify the best-selling items. To achieve this, he needs a function that identifies the top N m...
from typing import List def process_and_square_list(raw_data: List[str]) -> List[int]: # Remove duplicates by converting to a set unique_strings = set(raw_data) # Convert each unique string to an integer integers = [int(s) for s in unique_strings] # Sort the integers in ascending order sorted_i...
simplelr_Docs
[ { "content": "Question:\n**Objective:** This task assesses your ability to manipulate and process lists using Python's data structure methods, comprehensions, and basic conditional logic.\n\n**Problem Statement:**\n\nYou are given a list of raw data elements, which are strings representing integers. Your task i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9623, "level": 1, "question": "**Objective:** This task assesses your ability to manipulate and process lists using Python's data structure methods, comprehensions, and basic conditional logic.\n\n**Problem Statement:**\n\nYou are given a list of raw data elements, which are strings...
def convert_temperature(temp, conversion_type): if conversion_type == "CtoF": converted_temp = (temp * 9/5) + 32 else: converted_temp = (temp - 32) * 5/9 return round(converted_temp, 2)
simplelr_Filter
[ { "content": "Question:\nI need to write a Python function that can convert a given temperature from Celsius to Fahrenheit and vice versa. The function should take two parameters: the temperature value and a string indicating the conversion type (\"CtoF\" for Celsius to Fahrenheit and \"FtoC\" for Fahrenheit to...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9624, "level": 1, "question": "I need to write a Python function that can convert a given temperature from Celsius to Fahrenheit and vice versa. The function should take two parameters: the temperature value and a string indicating the conversion type (\"CtoF\" for Celsius to Fahren...
def max_number_after_merging(n, arr): return sum(arr)
simplelr_Code_Contests
[ { "content": "Question:\nIn a faraway kingdom, there lived a peculiar creature known as the \"Number Phoenix\". This creature has a list of n distinct integers and enjoys playing a game. The Number Phoenix can choose two integers from the list, erase them, and replace them with their sum. The game continues unt...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9625, "level": 1, "question": "In a faraway kingdom, there lived a peculiar creature known as the \"Number Phoenix\". This creature has a list of n distinct integers and enjoys playing a game. The Number Phoenix can choose two integers from the list, erase them, and replace them wit...
def factorial(n, memo={}): if n in memo: return memo[n] if n == 0: memo[n] = 1 return 1 result = n * factorial(n - 1, memo) memo[n] = result return result # Example usage: print(factorial(4)) # Output: 24
simplelr_Filter
[ { "content": "Question:\nHere is the base case for a recursive function:\n```\ndef factorial(n, memo={}):\n if n == 0:\n return 1\n ...\n```\nUsing the technique of memoization, implement the recursive function to calculate the factorial of `n`. \n\nAlso, provide an example where you calculate the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9626, "level": 1, "question": "Here is the base case for a recursive function:\n```\ndef factorial(n, memo={}):\n if n == 0:\n return 1\n ...\n```\nUsing the technique of memoization, implement the recursive function to calculate the factorial of `n`. \n\nAlso, provide ...
def get_factorial(n: int) -> int: result = 1 for i in range(1, n + 1): result *= i return result
simplelr_Package
[ { "content": "Question:\nIn this problem, you are required to write a function named `get_factorial` that computes the factorial of a given non-negative integer. The factorial of a number `n` is the product of all positive integers less than or equal to `n`. It is denoted by `n!`.\n\nThe factorial of `0` is def...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9627, "level": 1, "question": "In this problem, you are required to write a function named `get_factorial` that computes the factorial of a given non-negative integer. The factorial of a number `n` is the product of all positive integers less than or equal to `n`. It is denoted by `...
def longest_good_substring(s): balance_map = {0: -1} current_balance = 0 max_len = 0 for i, char in enumerate(s): if char == 'a': current_balance += 1 else: current_balance -= 1 if current_balance in balance_map: length = i - balance_map[curren...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` containing only characters 'a' and 'b', a **good substring** is defined as a substring that contains an equal number of 'a's and 'b's. Write a function to return _the length of the longest good substring in_ `s`. If no such substring exists, return `0`.\nAnswer:\nLet'...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9628, "level": 1, "question": "Given a string `s` containing only characters 'a' and 'b', a **good substring** is defined as a substring that contains an equal number of 'a's and 'b's. Write a function to return _the length of the longest good substring in_ `s`. If no such substring...
def numTrees(n): if n == 0: return 1 dp = [0] * (n + 1) dp[0] = 1 # Base case: empty tree for i in range(1, n + 1): for j in range(1, i + 1): dp[i] += dp[j-1] * dp[i-j] return dp[n]
simplelr_Apps
[ { "content": "Question:\nGiven an integer `n`, define a function to return the number of unique binary search trees (BST) that can be created using all the integers from `1` to `n` (inclusive).\n\nExample: For `n = 3` the result should be `5`.\n\n0 <= n <= 19\n\nYou may assume the creation of BSTs does not depe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9629, "level": 1, "question": "Given an integer `n`, define a function to return the number of unique binary search trees (BST) that can be created using all the integers from `1` to `n` (inclusive).\n\nExample: For `n = 3` the result should be `5`.\n\n0 <= n <= 19\n\nYou may assume...
def process_numbers(numbers): return [num * 2 if num > 0 else num for num in numbers]
simplelr_Taco
[ { "content": "Question:\n# Task\nWrite a function that takes in a list of integers and returns a new list where each integer from the input list is doubled, but only if the integer is positive. If the integer is negative or zero, it should be left unchanged.\n\n# Input/Output\n\n`[input]` list of integers `numb...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9630, "level": 1, "question": "# Task\nWrite a function that takes in a list of integers and returns a new list where each integer from the input list is doubled, but only if the integer is positive. If the integer is negative or zero, it should be left unchanged.\n\n# Input/Output\...
import bisect def kth_smallest(mat, k): if not mat: return None # assuming k is valid for non-empty matrix rows = len(mat) cols = len(mat[0]) if rows > 0 else 0 low = mat[0][0] high = mat[-1][-1] while low < high: mid = (low + high) // 2 count = 0 ...
simplelr_Leetcode
[ { "content": "Question:\nGiven a matrix `mat` of integers where each row is sorted in non-decreasing order, return _the **k**-th smallest element in the matrix._ \nMake sure that your algorithm runs in logarithmic time complexity.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9631, "level": 1, "question": "Given a matrix `mat` of integers where each row is sorted in non-decreasing order, return _the **k**-th smallest element in the matrix._ \nMake sure that your algorithm runs in logarithmic time complexity.", "split": "train" }
def categorize_items(items, mapping): result = {category: [] for category in mapping} for item in items: for category, cat_items in mapping.items(): if item in cat_items: result[category].append(item) return result
simplelr_Filter
[ { "content": "Question:\nGiven a list of items, write a Python function that categorizes each item into a specified category based on a provided dictionary mapping. The function should take two arguments: a list of items and a dictionary where keys are category names and values are lists of items that belong to...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9632, "level": 1, "question": "Given a list of items, write a Python function that categorizes each item into a specified category based on a provided dictionary mapping. The function should take two arguments: a list of items and a dictionary where keys are category names and value...
def find_two_sum(nums, target): num_map = {} for i, num in enumerate(nums): complement = target - num if complement in num_map: return [num_map[complement], i] num_map[num] = i return None
simplelr_Filter
[ { "content": "Question:\nThe following code snippet defines a function called 'add' that takes two arguments: a list 'nums' and a number 'target'. The function aims to find two numbers within the 'nums' list that sum up to the 'target' value. If such a pair is found, the function returns their indices. Otherwis...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9633, "level": 1, "question": "The following code snippet defines a function called 'add' that takes two arguments: a list 'nums' and a number 'target'. The function aims to find two numbers within the 'nums' list that sum up to the 'target' value. If such a pair is found, the funct...
import torch def dict_to_padded_tensor(data_dict): # Extract the values from the dictionary sequences = list(data_dict.values()) # Find the maximum sequence length max_len = max(len(seq) for seq in sequences) # Pad each sequence with zeros padded_sequences = [] for seq in sequence...
simplelr_Filter
[ { "content": "Question:\nI'm working on a machine learning project using PyTorch, and I have a dictionary with variable-length lists of values. I need to convert this dictionary into a batch tensor for my model. However, because the lists are of different lengths, I'm encountering an issue when trying to stack ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9634, "level": 1, "question": "I'm working on a machine learning project using PyTorch, and I have a dictionary with variable-length lists of values. I need to convert this dictionary into a batch tensor for my model. However, because the lists are of different lengths, I'm encounte...
def sumOfPrimes(n): if n < 2: return 0 is_prime = [True] * (n + 1) is_prime[0], is_prime[1] = False, False for p in range(2, int(n ** 0.5) + 1): if is_prime[p]: for multiple in range(p * p, n + 1, p): is_prime[multiple] = False total = 0 for i in range...
simplelr_Taco
[ { "content": "Question:\nYou are given a number $n$. You have to find the sum of all prime numbers less than or equal to $n$ and return that sum. A prime number is a natural number greater than 1 that has no divisors other than 1 and itself.\n\nFunction Description\n\nComplete the `sumOfPrimes` function in the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9635, "level": 1, "question": "You are given a number $n$. You have to find the sum of all prime numbers less than or equal to $n$ and return that sum. A prime number is a natural number greater than 1 that has no divisors other than 1 and itself.\n\nFunction Description\n\nComplete...
import re from collections import Counter def most_frequent_words(filename): """ Reads a file and returns a list of the most frequent words. Args: filename: The name of the file to read. Returns: A list of tuples, where each tuple contains a word and its frequency. The list is...
simplelr_Filter
[ { "content": "Question:\nHere is a problem:\nWe want to make a program that reads a list of words from a file and then outputs the words that appear most frequently.\nHere is a Python code:\n\n```python\nfrom collections import Counter\n\ndef most_frequent_words(filename):\n \"\"\"\n Reads a file and returns ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9636, "level": 1, "question": "Here is a problem:\nWe want to make a program that reads a list of words from a file and then outputs the words that appear most frequently.\nHere is a Python code:\n\n```python\nfrom collections import Counter\n\ndef most_frequent_words(filename):\n ...
def filter_student_records(students, key, values): filtered_records = [] for student in students: if key in student and student[key] in values: filtered_records.append(student) return filtered_records
simplelr_Filter
[ { "content": "Question:\nDesign a Python function to filter and return a list of dictionaries where each dictionary represents a student record. The function should filter these records based on a given key and a list of values. The function should return only those records where the value associated with the g...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9637, "level": 1, "question": "Design a Python function to filter and return a list of dictionaries where each dictionary represents a student record. The function should filter these records based on a given key and a list of values. The function should return only those records wh...
def calculate_card_probability(drawn_str, specific_card): drawn = drawn_str.split(',') if drawn_str else [] if specific_card in drawn: return 0 remaining = 52 - len(drawn) return 1 / remaining if remaining > 0 else 0
simplelr_Filter
[ { "content": "Question:\nGiven a string of comma-separated values representing a sequence of card draws from a standard 52-card deck (where a card is represented in the format `[rank][suit]`, e.g., `As` for Ace of Spades, `Tc` for Ten of Clubs), implement a Python function that calculates the probability of dra...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9638, "level": 1, "question": "Given a string of comma-separated values representing a sequence of card draws from a standard 52-card deck (where a card is represented in the format `[rank][suit]`, e.g., `As` for Ace of Spades, `Tc` for Ten of Clubs), implement a Python function tha...
def is_palindrome(s): # Remove non-alphanumeric characters and convert to lowercase cleaned = ''.join([c.lower() for c in s if c.isalnum()]) # Check if the cleaned string is a palindrome return cleaned == cleaned[::-1]
simplelr_Filter
[ { "content": "Question:\nGiven any string, write a Python function that determines if that string is a palindrome. A palindrome string is defined as a string that remains the same when its characters are reversed. Your function should ignore case sensitivity, whitespace, punctuation, and only consider alphanume...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9639, "level": 1, "question": "Given any string, write a Python function that determines if that string is a palindrome. A palindrome string is defined as a string that remains the same when its characters are reversed. Your function should ignore case sensitivity, whitespace, punct...
def fibonacci(n): """Returns the nth Fibonacci number.""" if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2)
simplelr_Apps
[ { "content": "Question:\nImplement a function that takes an integer n and returns the nth term of the Fibonacci sequence. The Fibonacci sequence is defined as follows: \n\n- F(0) = 0\n- F(1) = 1\n- F(n) = F(n-1) + F(n-2) for n > 1\n\nYou are not allowed to use a loop; the function must be recursive.\n\n```pytho...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9640, "level": 1, "question": "Implement a function that takes an integer n and returns the nth term of the Fibonacci sequence. The Fibonacci sequence is defined as follows: \n\n- F(0) = 0\n- F(1) = 1\n- F(n) = F(n-1) + F(n-2) for n > 1\n\nYou are not allowed to use a loop; the func...
def reverse_string(s): result = "" for i in range(len(s)-1, -1, -1): result += s[i] return result print(reverse_string("hello")) # Output: 'olleh'
simplelr_Evol
[ { "content": "Question:\nCorrect the following code to reverse a string.\n\ndef reverse_string(s):\n result = \"\"\n for i in range(len(s), 0):\n result += s[i]\n return result\n\nprint(reverse_string(\"hello\"))\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9641, "level": 1, "question": "Correct the following code to reverse a string.\n\ndef reverse_string(s):\n result = \"\"\n for i in range(len(s), 0):\n result += s[i]\n return result\n\nprint(reverse_string(\"hello\"))", "split": "train" }
import pandas as pd def manipulate_dataframe(df): # Create a copy of the subset to avoid modifying the original DataFrame subset = df[['A', 'B']].copy() # Modify the first element of column 'A' in the subset subset.loc[0, 'A'] = 100 # Return the modified subset and the original DataFrame return...
simplelr_Docs
[ { "content": "Question:\n### Pandas Copy-on-Write Challenge\n\n#### Objective:\nYou are tasked with manipulating a DataFrame using pandas. The challenge specifically emphasizes the nuances introduced by the Copy-on-Write (CoW) behavior. Thorough understanding of CoW will be critical for accomplishing the task c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9642, "level": 1, "question": "### Pandas Copy-on-Write Challenge\n\n#### Objective:\nYou are tasked with manipulating a DataFrame using pandas. The challenge specifically emphasizes the nuances introduced by the Copy-on-Write (CoW) behavior. Thorough understanding of CoW will be cr...
def merge_intervals(intervals): if not intervals: return [] # Sort intervals based on the start time intervals.sort(key=lambda x: x[0]) merged = [intervals[0]] for current in intervals[1:]: last = merged[-1] if current[0] <= last[1]: # Merge the intervals ...
simplelr_Leetcode
[ { "content": "Question:\nGiven a list of intervals, where each interval is a pair of integers `[start, end]` representing the start and end times of a meeting, merge all overlapping intervals and return the list of merged intervals in sorted order. Ensure that the merged intervals are sorted by their start time...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9643, "level": 1, "question": "Given a list of intervals, where each interval is a pair of integers `[start, end]` representing the start and end times of a meeting, merge all overlapping intervals and return the list of merged intervals in sorted order. Ensure that the merged inter...
import os def rename_files_in_directory(directory, prefix, extension): """ Renames all files with the specified extension in the given directory by adding a prefix. Args: directory (str): The path to the directory containing the files to rename. prefix (str): The prefix to add to the b...
simplelr_Filter
[ { "content": "Question:\nCan you help me with a Python script that renames files in a directory by adding a prefix to their original names? For example, if I have a file named `test.txt` and I want to add the prefix `archive_` to it, the new file name should be `archive_test.txt`. The script should be able to h...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9644, "level": 1, "question": "Can you help me with a Python script that renames files in a directory by adding a prefix to their original names? For example, if I have a file named `test.txt` and I want to add the prefix `archive_` to it, the new file name should be `archive_test.t...
from typing import List def house_robber(houses: List[int]) -> int: if not houses: return 0 a, b = 0, houses[0] for house in houses[1:]: a, b = b, max(b, a + house) return b
simplelr_Data_Structure
[ { "content": "Question:\n### Robber's Dilemma: Maximum Loot Calculation\n\nYou are aiding a professional burglar who plans to rob houses along a street. Each house has a certain amount of money stashed. However, stealing from any two consecutive houses will trigger an alarm that contacts the police.\n\nGiven a ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9645, "level": 1, "question": "### Robber's Dilemma: Maximum Loot Calculation\n\nYou are aiding a professional burglar who plans to rob houses along a street. Each house has a certain amount of money stashed. However, stealing from any two consecutive houses will trigger an alarm th...
import bisect def find_longest_divisible_subsequence(nums): if not nums: return 0 # Sort the array and count the frequency of each number nums.sort() counts = {} for num in nums: counts[num] = counts.get(num, 0) + 1 # Extract the sorted unique numbers unique_nums =...
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `nums`, write a function that finds the longest subsequence such that each element in the subsequence is divisible by the previous one. Return the length of this subsequence. Efficiency is key, so consider optimizing your solution to handle large input sizes effec...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9646, "level": 1, "question": "Given an integer array `nums`, write a function that finds the longest subsequence such that each element in the subsequence is divisible by the previous one. Return the length of this subsequence. Efficiency is key, so consider optimizing your solutio...
def longest_ones(nums, k): left = 0 zeros = 0 max_count = 0 for right in range(len(nums)): if nums[right] == 0: zeros += 1 # Shrink the window until we have at most k zeros while zeros > k: if nums[left] == 0: zeros -= 1 left +=...
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `nums` and an integer `k`, return the maximum number of consecutive `1`s in the array if you can flip at most `k` `0`s.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9647, "level": 1, "question": "Given an integer array `nums` and an integer `k`, return the maximum number of consecutive `1`s in the array if you can flip at most `k` `0`s.", "split": "train" }
def count_frequencies(lst): freq = {} for element in lst: if isinstance(element, str): key = element.lower() else: key = element if key in freq: freq[key] += 1 else: freq[key] = 1 return freq
simplelr_Apps
[ { "content": "Question:\nWrite a function that takes a list of integers and returns a dictionary with the frequency count of all elements in the list. The function should ignore case for any string elements and count them as a single entity, regardless of their letter casing.\n\nThe challenge is to implement th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9648, "level": 1, "question": "Write a function that takes a list of integers and returns a dictionary with the frequency count of all elements in the list. The function should ignore case for any string elements and count them as a single entity, regardless of their letter casing.\...
import re def is_valid_identifier(identifier): keywords = [ "if", "else", "while", "for", "return", "break", "continue", "def", "class", "try", "except", "import", "from", "as", "with" ] # Check if the identifier is in the list of reserved keywords if identifier in keywords: ...
simplelr_Taco
[ { "content": "Question:\nCreate a function `is_valid_identifier` which takes a string and returns a boolean indicating whether the string is a valid identifier in a programming language. A valid identifier adheres to the following rules:\n\n1. The identifier must start with a letter (a-z, A-Z) or an underscore ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9649, "level": 1, "question": "Create a function `is_valid_identifier` which takes a string and returns a boolean indicating whether the string is a valid identifier in a programming language. A valid identifier adheres to the following rules:\n\n1. The identifier must start with a ...
def spiralOrder(arr): if not arr or not arr[0]: return [] result = [] top = 0 bottom = len(arr) - 1 left = 0 right = len(arr[0]) - 1 while top <= bottom and left <= right: # Traverse top row from left to right for j in range(left, right + 1): res...
simplelr_Filter
[ { "content": "Question:\nFor a 2D array, `arr`, write a function called `spiralOrder` which takes the 2D array as input and returns a list containing all elements of the arr in spiral order.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9650, "level": 1, "question": "For a 2D array, `arr`, write a function called `spiralOrder` which takes the 2D array as input and returns a list containing all elements of the arr in spiral order.", "split": "train" }
from typing import List, Tuple def find_pair_with_sum(nums: List[int], target: int) -> Tuple[int, int]: seen = {} for i, num in enumerate(nums): complement = target - num if complement in seen: return (seen[complement], i) seen[num] = i return None
simplelr_Data_Structure
[ { "content": "Question:\nYou are given an array of integers and a target integer. Write a function called `find_pair_with_sum` that finds indices of the two numbers in the array such that they add up to the target integer. Ensure your function handles edge cases and performs optimally.\n\n### Function Signature...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9651, "level": 1, "question": "You are given an array of integers and a target integer. Write a function called `find_pair_with_sum` that finds indices of the two numbers in the array such that they add up to the target integer. Ensure your function handles edge cases and performs o...
def move_zeros(array: list) -> list: non_zeros = [] zeros = [] for element in array: if (isinstance(element, int) or isinstance(element, float)) and element == 0 and not isinstance(element, bool): zeros.append(element) else: non_zeros.append(element) return non_ze...
simplelr_Data_Structure
[ { "content": "Question:\n### Moving Zeros in an Array\n\nYou are tasked with implementing a function that takes a list and moves all zeros to the end, while preserving the order of the other elements.\n\n#### Function Signature:\n```python\ndef move_zeros(array: list) -> list:\n```\n\n### Input:\n* `array`: A l...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9652, "level": 1, "question": "### Moving Zeros in an Array\n\nYou are tasked with implementing a function that takes a list and moves all zeros to the end, while preserving the order of the other elements.\n\n#### Function Signature:\n```python\ndef move_zeros(array: list) -> list:...
def is_unique(s): return len(s) == len(set(s))
simplelr_Filter
[ { "content": "Question:\nWrite a code snippet in Python that checks whether a given string contains only unique characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9653, "level": 1, "question": "Write a code snippet in Python that checks whether a given string contains only unique characters.", "split": "train" }
def sum_of_squares(s): return sum(int(x)**2 for x in s.split())
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a string of space-separated integers as input and returns the sum of the squares of those integers. The input string will contain at least one integer, and all integers will be non-negative.\n\nFor example, if the input string is `\"1 2 3\"`, the function sho...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9654, "level": 1, "question": "Write a function that takes a string of space-separated integers as input and returns the sum of the squares of those integers. The input string will contain at least one integer, and all integers will be non-negative.\n\nFor example, if the input stri...
def maximum_product_of_three(nums): nums.sort() n = len(nums) candidate1 = nums[n-1] * nums[n-2] * nums[n-3] candidate2 = nums[0] * nums[1] * nums[n-1] return max(candidate1, candidate2)
simplelr_Evol
[ { "content": "Question:\nWrite a function to find the maximum product of three numbers in an array of integers. The function should return this maximum product. Assume the array contains at least three numbers. \n\nExample:\nInput: [1, 10, 2, 6, 5, 3]\nOutput: 300\n\nThe input array may contain both positive an...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9655, "level": 1, "question": "Write a function to find the maximum product of three numbers in an array of integers. The function should return this maximum product. Assume the array contains at least three numbers. \n\nExample:\nInput: [1, 10, 2, 6, 5, 3]\nOutput: 300\n\nThe input...
def find_max_consecutive_ones(nums): s = ''.join(map(str, nums)) groups = s.split('0') return max(len(g) for g in groups)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the maximum number of consecutive 1's in a binary array. You can use the built-in functions like count, max, etc., but try not to use any sort functions or algorithms to solve this problem.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9656, "level": 1, "question": "Write a python function to find the maximum number of consecutive 1's in a binary array. You can use the built-in functions like count, max, etc., but try not to use any sort functions or algorithms to solve this problem.", "split": "train" }
def find_most_popular_books(ratings, tags): # Create a dictionary to map book IDs to their ratings book_ratings = {book: rating for book, rating in ratings} # Dictionary to track the highest rated book for each tag tag_max = {} for book, tag in tags: current_rating = book_ratings[b...
simplelr_Code_Contests
[ { "content": "Question:\nYou are managing an online bookstore, which needs a system to categorize books based on their popularity. Each book in the bookstore can be rated by readers and has multiple tags associated with it. To determine a book's popularity, you are given two pieces of information:\n\n1. A list ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9657, "level": 1, "question": "You are managing an online bookstore, which needs a system to categorize books based on their popularity. Each book in the bookstore can be rated by readers and has multiple tags associated with it. To determine a book's popularity, you are given two p...
from typing import List def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]: if not matrix: return [] n = len(matrix) m = len(matrix[0]) if n > 0 else 0 transposed = [] for col in range(m): new_row = [] for row in range(n): new_row.append(m...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\n**Matrix Transpose Optimization**\n\nYou are required to implement a function that efficiently computes the transpose of a given matrix. The transpose of a matrix is obtained by flipping it over its diagonal, switching the row and column indices of the matrix.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9658, "level": 1, "question": "### Problem Statement\n\n**Matrix Transpose Optimization**\n\nYou are required to implement a function that efficiently computes the transpose of a given matrix. The transpose of a matrix is obtained by flipping it over its diagonal, switching the row ...
import time def sleep_ms(milliseconds): """ Sleep for the specified number of milliseconds. Args: milliseconds (int): The duration to sleep in milliseconds. """ time.sleep(milliseconds / 1000)
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that simulates the behavior of the `os.sleep()` function but with milliseconds precision, as `os.sleep()` only supports seconds?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9659, "level": 1, "question": "How can I create a Python function that simulates the behavior of the `os.sleep()` function but with milliseconds precision, as `os.sleep()` only supports seconds?", "split": "train" }
def printInvertedTriangle(n): for i in range(n, 0, -1): print('*' * i)
simplelr_Taco
[ { "content": "Question:\nGiven an integer n, write a function that prints an inverted right-angled triangle pattern of asterisks. The triangle should have n rows, with the first row containing n asterisks, the second row containing n-1 asterisks, and so on, until the last row which contains 1 asterisk. \n\nExam...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9660, "level": 1, "question": "Given an integer n, write a function that prints an inverted right-angled triangle pattern of asterisks. The triangle should have n rows, with the first row containing n asterisks, the second row containing n-1 asterisks, and so on, until the last row ...
def get_diagonal_elements(matrix_dict): diagonal = {} for key in matrix_dict: row_str, col_str = key.split(',') row = int(row_str) col = int(col_str) if row == col: diagonal[key] = matrix_dict[key] return diagonal
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes an input dictionary and returns a new dictionary with all the diagonal elements of a square matrix represented by the input dictionary. The keys in the dictionary represent the positions of the elements in the matrix, formatted as 'row,col' where row a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9661, "level": 1, "question": "Write a Python function that takes an input dictionary and returns a new dictionary with all the diagonal elements of a square matrix represented by the input dictionary. The keys in the dictionary represent the positions of the elements in the matrix,...
def remove_adjacent_pairs(s): stack = [] for char in s: if stack and stack[-1] == char: stack.pop() else: stack.append(char) return ''.join(stack)
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` consisting of lowercase English letters. You can apply the following operation any number of times: \n\n* Choose any two adjacent characters in the string, and if they are equal, remove both of them from the string. \n\nYour task is to determine the final stri...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9662, "level": 1, "question": "You are given a string `s` consisting of lowercase English letters. You can apply the following operation any number of times: \n\n* Choose any two adjacent characters in the string, and if they are equal, remove both of them from the string. \n\nYour ...
def next_bigger(num: int) -> int: digits = list(str(num)) # Find the pivot point i = len(digits) - 2 while i >= 0 and digits[i] >= digits[i + 1]: i -= 1 if i == -1: return -1 # Find the successor j = len(digits) - 1 while digits[j] <= digits[i]: j -= 1 # Swap ...
simplelr_Data_Structure
[ { "content": "Question:\nYou are given a positive integer represented by `num`. Your task is to write a function `next_bigger(num)` that returns the next higher number using the exact same set of digits as the given integer. If no such number exists, return -1.\n\n### Input Format\n\n* A positive integer `num` ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9663, "level": 1, "question": "You are given a positive integer represented by `num`. Your task is to write a function `next_bigger(num)` that returns the next higher number using the exact same set of digits as the given integer. If no such number exists, return -1.\n\n### Input Fo...
def sum_of_integers(numbers): total = 0 index = 0 while index < len(numbers): total += numbers[index] index += 1 return total
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of integers and returns the sum of all the integers in the list. Use the `while` loop to implement the function.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9664, "level": 1, "question": "Write a Python function that takes a list of integers and returns the sum of all the integers in the list. Use the `while` loop to implement the function.", "split": "train" }
def can_form_palindrome(s: str) -> bool: counts = {} for c in s: if c.isalnum(): c_lower = c.lower() counts[c_lower] = counts.get(c_lower, 0) + 1 odd_counts = 0 for v in counts.values(): if v % 2 != 0: odd_counts += 1 if odd_counts > 1: ...
simplelr_Package
[ { "content": "Question:\nIn competitive programming, string manipulation problems are quite common. One such problem is to determine whether a given string can be rearranged to form a palindrome. A palindrome is a word, phrase, or sequence that reads the same backward as forward. For this problem, consider only...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9665, "level": 1, "question": "In competitive programming, string manipulation problems are quite common. One such problem is to determine whether a given string can be rearranged to form a palindrome. A palindrome is a word, phrase, or sequence that reads the same backward as forwa...
from collections import Counter def are_anagrams(str1, str2): # Remove whitespace and convert to lowercase s1 = str1.replace(" ", "").lower() s2 = str2.replace(" ", "").lower() # Check if lengths are different if len(s1) != len(s2): print(len(s1)) return False # Count ...
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that takes two input strings and determines if they are anagrams by checking if they contain the exact same characters with the same frequency, ignoring case and whitespace. If the strings are anagrams, return True; otherwise, return False. The function should a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9666, "level": 1, "question": "Create a Python function that takes two input strings and determines if they are anagrams by checking if they contain the exact same characters with the same frequency, ignoring case and whitespace. If the strings are anagrams, return True; otherwise, ...
def find_min_prime(): return 2
simplelr_Filter
[ { "content": "Question:\nWrite a Python function `find_min_prime()` that returns the smallest prime number. Prime numbers are natural numbers greater than 1 that have no positive divisors other than 1 and themselves. The smallest prime number is 2. Your function should be efficient and return the result directl...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9667, "level": 1, "question": "Write a Python function `find_min_prime()` that returns the smallest prime number. Prime numbers are natural numbers greater than 1 that have no positive divisors other than 1 and themselves. The smallest prime number is 2. Your function should be effi...
def is_sum_of_consecutive_integers(n: int) -> bool: return (n & (n - 1)) != 0
simplelr_Evol
[ { "content": "Question:\nYou have been given an integer value `n`. Your task is to write a function that determines whether the integer can be represented as the sum of two or more consecutive positive integers.\n\nFor example, the number `15` can be expressed as:\n- 1 + 2 + 3 + 4 + 5\n- 4 + 5 + 6\n- 7 + 8\n\nO...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9668, "level": 1, "question": "You have been given an integer value `n`. Your task is to write a function that determines whether the integer can be represented as the sum of two or more consecutive positive integers.\n\nFor example, the number `15` can be expressed as:\n- 1 + 2 + 3...
def scalar_product(a, b): return sum(x * y for x, y in zip(a, b))
simplelr_Taco
[ { "content": "Question:\nWrite a function to calculate the scalar or dot product of two vectors. The function should:\n\n+ Accept two arrays of integers as parameters, representing the vectors.\n+ Return the scalar product of the two arrays.\n\n**Note:** The two vectors will always have the same length.\n\n## E...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9669, "level": 1, "question": "Write a function to calculate the scalar or dot product of two vectors. The function should:\n\n+ Accept two arrays of integers as parameters, representing the vectors.\n+ Return the scalar product of the two arrays.\n\n**Note:** The two vectors will a...
def longest_unique_substring(s): last_occurrence = {} left = 0 max_len = 0 start = 0 for right in range(len(s)): char = s[right] if char in last_occurrence and last_occurrence[char] >= left: left = last_occurrence[char] + 1 last_occurrence[char] = right cu...
simplelr_Code_Contests
[ { "content": "Question:\nYou are given a string containing only lowercase alphabets. Your task is to find the longest substring without repeating characters. The substring must be a contiguous block of characters within the string.\n\nWrite a function `longest_unique_substring` that takes a single string as inp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9670, "level": 1, "question": "You are given a string containing only lowercase alphabets. Your task is to find the longest substring without repeating characters. The substring must be a contiguous block of characters within the string.\n\nWrite a function `longest_unique_substring...
def get_value_from_path(obj, path): if not path: return None # or return obj if the empty path is considered to return the whole object keys = path.split('.') current = obj for key in keys: if isinstance(current, dict) and key in current: current = current[key] ...
simplelr_Filter
[ { "content": "Question:\nI have an object where values are key-value pair that can be nested to any depth. \n\nFor example:\n```\n{\r\n \"key1\": \"value\",\r\n \"key2\": {\r\n \"key21\": \"value1\",\r\n \"key22\": {\r\n \"key221\": \"value2\",\r\n \"key222\": \"value3\"\r\n }\r\n },\r\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9671, "level": 1, "question": "I have an object where values are key-value pair that can be nested to any depth. \n\nFor example:\n```\n{\r\n \"key1\": \"value\",\r\n \"key2\": {\r\n \"key21\": \"value1\",\r\n \"key22\": {\r\n \"key221\": \"value2\",\r\n \"key222\"...
from typing import List def search_matrix(matrix: List[List[int]], target: int) -> bool: if not matrix or not matrix[0]: return False rows = len(matrix) cols = len(matrix[0]) if rows > 0 else 0 low, high = 0, rows - 1 while low <= high: mid = (low + high) // 2 ...
simplelr_Apps
[ { "content": "Question:\nYou are given a matrix of integers, where each row is sorted in ascending order and the first integer of each row is greater than the last integer of the previous row. This creates a \"flattened\" representation of a sorted list, arranged into a 2D matrix.\n\nYou need to write a functio...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9672, "level": 1, "question": "You are given a matrix of integers, where each row is sorted in ascending order and the first integer of each row is greater than the last integer of the previous row. This creates a \"flattened\" representation of a sorted list, arranged into a 2D mat...
def width_of_binary_tree(arr): max_width = 0 k = 0 n = len(arr) while True: start = 2 ** k - 1 if start >= n: break end = 2 ** (k + 1) - 2 if end >= n: end = n - 1 level = arr[start:end+1] # Find first non-null ...
simplelr_Leetcode
[ { "content": "Question:\nGiven a list of integers `arr` representing a binary tree in level-order traversal, return _the **maximum** width of the binary tree_. The **width** of a binary tree is the maximum width among all levels. The width of one level is defined as the number of nodes between the leftmost and ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9673, "level": 1, "question": "Given a list of integers `arr` representing a binary tree in level-order traversal, return _the **maximum** width of the binary tree_. The **width** of a binary tree is the maximum width among all levels. The width of one level is defined as the number...
from typing import List def ternary_search_range(arr: List[int], left: int, right: int, key: int) -> int: low = left high = right while low <= high: mid1 = low + (high - low) // 3 mid2 = high - (high - low) // 3 if arr[mid1] == key: return mid1 if a...
simplelr_Data_Structure
[ { "content": "Question:\n### Ternary Search Extension with Range Queries\n\n#### Problem Statement\nYou are given a sorted array of distinct integers. A ternary search function has been implemented to find the index of a given value in this array. Your task is to extend this functionality to also support range ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9674, "level": 1, "question": "### Ternary Search Extension with Range Queries\n\n#### Problem Statement\nYou are given a sorted array of distinct integers. A ternary search function has been implemented to find the index of a given value in this array. Your task is to extend this f...
import torch def tensor_operations(): # 1. Tensor Initialization A = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float64) # 2. Mathematical Operations B = A.pow(2) C = A + B # 3. Automatic Differentiation D = C.clone().detach().requires_grad_(True) total_sum = D.sum() ...
simplelr_Docs
[ { "content": "Question:\n#### Objective\nTo assess your understanding of PyTorch tensors, you will create a tensor, perform various operations on it, and demonstrate the use of automatic differentiation.\n\n#### Problem Statement\nImplement a function `tensor_operations` that performs the following tasks:\n\n1....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9675, "level": 1, "question": "#### Objective\nTo assess your understanding of PyTorch tensors, you will create a tensor, perform various operations on it, and demonstrate the use of automatic differentiation.\n\n#### Problem Statement\nImplement a function `tensor_operations` that ...
def max_overlapping_intervals(intervals): events = [] for s, e in intervals: events.append((s, 0)) # 0 represents the start of an interval events.append((e, 1)) # 1 represents the end of an interval # Sort the events by time, and for the same time, starts come before ends events.sort(k...
simplelr_Filter
[ { "content": "Question:\nCreate a function in Python to find the maximum number of overlapping intervals. The input will be a list of intervals, where each interval is represented as a tuple of two integers: the start and end points. The function should return the maximum number of overlapping intervals at any ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9676, "level": 1, "question": "Create a function in Python to find the maximum number of overlapping intervals. The input will be a list of intervals, where each interval is represented as a tuple of two integers: the start and end points. The function should return the maximum numb...
from typing import List def sum_of_distinct_elements(matrix: List[List[int]]) -> List[int]: result = [] for row in matrix: unique_elements = set(row) result.append(sum(unique_elements)) return result
simplelr_Algorithm
[ { "content": "Question:\n### Sum of Distinct Elements in Matrix Rows\n\n**Context:** In a matrix of integers, each row contains elements that can have duplicates. Your task is to compute the sum of distinct elements for each row and return these sums.\n\n### Task:\nWrite a function, `sum_of_distinct_elements`, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9677, "level": 1, "question": "### Sum of Distinct Elements in Matrix Rows\n\n**Context:** In a matrix of integers, each row contains elements that can have duplicates. Your task is to compute the sum of distinct elements for each row and return these sums.\n\n### Task:\nWrite a fun...
def min_cost_to_make_equal(nums): nums.sort() n = len(nums) median = nums[n // 2] return sum(abs(num - median) for num in nums)
simplelr_Leetcode
[ { "content": "Question:\nYou are given a **0-indexed** integer array `nums`. You are allowed to perform the following operation any number of times: Choose an element `nums[i]` and set `nums[i]` to `nums[i] + 1` or `nums[i] - 1`. The cost of each operation is `1`. Find the **minimum** cost to make all elements ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9678, "level": 1, "question": "You are given a **0-indexed** integer array `nums`. You are allowed to perform the following operation any number of times: Choose an element `nums[i]` and set `nums[i]` to `nums[i] + 1` or `nums[i] - 1`. The cost of each operation is `1`. Find the **m...
from typing import List def simon_says(commands: List[str]) -> List[str]: result = [] prefix = 'Simon says ' for cmd in commands: if cmd.startswith(prefix): result.append(cmd[len(prefix):]) else: result.append('') return result
simplelr_Code_Contests
[ { "content": "Question:\nSimon Says is a famous game where a leader, Simon, gives a command and the players have to follow the command only if it starts with \"Simon says\".\n\nIn this problem, you are given a list of commands and you need to determine which commands should be followed.\n\nWrite a function `sim...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9679, "level": 1, "question": "Simon Says is a famous game where a leader, Simon, gives a command and the players have to follow the command only if it starts with \"Simon says\".\n\nIn this problem, you are given a list of commands and you need to determine which commands should be...
from itertools import combinations from typing import List, Set, Tuple def k_subsets(nums: List[int], k: int) -> Set[Tuple[int]]: if k == 0: return {()} return set(combinations(nums, k))
simplelr_Data_Structure
[ { "content": "Question:\nYou are given a set of distinct integers, `nums`, and you need to return all possible k-sized subsets. In mathematics, this is also known as the k-combinations or k-element subsets of a set.\n\n### Objective:\n\nImplement a function `k_subsets(nums: List[int], k: int) -> Set[Tuple[int]]...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9680, "level": 1, "question": "You are given a set of distinct integers, `nums`, and you need to return all possible k-sized subsets. In mathematics, this is also known as the k-combinations or k-element subsets of a set.\n\n### Objective:\n\nImplement a function `k_subsets(nums: Li...
import collections def can_form_palindrome(s): counts = collections.Counter(s) odd_counts = 0 for count in counts.values(): if count % 2 != 0: odd_counts += 1 if len(s) % 2 == 0: return odd_counts == 0 else: return odd_counts == 1
simplelr_Apps
[ { "content": "Question:\n# Summary:\nWrite a function that determines whether a given string can be rearranged to form a palindrome.\n\n# Description:\nA palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalizati...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9681, "level": 1, "question": "# Summary:\nWrite a function that determines whether a given string can be rearranged to form a palindrome.\n\n# Description:\nA palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring sp...
def binary_search(arr: list[int | float], target: int | float) -> int: if not arr: return -1 left, right = 0, len(arr) - 1 is_ascending = arr[left] < arr[right] while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid ...
simplelr_Algorithm
[ { "content": "Question:\nBinary Search on a Sorted Array\n\n#### Problem Statement\n\n#### Context\nYou are implementing a function to perform a binary search on a sorted array. Binary search is an efficient algorithm for finding an item from a sorted list of items by repeatedly dividing the search interval in ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9682, "level": 1, "question": "Binary Search on a Sorted Array\n\n#### Problem Statement\n\n#### Context\nYou are implementing a function to perform a binary search on a sorted array. Binary search is an efficient algorithm for finding an item from a sorted list of items by repeated...
def binary_search(array, target): low = 0 high = len(array) - 1 while low <= high: mid = (low + high) // 2 if array[mid] == target: return mid elif target < array[mid]: high = mid - 1 else: low = mid + 1 return -1
simplelr_Prefill
[ { "content": "Question:\nCreate a function that implements the binary search algorithm to find a target element in a sorted array. If the target is not found, return -1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9683, "level": 1, "question": "Create a function that implements the binary search algorithm to find a target element in a sorted array. If the target is not found, return -1.", "split": "train" }
def longest_subarray_with_sum(nums: list[int], target_sum: int) -> int: if not nums: return 0 prefix_map = {0: -1} # Store the first occurrence of each prefix sum current_sum = 0 max_length = 0 for i, num in enumerate(nums): current_sum += num required = current_su...
simplelr_Algorithm
[ { "content": "Question:\n**Longest Subarray with Given Sum**\n\nYou are given an array of integers and a target sum. Modify the existing algorithm to find the longest subarray (contiguous sequence of elements) in the array that sums up to the target sum.\n\nGiven:\n- `nums`: A list of integers.\n- `target_sum`:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9684, "level": 1, "question": "**Longest Subarray with Given Sum**\n\nYou are given an array of integers and a target sum. Modify the existing algorithm to find the longest subarray (contiguous sequence of elements) in the array that sums up to the target sum.\n\nGiven:\n- `nums`: A...
import math def nearest_lower_perfect_square_sqrt(n): if n < 0: return 0 return math.isqrt(n)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to check if the given number is a perfect square and, if it is, return its square root. If not, return the nearest lower perfect square's square root.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9685, "level": 1, "question": "Write a function to check if the given number is a perfect square and, if it is, return its square root. If not, return the nearest lower perfect square's square root.", "split": "train" }
def most_frequent(nums: list[int]) -> int: if not nums: return None counts = {} for num in nums: counts[num] = counts.get(num, 0) + 1 max_count = 0 most_freq = None for num, count in counts.items(): if count > max_count: max_count = count most_freq...
simplelr_Algorithm
[ { "content": "Question:\n### Question Style\n- Coding focus: Algorithmic implementation, handling edge cases, and optimization.\n- Clear problem statement with input, output, and constraints.\n- Example usage demonstrating expected behavior.\n\n### Question\n**Most Frequent Element Calculation**\n\nYou need to ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9686, "level": 1, "question": "### Question Style\n- Coding focus: Algorithmic implementation, handling edge cases, and optimization.\n- Clear problem statement with input, output, and constraints.\n- Example usage demonstrating expected behavior.\n\n### Question\n**Most Frequent El...
def find_kth_largest(arr, k): sorted_arr = sorted(arr, reverse=True) return sorted_arr[k-1]
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of integers `arr` and an integer `k`. Your task is to find the `k`-th largest element in the list. The `k`-th largest element is the element that would appear in the `k`-th position if the list were sorted in descending order. You must do this in `O(n log n)` time c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9687, "level": 1, "question": "You are given a list of integers `arr` and an integer `k`. Your task is to find the `k`-th largest element in the list. The `k`-th largest element is the element that would appear in the `k`-th position if the list were sorted in descending order. You ...
def min_additional_candies(nums): if not nums: return 0 res = 0 prev = nums[0] for i in range(1, len(nums)): if nums[i] < prev: res += prev - nums[i] else: prev = nums[i] return res
simplelr_Leetcode
[ { "content": "Question:\nYou are given an integer array `nums` of length `n`. Each element in `nums` represents the number of candies a child will initially receive. You need to distribute additional candies to the children such that the total number of candies each child has forms a non-decreasing sequence fro...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9688, "level": 1, "question": "You are given an integer array `nums` of length `n`. Each element in `nums` represents the number of candies a child will initially receive. You need to distribute additional candies to the children such that the total number of candies each child has ...
def reverse_string(s): s = list(s) n = len(s) for i in range(n // 2): s[i], s[n - 1 - i] = s[n - 1 - i], s[i] return ''.join(s)
simplelr_Filter
[ { "content": "Question:\nGiven a string, reverse the order of its characters without using any built-in string manipulation functions or additional data structures. The solution should have a time complexity of O(n), where n is the length of the string. Additionally, you are not allowed to create any new variab...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9689, "level": 1, "question": "Given a string, reverse the order of its characters without using any built-in string manipulation functions or additional data structures. The solution should have a time complexity of O(n), where n is the length of the string. Additionally, you are n...
def min_slicing_operations(nums): sorted_nums = sorted(nums) if nums == sorted_nums: return 0 left = 0 while left < len(nums) and nums[left] == sorted_nums[left]: left += 1 right = len(nums) - 1 while right >= 0 and nums[right] == sorted_nums[right]: right -= 1 # Extr...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of integers `nums`. We define a slicing operation that operates on a subarray of `nums` to reverse the order of the elements within that subarray. Return the minimum number of slicing operations required to make the entire array sorted in non-decreasing order. Not...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9690, "level": 1, "question": "You are given an array of integers `nums`. We define a slicing operation that operates on a subarray of `nums` to reverse the order of the elements within that subarray. Return the minimum number of slicing operations required to make the entire array ...
def count_ones_in_binary(n): count = 0 n = abs(n) while n: count += n & 1 n >>= 1 return count
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the number of 1s in the binary representation of an integer. The function should take an integer as input and return the count of 1s.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9691, "level": 1, "question": "Write a function to calculate the number of 1s in the binary representation of an integer. The function should take an integer as input and return the count of 1s.", "split": "train" }
def reverseString(S): return S[::-1]
simplelr_Taco
[ { "content": "Question:\nGiven a string S, print the characters in reverse order.\nExample 1:\nInput:\nS = \"Geeks\"\nOutput: \"skeeG\"\nExample 2:\nInput:\nS = \"Programming\"\nOutput: \"gnimmargorP\"\nYour Task:\nComplete the function reverseString() which takes a string S as input parameter and returns the r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9692, "level": 1, "question": "Given a string S, print the characters in reverse order.\nExample 1:\nInput:\nS = \"Geeks\"\nOutput: \"skeeG\"\nExample 2:\nInput:\nS = \"Programming\"\nOutput: \"gnimmargorP\"\nYour Task:\nComplete the function reverseString() which takes a string S a...
def int_to_binary(n): return bin(n)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to convert an integer to a binary string, ensuring the result has a leading '0b' prefix.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9693, "level": 1, "question": "Write a python function to convert an integer to a binary string, ensuring the result has a leading '0b' prefix.", "split": "train" }
def lexical_addition(a: str, b: str) -> str: a_rev = a[::-1] b_rev = b[::-1] max_len = max(len(a_rev), len(b_rev)) carry = 0 result = [] for i in range(max_len): digit_a = int(a_rev[i]) if i < len(a_rev) else 0 digit_b = int(b_rev[i]) if i < len(b_rev) else 0 ...
simplelr_Code_Contests
[ { "content": "Question:\nIn a kingdom far away, there lived a ruler who loved playing with numbers. He created a special game called Lexical Addition for his courtiers. In Lexical Addition, two non-negative integers are given as strings, and their sum must be computed as if adding them digit by digit, but the r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9694, "level": 1, "question": "In a kingdom far away, there lived a ruler who loved playing with numbers. He created a special game called Lexical Addition for his courtiers. In Lexical Addition, two non-negative integers are given as strings, and their sum must be computed as if ad...
from typing import List, Tuple def evaluate_or_operations(operations: List[Tuple[int, int]]) -> List[int]: return [a | b for a, b in operations]
simplelr_Algorithm
[ { "content": "Question:\n### Coding Question\n\n**Objective**: Write a function to evaluate a list of binary OR gate operations.\n\n### Problem Statement\n\nYou are given a list of tuples where each tuple contains two integers representing the inputs for a binary OR gate. You need to write a function `evaluate_...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9695, "level": 1, "question": "### Coding Question\n\n**Objective**: Write a function to evaluate a list of binary OR gate operations.\n\n### Problem Statement\n\nYou are given a list of tuples where each tuple contains two integers representing the inputs for a binary OR gate. You ...
def generate_primes(n): if n <= 1: return [] sieve = [True] * (n + 1) sieve[0] = sieve[1] = False for i in range(2, int(n ** 0.5) + 1): if sieve[i]: sieve[i*i : n+1 : i] = [False] * len(sieve[i*i : n+1 : i]) primes = [i for i in range(2, n) if sieve[i]] return primes
simplelr_Prefill
[ { "content": "Question:\nCreate a function that generates a list of prime numbers up to a given maximum value. The function should take an integer `n` as its argument, where `n` represents the maximum number to search for prime numbers. The function should return a list of all prime numbers less than `n`.\nAnsw...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9696, "level": 1, "question": "Create a function that generates a list of prime numbers up to a given maximum value. The function should take an integer `n` as its argument, where `n` represents the maximum number to search for prime numbers. The function should return a list of all...
def longest_subarray_sum_k(arr, K): current_sum = 0 sum_map = {0: -1} max_len = 0 start = 0 end = 0 for j in range(len(arr)): current_sum += arr[j] # Check if current_sum - K exists in the map if (current_sum - K) in sum_map: possible_i = sum_map[current_sum...
simplelr_Taco
[ { "content": "Question:\n#Finding the Longest Subarray with Sum K\n\nYou have to write a method, that gets two parameters:\n\n```markdown\n1. An array of integers\n2. An integer K\n```\n\n#The method should find and return the longest contiguous subarray which sums to K. If there are multiple subarrays with the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9697, "level": 1, "question": "#Finding the Longest Subarray with Sum K\n\nYou have to write a method, that gets two parameters:\n\n```markdown\n1. An array of integers\n2. An integer K\n```\n\n#The method should find and return the longest contiguous subarray which sums to K. If th...
from collections import defaultdict def binarySubarraySum(nums, k): prefix_count = defaultdict(int) prefix_count[0] = 1 # Initialize with prefix sum 0 current_sum = 0 result = 0 for num in nums: current_sum += num # Check if (current_sum - k) has been seen before result +=...
simplelr_Taco
[ { "content": "Question:\nTitle: Binary Subarray Sum\n\nGiven a binary array `nums` and an integer `k`, write a function that returns the number of non-empty subarrays that have a sum equal to `k`.\n\nA binary array is an array that contains only 0s and 1s. A subarray is a contiguous part of the array.\n\n#### E...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9698, "level": 1, "question": "Title: Binary Subarray Sum\n\nGiven a binary array `nums` and an integer `k`, write a function that returns the number of non-empty subarrays that have a sum equal to `k`.\n\nA binary array is an array that contains only 0s and 1s. A subarray is a cont...
def optimized_categorize_products(sales): return {product: "High Performing" if (sum(sale)/12) > 150 else "Low Performing" for product, sale in sales.items()}
simplelr_Evol
[ { "content": "Question:\nA company wants to categorize its products based on their sales performance over the past year. The product data is stored in a dictionary where keys represent product IDs and values are lists of 12 integers, each representing the sales numbers for every month. For example:\n\n```python...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 9699, "level": 1, "question": "A company wants to categorize its products based on their sales performance over the past year. The product data is stored in a dictionary where keys represent product IDs and values are lists of 12 integers, each representing the sales numbers for eve...