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 rotate_matrix(matrix): return [list(row[::-1]) for row in zip(*matrix)]
simplelr_Package
[ { "content": "Question:\nThis problem aims to help you understand and practice the usage of advanced Python list comprehensions, as well as manipulation of nested lists (matrices).\n\nYou are required to create a function `rotate_matrix` that rotates a given square matrix 90 degrees clockwise. Here is a detaile...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1200, "level": 1, "question": "This problem aims to help you understand and practice the usage of advanced Python list comprehensions, as well as manipulation of nested lists (matrices).\n\nYou are required to create a function `rotate_matrix` that rotates a given square matrix 90 d...
def extract_numbers(s): num_str = '' for char in s: if char.isdigit(): num_str += char return int(num_str) if num_str else 0
simplelr_Apps
[ { "content": "Question:\nYou are given a string that contains both letters and numbers. Create a function that extracts all the numbers from the string, concatenates them together, and returns the resulting number as an integer. If there are no numbers in the input string, the function should return 0.\n\nFor e...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1201, "level": 1, "question": "You are given a string that contains both letters and numbers. Create a function that extracts all the numbers from the string, concatenates them together, and returns the resulting number as an integer. If there are no numbers in the input string, the...
from collections import defaultdict def min_window_substring(s, t): if not t or not s: return "" if len(t) > len(s): return "" t_count = defaultdict(int) for char in t: t_count[char] += 1 required = len(t_count) formed = 0 s_count = defaultdict(int) ...
simplelr_Filter
[ { "content": "Question:\n### Problem\n**Minimum Window Substring**\n\nGiven two strings `s` and `t` of lengths `m` and `n` respectively, return the minimum window substring of `s` which will contain all the characters of `t` in complexity O(m + n).\n\n**Example 1:**\n\nInput: `s = \"ADOBECODEBANC\", t = \"ABC\"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1202, "level": 1, "question": "### Problem\n**Minimum Window Substring**\n\nGiven two strings `s` and `t` of lengths `m` and `n` respectively, return the minimum window substring of `s` which will contain all the characters of `t` in complexity O(m + n).\n\n**Example 1:**\n\nInput: ...
from typing import List def find_anagrams(target: str, words: List[str]) -> List[str]: # Preprocess the target: strip, lowercase, and sort the characters target_clean = target.strip().lower() target_sorted = ''.join(sorted(target_clean)) target_length = len(target_clean) result = [] for wo...
simplelr_Package
[ { "content": "Question:\nYou are required to implement a function named `find_anagrams` that identifies all anagrams of a given word within an input list of words. An anagram is defined as a word or phrase formed by rearranging the letters of another, such as `spar` formed from `rasp`.\n\nThe function should ta...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1203, "level": 1, "question": "You are required to implement a function named `find_anagrams` that identifies all anagrams of a given word within an input list of words. An anagram is defined as a word or phrase formed by rearranging the letters of another, such as `spar` formed fro...
from typing import List def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]: """ Rotates the given 2D matrix 90 degrees clockwise and returns the result. Validates the matrix to ensure all rows are of the same length and the matrix is non-empty. >>> rotate_matrix([[1, 2], [3, 4]]) [[3, 1], [4, 2]...
simplelr_Evol
[ { "content": "Question:\nDesign a function that restructures the elements of a given 2D list (matrix) by rotating the matrix 90 degrees clockwise. Additionally, include functionality to validate the matrix dimensions (i.e., it should be a non-empty list of non-empty lists and all rows must be of the same length...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1204, "level": 1, "question": "Design a function that restructures the elements of a given 2D list (matrix) by rotating the matrix 90 degrees clockwise. Additionally, include functionality to validate the matrix dimensions (i.e., it should be a non-empty list of non-empty lists and ...
def integer_square_cube(n): return (n, n ** 2, n ** 3)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an integer as an argument and returns a tuple containing the integer value, its square, and its cube.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1205, "level": 1, "question": "Create a function that takes an integer as an argument and returns a tuple containing the integer value, its square, and its cube.", "split": "train" }
from typing import List, Set, Dict def assign_category(recipes: List[Set[str]], categories: Dict[str, Set[str]]) -> List[str]: result = [] for recipe in recipes: best_category = "" max_size = -1 for category, sub_ingredients in categories.items(): if sub_ingredients.issubset...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Question\n\n**Scenario**:\n\nYou are developing a feature for a recipe application that categorizes recipes based on their ingredients. A recipe can only belong to one category and it must include all the sub-ingredients of that category to qualify. Your goal is to write a fu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1206, "level": 1, "question": "### Coding Question\n\n**Scenario**:\n\nYou are developing a feature for a recipe application that categorizes recipes based on their ingredients. A recipe can only belong to one category and it must include all the sub-ingredients of that category to ...
import random def generate_random_number(start, end): """ Generates a random integer between the specified start and end values (inclusive). Args: start (int): The lower bound of the range. end (int): The upper bound of the range. Returns: int: A randomly generated int...
simplelr_Filter
[ { "content": "Question:\nWrite a Python programs that generates a random number between 1 and 100 using the random module. Implement a function that takes the range of numbers as parameters and returns a randomly generated integer within that range. Additionally, implement error handling to prevent invalid inpu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1207, "level": 1, "question": "Write a Python programs that generates a random number between 1 and 100 using the random module. Implement a function that takes the range of numbers as parameters and returns a randomly generated integer within that range. Additionally, implement err...
import math def smallest_prime_factor(n): if n <= 1: return n if n == 2: return 2 if n % 2 == 0: return 2 max_divisor = int(math.sqrt(n)) + 1 for i in range(3, max_divisor, 2): if n % i == 0: return i return n
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to find the smallest prime factor of a given number. The function should return the smallest prime factor of the number. If the number is prime or 1, the function should return the number itself.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1208, "level": 1, "question": "Write a Python function to find the smallest prime factor of a given number. The function should return the smallest prime factor of the number. If the number is prime or 1, the function should return the number itself.", "split": "train" }
from sympy import diff # assuming we're using sympy for differentiation def differentiate(f, x): if isinstance(f, (list, tuple)): return [differentiate(func, x) for func in f] else: # Compute the derivative of a single function return diff(f, x)
simplelr_Filter
[ { "content": "Question:\nI have a method that converts functions into their derivatives using symbolic computation. However, I'm not sure about how to handle the case where the input is an array of functions. \nHere is the example of how the method should work on a single function:\n```python\ndifferentiate(f, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1209, "level": 1, "question": "I have a method that converts functions into their derivatives using symbolic computation. However, I'm not sure about how to handle the case where the input is an array of functions. \nHere is the example of how the method should work on a single func...
def calculate_mean(numbers): if not numbers: return 0 return sum(numbers) / len(numbers)
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that calculates the mean of a list of numbers?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1210, "level": 1, "question": "How can I create a Python function that calculates the mean of a list of numbers?", "split": "train" }
def count_occurrences(text: str, pattern: str) -> int: n = len(pattern) m = len(text) if n > m: return 0 count = 0 i = 0 while i <= m - n: if text[i:i+n] == pattern: count += 1 i += n else: i += 1 return count
simplelr_Algorithm
[ { "content": "Question:\n### String Pattern Finder: Substring Occurrence Counter\n\n**Context:** \nYou are creating a program that identifies how many times a particular pattern appears within a given string.\n\n**Problem:** \nWrite a function `count_occurrences(text: str, pattern: str) -> int` to count the n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1211, "level": 1, "question": "### String Pattern Finder: Substring Occurrence Counter\n\n**Context:** \nYou are creating a program that identifies how many times a particular pattern appears within a given string.\n\n**Problem:** \nWrite a function `count_occurrences(text: str, p...
def compress_string(s): if not s: return s # Though the problem states s is non-empty, this handles edge cases result = [] current_char = s[0] count = 1 for char in s[1:]: if char == current_char: count += 1 else: result.append(current_char ...
simplelr_Package
[ { "content": "Question:\nIn this problem, you need to write a Python function named `compress_string` that will compress a given string by replacing consecutive occurrences of the same character with the character followed by the number of occurrences. If the \"compressed\" string is longer than the original st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1212, "level": 1, "question": "In this problem, you need to write a Python function named `compress_string` that will compress a given string by replacing consecutive occurrences of the same character with the character followed by the number of occurrences. If the \"compressed\" st...
def find_positives(numbers): return [num for num in numbers if num > 0] numbers = [3, -1, 4, 0, -3, 5, -2, 7] print(find_positives(numbers))
simplelr_Filter
[ { "content": "Question:\ndef find_positives(numbers):\n return [num for num in numbers if num > 0]\n\nnumbers = [3, -1, 4, 0, -3, 5, -2, 7]\nprint(find_positives(numbers))\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1213, "level": 1, "question": "def find_positives(numbers):\n return [num for num in numbers if num > 0]\n\nnumbers = [3, -1, 4, 0, -3, 5, -2, 7]\nprint(find_positives(numbers))", "split": "train" }
import re def string_to_word_list(input_string): return [word for word in re.split('[ ,]+', input_string) if word] # Example usage: # input_str = "hello,world this is,a test" # output = string_to_word_list(input_str) # print(output) # Output: ['hello', 'world', 'this', 'is', 'a', 'test']
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python function that converts a string to a list of words, where words are separated by spaces or commas?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1214, "level": 1, "question": "Can you provide a Python function that converts a string to a list of words, where words are separated by spaces or commas?", "split": "train" }
def min_coins(coins: list[int], amount: int) -> int: if amount == 0: return 0 # Remove duplicates and sort coins in ascending order coins = sorted(list(set(coins))) # Initialize DP array with infinity dp = [float('inf')] * (amount + 1) dp[0] = 0 # Base case for i in r...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Context\nYou are developing a dynamic programming algorithm to solve the classic \"coin change problem\". The goal is to determine the minimum number of coins required to make up a given amount. Your implementation should efficiently handle differe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1215, "level": 1, "question": "### Coding Assessment Question\n\n#### Context\nYou are developing a dynamic programming algorithm to solve the classic \"coin change problem\". The goal is to determine the minimum number of coins required to make up a given amount. Your implementatio...
def get_substring(s, n): if n <= 0: return "" return s[:n]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that accepts a string and a number as input. The function should return a substring from the given string, starting from the beginning of the string and up to the nth character. If n is greater than the length of the string, return the entire string.\nAnswer:\nLet's th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1216, "level": 1, "question": "Create a function that accepts a string and a number as input. The function should return a substring from the given string, starting from the beginning of the string and up to the nth character. If n is greater than the length of the string, return th...
def find_rectangles(rows: int, cols: int) -> int: rows_comb = (rows + 1) * rows // 2 cols_comb = (cols + 1) * cols // 2 return rows_comb * cols_comb
simplelr_Algorithm
[ { "content": "Question:\n### Question\n\nIn this task, you are required to implement a function called `find_rectangles` which calculates the number of rectangles that can be formed within a given grid.\n\n#### Function Signature\n```python\ndef find_rectangles(rows: int, cols: int) -> int:\n ...\n```\n\n###...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1217, "level": 1, "question": "### Question\n\nIn this task, you are required to implement a function called `find_rectangles` which calculates the number of rectangles that can be formed within a given grid.\n\n#### Function Signature\n```python\ndef find_rectangles(rows: int, cols...
import heapq def optimized_prims_mst(graph): if not graph: return 0 start_node = next(iter(graph.keys())) visited = set([start_node]) heap = [] total_weight = 0 # Initialize the heap with all edges from the starting node for neighbor in graph[start_node]: weight = ...
simplelr_Data_Structure
[ { "content": "Question:\n### Problem: Refactoring Prim’s Algorithm\n\nYou are provided with a partial implementation of Prim's Algorithm. Your task is to complete and optimize this implementation, ensuring it can handle more complex scenarios efficiently. Specifically, ensure that the algorithm correctly identi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1218, "level": 1, "question": "### Problem: Refactoring Prim’s Algorithm\n\nYou are provided with a partial implementation of Prim's Algorithm. Your task is to complete and optimize this implementation, ensuring it can handle more complex scenarios efficiently. Specifically, ensure ...
def word_frequencies(word_list): freq = {} for word in word_list: freq[word] = freq.get(word, 0) + 1 return freq
simplelr_Filter
[ { "content": "Question:\nDesign a Python function that, given a list of words, returns a dictionary with the words as keys and their frequencies as values. For example, given the list `[\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"banana\"]`, the function should return `{\"apple\": 2, \"banana\":...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1219, "level": 1, "question": "Design a Python function that, given a list of words, returns a dictionary with the words as keys and their frequencies as values. For example, given the list `[\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"banana\"]`, the function should...
def sum_of_perfect_squares(n): total = 0 i = 0 while i * i <= n: total += i * i i += 1 return total
simplelr_Filter
[ { "content": "Question:\nHello! I've been having trouble with a programming problem. I'm trying to create a function that takes a number, n, as input and returns the sum of all perfect squares less than or equal to n. \n\nCould you help me with this?\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1220, "level": 1, "question": "Hello! I've been having trouble with a programming problem. I'm trying to create a function that takes a number, n, as input and returns the sum of all perfect squares less than or equal to n. \n\nCould you help me with this?", "split": "train" }
def get_version_string(version_info: dict) -> str: major = version_info["PY_MAJOR_VERSION"] minor = version_info["PY_MINOR_VERSION"] micro = version_info["PY_MICRO_VERSION"] base = f"{major}.{minor}.{micro}" release_level = version_info["PY_RELEASE_LEVEL"] release_map = { "0xA": 'a'...
simplelr_Docs
[ { "content": "Question:\n## Coding Assessment Question\n\nIn this task, you are required to implement a function that processes version information of CPython and returns the version string.\n\nThe version information will be provided as a dictionary with the following keys:\n- \"PY_MAJOR_VERSION\" \n- \"PY_MIN...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1221, "level": 1, "question": "## Coding Assessment Question\n\nIn this task, you are required to implement a function that processes version information of CPython and returns the version string.\n\nThe version information will be provided as a dictionary with the following keys:\n...
def categorize_transactions(transactions): credit = [] debit = [] for transaction in transactions: if transaction['type'] == 'credit': credit.append(transaction) else: debit.append(transaction) return {'credit': credit, 'debit': debit}
simplelr_Evol
[ { "content": "Question:\nGiven a list of transactions represented as dictionaries with 'id', 'amount' and 'type' (either 'credit' or 'debit'), write a Python function that categorizes these transactions into two separate lists: one for 'credit' and one for 'debit'. Each list should preserve the original order o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1222, "level": 1, "question": "Given a list of transactions represented as dictionaries with 'id', 'amount' and 'type' (either 'credit' or 'debit'), write a Python function that categorizes these transactions into two separate lists: one for 'credit' and one for 'debit'. Each list s...
def solve(d): result = [] for name, age in d.items(): if age > 18: result.append(name) return result
simplelr_Filter
[ { "content": "Question:\nYou've been tasked with creating a Python function `solve` that takes a dictionary `d` as input, where `d` contains information about users and their respective ages. The function should return the names of users who are older than 18 years.\nAnswer:\nLet's think step by step.\n", "...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1223, "level": 1, "question": "You've been tasked with creating a Python function `solve` that takes a dictionary `d` as input, where `d` contains information about users and their respective ages. The function should return the names of users who are older than 18 years.", "split...
import re def analyze_logs(logs: str) -> dict: total_requests = 0 sum_size = 0 status_counts = {} # Regular expression pattern to match the log entry format pattern = re.compile(r'^([0-9.]+) - - \[(.*?)\] "(.*?)" (\d+) (\d+)') # Split the logs into individual lines lines = logs.split('\n'...
simplelr_Docs
[ { "content": "Question:\n### Problem: Log File Analyzer\n\nYou are provided with a large log file from a web server. Each entry in the log file contains information about a single request to the server. The format of each log entry is as follows:\n\n```\nIP_ADDRESS - - [DATE] \"HTTP_METHOD URL HTTP_VERSION\" ST...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1224, "level": 1, "question": "### Problem: Log File Analyzer\n\nYou are provided with a large log file from a web server. Each entry in the log file contains information about a single request to the server. The format of each log entry is as follows:\n\n```\nIP_ADDRESS - - [DATE] ...
def square_and_sort_evens(lst): even_squares = [x ** 2 for x in lst if x % 2 == 0] even_squares.sort() return even_squares
simplelr_Apps
[ { "content": "Question:\nCreate a function that takes a list of integers and returns a new list containing the squares of all the even numbers from the original list, sorted in ascending order.\n\nExample:\n```\ninput: [4, 3, 1, 6, 9, 8]\noutput: [16, 36, 64]\n\ninput: [7, 2, 5, 8, 11, 4]\noutput: [4, 16, 64]\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1225, "level": 1, "question": "Create a function that takes a list of integers and returns a new list containing the squares of all the even numbers from the original list, sorted in ascending order.\n\nExample:\n```\ninput: [4, 3, 1, 6, 9, 8]\noutput: [16, 36, 64]\n\ninput: [7, 2, ...
def get_customer_category(transactions: dict, high_threshold: float, low_threshold: float) -> dict: result = {} for customer, txns in transactions.items(): total = sum(txns) if total > high_threshold: result[customer] = 'High' elif total <= low_threshold: result[c...
simplelr_Package
[ { "content": "Question:\n**\n\nImagine you are tasked with developing a function for a banking software `get_customer_category`, which will categorize bank customers based on their yearly transactions. The function should take as input a dictionary representing customer transactions and two threshold values. Sp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1226, "level": 1, "question": "**\n\nImagine you are tasked with developing a function for a banking software `get_customer_category`, which will categorize bank customers based on their yearly transactions. The function should take as input a dictionary representing customer transa...
def total_value(records): total = 0 for record in records: quantity = record['quantity'] price = record['price'] if quantity < 0 or price <= 0: continue total += quantity * price return total
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of dictionaries, where each dictionary represents a record with a 'name', 'quantity', and 'price' key. The function should return the total value of all records, calculated as the sum of (quantity * price) for each record. Additionally, filter o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1227, "level": 1, "question": "Write a Python function that takes a list of dictionaries, where each dictionary represents a record with a 'name', 'quantity', and 'price' key. The function should return the total value of all records, calculated as the sum of (quantity * price) for ...
def longest_climb_series(heights): n = len(heights) if n <= 1: return n max_len = 1 dp = [{} for _ in range(n)] for i in range(1, n): for j in range(i): d = heights[i] - heights[j] prev_length = dp[j].get(d, 1) current_length = prev_length + 1 ...
simplelr_Codeforces
[ { "content": "Question:\nGiven a list of integers representing the heights of trees lined in a row, you like to climb these trees in a series such that the difference in heights between each consecutive tree you climb is the same. Your task is to determine the length of the longest possible series of climbs wit...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1228, "level": 1, "question": "Given a list of integers representing the heights of trees lined in a row, you like to climb these trees in a series such that the difference in heights between each consecutive tree you climb is the same. Your task is to determine the length of the lo...
def first_non_repeating(s): # Build frequency dictionary freq = {} for char in s: if char in freq: freq[char] += 1 else: freq[char] = 1 # Find the first non-repeating character for char in s: if freq[char] == 1: return char return ...
simplelr_Apps
[ { "content": "Question:\nYou need to write a function that finds the first non-repeating character in a given string. Return the character if it exists, otherwise return an empty string. Examples:\n\nHandle edge cases where the string might be completely without unique characters.\n\n```python\nfirst_non_repeat...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1229, "level": 1, "question": "You need to write a function that finds the first non-repeating character in a given string. Return the character if it exists, otherwise return an empty string. Examples:\n\nHandle edge cases where the string might be completely without unique charact...
from collections import Counter def rearrange_string(s): counts = Counter(s) n = len(s) max_count = max(counts.values()) if max_count > (n + 1) // 2: return "" res = [] last_char = None sorted_chars = sorted(counts.keys()) for _ in range(n): candidates = [...
simplelr_Filter
[ { "content": "Question:\nGiven a string `s`, write a Python function `rearrange_string(s)` that takes a string `s` as input and returns the lexicographically smallest string that can be formed by rearranging the characters in `s` such that no two adjacent characters in the resulting string are the same. If no s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1230, "level": 1, "question": "Given a string `s`, write a Python function `rearrange_string(s)` that takes a string `s` as input and returns the lexicographically smallest string that can be formed by rearranging the characters in `s` such that no two adjacent characters in the res...
def max_common_substring(master: str, slave: str) -> int: m = len(master) n = len(slave) # Create a DP table initialized with zeros dp = [[0] * (n + 1) for _ in range(m + 1)] max_length = 0 for i in range(1, m + 1): for j in range(1, n + 1): if master[i-1] == slave[j-1]:...
simplelr_Codeforces
[ { "content": "Question:\nIn the fictional land of Stringland, every citizen uses strings for communication. Given two strings, `master` and `slave`, the citizens have a unique way of determining how similar two strings are. The similarity score is calculated by finding the maximum length of the substring that o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1231, "level": 1, "question": "In the fictional land of Stringland, every citizen uses strings for communication. Given two strings, `master` and `slave`, the citizens have a unique way of determining how similar two strings are. The similarity score is calculated by finding the max...
def decode_message(encoded_message): result = '' for s in encoded_message: num = int(s) char = chr(ord('A') + num - 1) result += char return result
simplelr_Taco
[ { "content": "Question:\nTask\n\nYou have been given a message encoded in a certain format. The message consists of a series of words, and each word is a sequence of digits. Each digit in the word represents a letter in the alphabet encoded as follows: A = 1, B = 2, ..., Z = 26. Your task is to implement a func...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1232, "level": 1, "question": "Task\n\nYou have been given a message encoded in a certain format. The message consists of a series of words, and each word is a sequence of digits. Each digit in the word represents a letter in the alphabet encoded as follows: A = 1, B = 2, ..., Z = 2...
def longest_constant_interval(distances): if not distances: return "" groups = [] current_value = distances[0] current_start = 0 for i in range(1, len(distances)): if distances[i] != current_value: groups.append((current_value, current_start, i - 1)) ...
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes in a list of integers representing the distances traveled by a vehicle in consecutive seconds. The function should return a string containing the starting and ending seconds of the longest continuous interval where the vehicle traveled the same distance every...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1233, "level": 1, "question": "Write a function that takes in a list of integers representing the distances traveled by a vehicle in consecutive seconds. The function should return a string containing the starting and ending seconds of the longest continuous interval where the vehic...
from typing import List def sort_segments(n: int, arr: List[int], m: int, segments: List[int], order: List[int]) -> List[int]: current_index = 0 segments_list = [] for length in segments: end = current_index + length segments_list.append(arr[current_index:end]) current_index = end ...
simplelr_Algorithm
[ { "content": "Question:\n### Number Sorting with Constraints\n\n#### Problem Description:\nYou are tasked with implementing a function that sorts a given list of integers but with an added constraint: the list is partitioned into several segments, each of which needs to be sorted independently. Additionally, th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1234, "level": 1, "question": "### Number Sorting with Constraints\n\n#### Problem Description:\nYou are tasked with implementing a function that sorts a given list of integers but with an added constraint: the list is partitioned into several segments, each of which needs to be sor...
def list_length(lst): return len(lst)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers and returns the length of the list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1235, "level": 1, "question": "Create a function that takes a list of integers and returns the length of the list.", "split": "train" }
def find_longest_substring_with_k_distinct_chars(s: str, k: int) -> str: if k == 0 or len(s) == 0: return "" max_length = 0 max_start = 0 char_count = {} left = 0 for right in range(len(s)): char = s[right] if char in char_count: char_count[char] += ...
simplelr_Apps
[ { "content": "Question:\nCreate a function `find_longest_substring_with_k_distinct_chars(s: str, k: int) -> str` that finds the longest substring of a given string `s` containing up to `k` distinct characters. If there are multiple substrings with the same length, return the one that appears first in the string...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1236, "level": 1, "question": "Create a function `find_longest_substring_with_k_distinct_chars(s: str, k: int) -> str` that finds the longest substring of a given string `s` containing up to `k` distinct characters. If there are multiple substrings with the same length, return the o...
def common_elements(list1, list2): set1 = set(list1) set2 = set(list2) combined = list1 + list2 result = [] added = set() for num in combined: if num in set1 and num in set2 and num not in added: result.append(num) added.add(num) return result
simplelr_Evol
[ { "content": "Question:\nDesign a function that takes two lists of integers as input and returns a list containing the common elements between the two lists, without duplicates. The order of elements in the resulting list should reflect their first appearance in the input lists.\nlist1 = [1, 2, 3, 4, 4, 5]\nlis...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1237, "level": 1, "question": "Design a function that takes two lists of integers as input and returns a list containing the common elements between the two lists, without duplicates. The order of elements in the resulting list should reflect their first appearance in the input list...
def highest_frequency_character(s): char_info = {} for index, char in enumerate(s): if char not in char_info: char_info[char] = (1, index) else: current_count, current_index = char_info[char] char_info[char] = (current_count + 1, current_index) if not...
simplelr_Package
[ { "content": "Question:\nIn this problem, you are required to use Python to manipulate strings, specifically focusing on character frequency analysis. You will create a function called `highest_frequency_character(s)` that finds the character with the highest frequency in a given string. In the case of a tie (i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1238, "level": 1, "question": "In this problem, you are required to use Python to manipulate strings, specifically focusing on character frequency analysis. You will create a function called `highest_frequency_character(s)` that finds the character with the highest frequency in a gi...
def reverse_integer_list(s: str) -> list[int]: parts = s.split(',') numbers = [int(x) for x in parts] numbers.reverse() return numbers
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are given a task to write a function that takes a string containing a list of integers separated by commas and returns the reversed list of integers. The input string will always be well-formed and will not contain any spaces.\n\n### Function Signature\n```p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1239, "level": 1, "question": "### Problem Statement\n\nYou are given a task to write a function that takes a string containing a list of integers separated by commas and returns the reversed list of integers. The input string will always be well-formed and will not contain any spac...
from typing import List, Tuple, Dict def summarize_timestamps(timestamps: List[str]) -> Tuple[Dict[str, Dict[str, str]], int]: result_dict = {} for ts in timestamps: date_part, time_part = ts.split(' ', 1) if date_part not in result_dict: result_dict[date_part] = { '...
simplelr_Docs
[ { "content": "Question:\n#### Task:\nWrite a function in Python that takes a list of timestamps and returns a dictionary summarizing the following information for each unique date:\n- The earliest and latest times logged on that date.\n- The total number of unique dates present in the input list.\n\n#### Input:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1240, "level": 1, "question": "#### Task:\nWrite a function in Python that takes a list of timestamps and returns a dictionary summarizing the following information for each unique date:\n- The earliest and latest times logged on that date.\n- The total number of unique dates presen...
def process_data(data): new_data = [] sum_odd = 0 for num in data: if num % 2 == 0: new_data.append(num ** 2) else: sum_odd += num new_data.append(sum_odd) return new_data
simplelr_Filter
[ { "content": "Question:\nThe following code defines a function named `process_data` that takes a list of numbers as input and returns a new list with the following modifications:\n\n* **Squares:** All even numbers in the input list are squared.\n* **Sum:** The sum of all odd numbers in the input list is calcula...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1241, "level": 1, "question": "The following code defines a function named `process_data` that takes a list of numbers as input and returns a new list with the following modifications:\n\n* **Squares:** All even numbers in the input list are squared.\n* **Sum:** The sum of all odd n...
def max_subarray_sum(arr): if not arr: return 0 # Assuming the function should return 0 for an empty array max_ending_here = max_so_far = arr[0] for x in arr[1:]: max_ending_here = max(x, max_ending_here + x) if max_ending_here > max_so_far: max_so_far = max_ending_...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that finds the maximum sum of a subarray of a given array of integers. For example, the input array is `[1, -3, 2, 1, -1]`, and the function should return `3`, as the subarray `[2, 1]` has the maximum sum.\nAnswer:\nLet's think step by step.\n", "role": "user" } ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1242, "level": 1, "question": "Create a function that finds the maximum sum of a subarray of a given array of integers. For example, the input array is `[1, -3, 2, 1, -1]`, and the function should return `3`, as the subarray `[2, 1]` has the maximum sum.", "split": "train" }
def int_to_binary_string(n): if not isinstance(n, int) or n <= 0: raise ValueError("Input must be a positive integer.") return bin(n) + 'b'
simplelr_Prefill
[ { "content": "Question:\nCreate a function that converts a given positive integer into its binary representation in string format. The output string should start with '0b' and end with 'b' to indicate binary format. The function should validate that the input is indeed a positive integer and produce an appropri...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1243, "level": 1, "question": "Create a function that converts a given positive integer into its binary representation in string format. The output string should start with '0b' and end with 'b' to indicate binary format. The function should validate that the input is indeed a posit...
def power(base, exponent): if exponent == 0: return 1 elif exponent < 0: return 1 / power(base, -exponent) else: return base * power(base, exponent - 1)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to calculate the power of a number using recursion. The function should take two integers, `base` and `exponent`, and return the result of `base` raised to the power of `exponent`. The function should handle negative exponents by returning the reciprocal of the p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1244, "level": 1, "question": "Write a Python function to calculate the power of a number using recursion. The function should take two integers, `base` and `exponent`, and return the result of `base` raised to the power of `exponent`. The function should handle negative exponents b...
def merge_intervals(intervals): if not intervals: return [] intervals.sort(key=lambda x: x[0]) merged = [] for interval in intervals: if not merged: merged.append(interval) else: last = merged[-1] if interval[0] <= last[1]: # Me...
simplelr_Apps
[ { "content": "Question:\nGiven a list of intervals, merge all overlapping intervals.\n\nExample 1:\n\n\nInput: [[1,3],[2,6],[8,10],[15,18]]\nOutput: [[1,6],[8,10],[15,18]]\n\n\nExample 2:\n\n\nInput: [[1,4],[4,5]]\nOutput: [[1,5]]\n\n\nNote:\n\nMake sure the intervals are sorted in ascending order of their star...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1245, "level": 1, "question": "Given a list of intervals, merge all overlapping intervals.\n\nExample 1:\n\n\nInput: [[1,3],[2,6],[8,10],[15,18]]\nOutput: [[1,6],[8,10],[15,18]]\n\n\nExample 2:\n\n\nInput: [[1,4],[4,5]]\nOutput: [[1,5]]\n\n\nNote:\n\nMake sure the intervals are sort...
def invert_case_and_count(s): new_string = [] uppercase_count = 0 lowercase_count = 0 for char in s: if char.isupper(): uppercase_count += 1 new_string.append(char.lower()) elif char.islower(): lowercase_count += 1 new_string.append(char.up...
simplelr_Filter
[ { "content": "Question:\nI am trying to implement a function in Python that will convert a given string to a new string. The new string should have each character's case inverted - meaning, if the character is uppercase, it should be converted to lowercase, and vice versa. Additionally, I want to add a feature ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1246, "level": 1, "question": "I am trying to implement a function in Python that will convert a given string to a new string. The new string should have each character's case inverted - meaning, if the character is uppercase, it should be converted to lowercase, and vice versa. Add...
import string def count_word_frequency(strings, word, ignore_punctuation=False): # Process the target word processed_word = word.lower() if ignore_punctuation: # Remove all punctuation from the target word processed_word = processed_word.translate(str.maketrans('', '', string.punctuation)) ...
simplelr_Filter
[ { "content": "Question:\nWrite a python snippet that counts the frequency of a given word in a list of strings, ensuring the count is case-insensitive and also including an option to ignore punctuation. The function should take two arguments: a list of strings and a word to search for.\nAnswer:\nLet's think ste...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1247, "level": 1, "question": "Write a python snippet that counts the frequency of a given word in a list of strings, ensuring the count is case-insensitive and also including an option to ignore punctuation. The function should take two arguments: a list of strings and a word to se...
from typing import List def pigeonhole_sort(arr: List[int]) -> List[int]: if not arr: return [] min_val = min(arr) max_val = max(arr) range_size = max_val - min_val + 1 buckets = [0] * range_size for num in arr: buckets[num - min_val] += 1 result = [] for ...
simplelr_Data_Structure
[ { "content": "Question:\n### Pigeonhole Sort Implementation and Analysis\n\n#### Background\nPigeonhole Sort is an effective sorting algorithm for lists where the number of elements and key values are not very different. By distributing elements into \"holes\" and then collecting them in an orderly fashion, it ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1248, "level": 1, "question": "### Pigeonhole Sort Implementation and Analysis\n\n#### Background\nPigeonhole Sort is an effective sorting algorithm for lists where the number of elements and key values are not very different. By distributing elements into \"holes\" and then collect...
def max_same_value_subarray_sum(arr): if not arr: return 0 # Assuming the array is non-empty as per problem constraints max_sum = current_sum = arr[0] current_value = arr[0] current_count = 1 for num in arr[1:]: if num == current_value: current_count += 1 cur...
simplelr_Apps
[ { "content": "Question:\nGiven an array of integers, return the maximum sum of any non-empty subarray such that all elements in the subarray have the same value.\n\nExample 1:\n\nInput: [4, 4, 4, 5, 5, 6, 6, 6, 6]\n\nOutput: 24\n\nExplanation:\nThe contiguous subarray [6, 6, 6, 6] has the same value and its sum...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1249, "level": 1, "question": "Given an array of integers, return the maximum sum of any non-empty subarray such that all elements in the subarray have the same value.\n\nExample 1:\n\nInput: [4, 4, 4, 5, 5, 6, 6, 6, 6]\n\nOutput: 24\n\nExplanation:\nThe contiguous subarray [6, 6, 6...
def sort_dict_list_by_key(dict_list, key): return sorted(dict_list, key=lambda x: x[key])
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to sort a list of dictionary objects by a specified key in ascending order. The function should return the sorted list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1250, "level": 1, "question": "Write a python function to sort a list of dictionary objects by a specified key in ascending order. The function should return the sorted list.", "split": "train" }
def flatten_list(lst): result = [] for sublist in lst: result.extend(sublist) return result
simplelr_Apps
[ { "content": "Question:\nWrite a function called `flatten_list` which takes a list of lists and returns a single list with all the elements of the nested lists in the same order. The function should only handle a depth of one (i.e., it will not need to handle lists of lists of lists).\nAnswer:\nLet's think step...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1251, "level": 1, "question": "Write a function called `flatten_list` which takes a list of lists and returns a single list with all the elements of the nested lists in the same order. The function should only handle a depth of one (i.e., it will not need to handle lists of lists of...
def reverse_integer(num): is_negative = num < 0 n = abs(num) reversed_str = str(n)[::-1] reversed_num = int(reversed_str) return -reversed_num if is_negative else reversed_num
simplelr_Evol
[ { "content": "Question:\nReverse the digits of the given integer and return the resulting value. For instance, inputting 12345 should yield 54321. If the number is negative, retain the negative sign at the front. Inputting -678 would return -876.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1252, "level": 1, "question": "Reverse the digits of the given integer and return the resulting value. For instance, inputting 12345 should yield 54321. If the number is negative, retain the negative sign at the front. Inputting -678 would return -876.", "split": "train" }
def sum_of_matrix(matrix): return sum([element for row in matrix for element in row])
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to calculate the sum of all elements in a 2D list (matrix) using list comprehension.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1253, "level": 1, "question": "Write a Python function to calculate the sum of all elements in a 2D list (matrix) using list comprehension.", "split": "train" }
import itertools def generate_combinations_with_repetition(s): combinations = set() for k in range(1, len(s) + 1): for combo in itertools.product(s, repeat=k): combinations.add(''.join(combo)) return combinations
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to generate a set of all possible combinations of a string with repetitions allowed.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1254, "level": 1, "question": "Write a python function to generate a set of all possible combinations of a string with repetitions allowed.", "split": "train" }
import heapq def dijkstra_algorithm(graph, start, end): if start not in graph or end not in graph: return ([], 0) # Initialize distances and parents dictionaries distances = {node: float('inf') for node in graph} distances[start] = 0 parents = {} # Priority queue: (distance, n...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment: Develop a Custom Dijkstra’s Algorithm for Navigation System\n\n#### Scenario\nYou are working for an emerging tech company specializing in geographic information systems (GIS). Your team is tasked with creating a navigation system that finds the shortest path betw...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1255, "level": 1, "question": "### Coding Assessment: Develop a Custom Dijkstra’s Algorithm for Navigation System\n\n#### Scenario\nYou are working for an emerging tech company specializing in geographic information systems (GIS). Your team is tasked with creating a navigation syste...
def flip_binary_string(s): return s.translate(str.maketrans('01', '10'))
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to flip a binary string (convert all '0's to '1's and all '1's to '0's).\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1256, "level": 1, "question": "Write a python function to flip a binary string (convert all '0's to '1's and all '1's to '0's).", "split": "train" }
def filter_even_and_greater_than_ten(nums): return [num for num in nums if num % 2 == 0 and num > 10]
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of integers and returns a new list containing only the integers that are even and greater than 10. Use list comprehension for this task. The function should be efficient and concise.\nAnswer:\nLet's think step by step.\n", "role": "user" }...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1257, "level": 1, "question": "Write a Python function that takes a list of integers and returns a new list containing only the integers that are even and greater than 10. Use list comprehension for this task. The function should be efficient and concise.", "split": "train" }
from collections import deque def shortest_path(grid, start, end): x1, y1 = start x2, y2 = end # Check if start or end is blocked if grid[x1][y1] != 0 or grid[x2][y2] != 0: return -1 # If start is the same as end if (x1, y1) == (x2, y2): return 0 rows = len(grid) cols...
simplelr_Evol
[ { "content": "Question:\nCreate a function that determines the shortest path from a starting point to a destination within a 2D grid while circumventing obstacles. The grid is represented as a list of lists with 0's indicating navigable cells and 1's indicating obstacles. The function should receive the grid, t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1258, "level": 1, "question": "Create a function that determines the shortest path from a starting point to a destination within a 2D grid while circumventing obstacles. The grid is represented as a list of lists with 0's indicating navigable cells and 1's indicating obstacles. The ...
import math def cosine_similarity(vec1: list, vec2: list) -> float: if len(vec1) != len(vec2): raise ValueError("Vectors must be of the same length.") dot_product = 0.0 sum_a_sq = 0.0 sum_b_sq = 0.0 for a, b in zip(vec1, vec2): dot_product += a * b sum_a_sq += a **...
simplelr_Data_Structure
[ { "content": "Question:\n### Cosine Similarity Calculation\nYou have been tasked with writing a function to calculate the cosine similarity between two vectors. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1259, "level": 1, "question": "### Cosine Similarity Calculation\nYou have been tasked with writing a function to calculate the cosine similarity between two vectors. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures th...
def sort_XO(arr): o_pos = 0 for i in range(len(arr)): if arr[i] == 'O': arr[o_pos], arr[i] = arr[i], arr[o_pos] o_pos += 1 return arr
simplelr_Prefill
[ { "content": "Question:\nWrite a function to sort an array of strings containing only two types of characters, 'X' and 'O'. The function should sort the array such that all 'O's come first and all 'X's come last, maintaining relative order among 'O's and 'X's. The function should achieve this sorting in O(n) ti...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1260, "level": 1, "question": "Write a function to sort an array of strings containing only two types of characters, 'X' and 'O'. The function should sort the array such that all 'O's come first and all 'X's come last, maintaining relative order among 'O's and 'X's. The function sho...
def list_partition(lst): result = {'even': [], 'odd': []} for num in lst: if num % 2 == 0: result['even'].append(num) else: result['odd'].append(num) return result
simplelr_Apps
[ { "content": "Question:\nCreate a function that takes a list of integers and returns a dictionary with two keys: \"even\" and \"odd\". The value for each key should be a list of the corresponding even and odd integers from the input list. \n\nIf there are no even or odd integers, the value should be an empty li...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1261, "level": 1, "question": "Create a function that takes a list of integers and returns a dictionary with two keys: \"even\" and \"odd\". The value for each key should be a list of the corresponding even and odd integers from the input list. \n\nIf there are no even or odd intege...
def is_palindrome(word): word_list = list(word) reversed_word_list = word_list.copy() reversed_word_list.reverse() return word_list == reversed_word_list
simplelr_Filter
[ { "content": "Question:\nWith only \"Python Lists\" and without using direct string introspection, create a function that determines if a given word is a palindrome.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1262, "level": 1, "question": "With only \"Python Lists\" and without using direct string introspection, create a function that determines if a given word is a palindrome.", "split": "train" }
def find_two_sum(nums, target): num_map = {} for index, num in enumerate(nums): complement = target - num if complement in num_map: return [num_map[complement], index] num_map[num] = index # As per problem statement, a solution exists, so no need for error handling re...
simplelr_Taco
[ { "content": "Question:\nWrite an algorithm that receives a list of numbers and a target number, and returns the indices of the two numbers that add up to the target. Consider that each input would have exactly one solution, and you may not use the same element twice.\n\n```python\nfind_two_sum([2, 11, 7, 15], ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1263, "level": 1, "question": "Write an algorithm that receives a list of numbers and a target number, and returns the indices of the two numbers that add up to the target. Consider that each input would have exactly one solution, and you may not use the same element twice.\n\n```py...
def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to implement the insertion sort algorithm for sorting a list of numbers. The function should take a list of integers or floats as input and return the list sorted in ascending order. Include a brief explanation of the insertion sort algorithm and the time complex...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1264, "level": 1, "question": "Write a Python function to implement the insertion sort algorithm for sorting a list of numbers. The function should take a list of integers or floats as input and return the list sorted in ascending order. Include a brief explanation of the insertion ...
from typing import List, Tuple def optimal_matrix_chain_multiplication(dims: List[int]) -> Tuple[int, List[List[int]]]: m = len(dims) if m < 2: return (0, []) n = m - 1 # Number of matrices dp = [[0] * m for _ in range(m)] split = [[0] * m for _ in range(m)] for l in range(2,...
simplelr_Data_Structure
[ { "content": "Question:\n### Problem: Optimal Matrix Chain Multiplication\n\nYou are given a sequence of matrices, and your goal is to determine the most efficient way to multiply these matrices together. The efficiency is measured by the minimum number of scalar multiplications needed.\n\n### Function Signatur...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1265, "level": 1, "question": "### Problem: Optimal Matrix Chain Multiplication\n\nYou are given a sequence of matrices, and your goal is to determine the most efficient way to multiply these matrices together. The efficiency is measured by the minimum number of scalar multiplicatio...
def increment_elements(lst): return [x + 1 for x in lst]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that increases the value of each element in a list by one.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1266, "level": 1, "question": "Create a function that increases the value of each element in a list by one.", "split": "train" }
def organize_books(n, titles): unique_titles = list(set(titles)) unique_titles.sort() return unique_titles
simplelr_Taco
[ { "content": "Question:\n# Task\n Emily loves reading books and she wants to organize her bookshelf. She has `n` books, each with a title consisting of lowercase English letters. Emily wants to arrange the books in lexicographical order, but she also wants to remove any duplicate titles to save space.\n\n Write...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1267, "level": 1, "question": "# Task\n Emily loves reading books and she wants to organize her bookshelf. She has `n` books, each with a title consisting of lowercase English letters. Emily wants to arrange the books in lexicographical order, but she also wants to remove any duplic...
def first_unique_char_optimized(s): char_count = [0] * 26 # Using a list for constant time access # Count the frequency of each character for c in s: index = ord(c) - ord('a') char_count[index] += 1 # Find the first character with count 1 for i in range(len(s)): c = s[i] ...
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario\nYou are working on a text processing module that needs to identify the first non-repeating character in various strings provided by users. Efficiently identifying such characters will help in various text analysis tasks, such as frequency analysis and unique element identi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1268, "level": 1, "question": "### Scenario\nYou are working on a text processing module that needs to identify the first non-repeating character in various strings provided by users. Efficiently identifying such characters will help in various text analysis tasks, such as frequency...
def gcd(a, b): a, b = abs(a), abs(b) while b: a, b = b, a % b return a
simplelr_Filter
[ { "content": "Question:\nThis is the code I wrote.\n\n```python\ndef gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n```\n\nThis function takes two integers as arguments and returns their greatest common divisor (GCD) using the Euclidean algorithm.\n\nHowever, I need to adapt this function to handle ne...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1269, "level": 1, "question": "This is the code I wrote.\n\n```python\ndef gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n```\n\nThis function takes two integers as arguments and returns their greatest common divisor (GCD) using the Euclidean algorithm.\n\nHowever, I need ...
def generate_pascals_triangle(n: int) -> list: if n == 0: return [] triangle = [[1]] if n == 1: return triangle for i in range(1, n): current_row = [1] prev_row = triangle[i-1] for j in range(1, i): current_row.append(prev_row[j-1] + prev_row[j]) ...
simplelr_Taco
[ { "content": "Question:\nWrite a function that accepts an integer n representing the number of rows in Pascal's Triangle and returns a list of lists containing the values in Pascal's Triangle up to the nth row.\n\nPascal's Triangle is a triangular array of numbers where the values on the edges of the triangle a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1270, "level": 1, "question": "Write a function that accepts an integer n representing the number of rows in Pascal's Triangle and returns a list of lists containing the values in Pascal's Triangle up to the nth row.\n\nPascal's Triangle is a triangular array of numbers where the va...
def min_path_cost(cost): if not cost or not cost[0]: return 0 m = len(cost) n = len(cost[0]) dp = [[0 for _ in range(n)] for _ in range(m)] dp[0][0] = cost[0][0] for j in range(1, n): dp[0][j] = dp[0][j-1] + cost[0][j] for i in range(1, m): dp[i][0] = dp[i-1...
simplelr_Leetcode
[ { "content": "Question:\nGiven a `m x n` integer grid `cost` where `cost[i][j]` represents the cost of stepping on the cell `(i, j)` from either the left or from above, return _the minimum cost to reach the bottom-right cell_ `(m-1, n-1)` from the top-left cell `(0, 0)`. You can only move either down or right a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1271, "level": 1, "question": "Given a `m x n` integer grid `cost` where `cost[i][j]` represents the cost of stepping on the cell `(i, j)` from either the left or from above, return _the minimum cost to reach the bottom-right cell_ `(m-1, n-1)` from the top-left cell `(0, 0)`. You c...
def reverse_and_count(s): reversed_s = s[::-1] char_count = {} for char in reversed_s: char_count[char] = char_count.get(char, 0) + 1 return reversed_s, char_count
simplelr_Filter
[ { "content": "Question:\nIn the given code, write a function that not only reverses a string, but also counts the occurrences of each character in the reversed string. The function should return the reversed string along with a dictionary where each key-value pair corresponds to a unique character (key) and its...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1272, "level": 1, "question": "In the given code, write a function that not only reverses a string, but also counts the occurrences of each character in the reversed string. The function should return the reversed string along with a dictionary where each key-value pair corresponds ...
import cgi def handle_cgi_request(): form = cgi.FieldStorage() errors = [] # Validate username if not ('username' in form and form['username'].value.strip()): errors.append('Username is required.') # Validate email if not ('email' in form and form['email'].value.strip()): erro...
simplelr_Docs
[ { "content": "Question:\n**CGI Form Data and File Upload Handling**\n\n**Objective:**\nCreate a CGI script using the `cgi` module that processes form data and handles file uploads. Your task is to write a function that processes form data and file uploads from an HTML form and returns the processed output as an...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1273, "level": 1, "question": "**CGI Form Data and File Upload Handling**\n\n**Objective:**\nCreate a CGI script using the `cgi` module that processes form data and handles file uploads. Your task is to write a function that processes form data and file uploads from an HTML form and...
import matplotlib.pyplot as plt import itertools def plot_product_sales(sales_data, product_filter=None, mode='total'): """ Plots the monthly sales for each product in sales_data. Parameters: sales_data (list): A list of dictionaries with keys 'product' and 'monthly_sales'. product_filter (lis...
simplelr_Package
[ { "content": "Question:\n### Problem\nYou are given a list of dictionaries, where each dictionary represents sales data for a product by month. Each dictionary has the following keys:\n- `product`: Name of the product (string).\n- `monthly_sales`: A list of integers representing monthly sales.\n\nWrite a functi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1274, "level": 1, "question": "### Problem\nYou are given a list of dictionaries, where each dictionary represents sales data for a product by month. Each dictionary has the following keys:\n- `product`: Name of the product (string).\n- `monthly_sales`: A list of integers representi...
from collections import Counter def most_frequent_element(arr): if not arr: return None count = Counter(arr) max_count = max(count.values()) candidates = [k for k, v in count.items() if v == max_count] return min(candidates)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in an array `arr` and returns the most frequent element in the array. If there are multiple elements with the same highest frequency, return the smallest one. If the array is empty, return `None`.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1275, "level": 1, "question": "Create a function that takes in an array `arr` and returns the most frequent element in the array. If there are multiple elements with the same highest frequency, return the smallest one. If the array is empty, return `None`.", "split": "train" }
def manual_sort_and_deduplicate(arr): # Remove duplicates by converting to a set and back to a list unique = list(set(arr)) n = len(unique) # Implement Bubble Sort to sort the unique elements for i in range(n): swapped = False # We need to loop through each element up to n - i -...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an **unsorted** array `arr` of size `n` containing **distinct integers**. Write a function that returns the array of the same integers sorted in **non-decreasing** order. Your solution should aim to implement the sorting algorithm manually rather than using built-in sortin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1276, "level": 1, "question": "You are given an **unsorted** array `arr` of size `n` containing **distinct integers**. Write a function that returns the array of the same integers sorted in **non-decreasing** order. Your solution should aim to implement the sorting algorithm manuall...
def sum_of_unique_elements(lst): unique_elements = set(lst) return sum(unique_elements)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the sum of all unique elements in a list. For instance, if the list contains squares of numbers from 1 to 5, like [1, 4, 9, 16, 25], the function should return the sum of these unique elements.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1277, "level": 1, "question": "Write a python function to find the sum of all unique elements in a list. For instance, if the list contains squares of numbers from 1 to 5, like [1, 4, 9, 16, 25], the function should return the sum of these unique elements.", "split": "train" }
def sum_of_divisors(n): if n <= 1: return 0 total = 0 sqrt_n = int(n ** 0.5) for i in range(1, sqrt_n + 1): if n % i == 0: if i != n: total += i j = n // i if j != i and j != n: total += j return total
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the sum of all divisors of a given number, excluding the number itself.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1278, "level": 1, "question": "Write a function to find the sum of all divisors of a given number, excluding the number itself.", "split": "train" }
def fibonacci_digits(n): if n == 0: return "" a, b = 0, 1 result = str(a) if len(result) >= n: return result[:n] result += str(b) if len(result) >= n: return result[:n] while True: next_num = a + b result += str(next_num) if len(result) >= n: ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that returns a string representation of the first n digits of the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the first 8 digits of the Fibonacci s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1279, "level": 1, "question": "Create a function that returns a string representation of the first n digits of the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, th...
def find_first_occurrence(lst, target): for index, value in enumerate(lst): if value == target: return index return -1
simplelr_Filter
[ { "content": "Question:\nWrite a function in Python that takes a list of integers and a target integer. The function should return the index of the first occurrence of the target in the list, or -1 if the target is not found. The function should handle the case where the list is empty. Additionally, provide a b...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1280, "level": 1, "question": "Write a function in Python that takes a list of integers and a target integer. The function should return the index of the first occurrence of the target in the list, or -1 if the target is not found. The function should handle the case where the list ...
def reverse_list(lst): if len(lst) <= 1: return lst[:] reversed_list = lst[:] left = 0 right = len(reversed_list) - 1 while left < right: reversed_list[left], reversed_list[right] = reversed_list[right], reversed_list[left] left += 1 right -= 1 return reversed_lis...
simplelr_Evol
[ { "content": "Question:\nWrite a function in Python that takes a list of integers and returns the list reversed without using the built-in `reverse()` method or slicing. Implement your own logic to reverse the list. Ensure your function is efficient and handles edge cases, such as empty lists or single-element ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1281, "level": 1, "question": "Write a function in Python that takes a list of integers and returns the list reversed without using the built-in `reverse()` method or slicing. Implement your own logic to reverse the list. Ensure your function is efficient and handles edge cases, suc...
from collections import deque def shortestPath(N, M, grid): # Check if the start or end is blocked if grid[0][0] == '#' or grid[N-1][M-1] == '#': return -1 # Handle the case where grid is 1x1 if N == 1 and M == 1: return 0 # Initialize the queue with starting position and ...
simplelr_Taco
[ { "content": "Question:\nGiven a grid of size N x M, where each cell may contain either a '.' indicating an open cell or a '#' indicating a blocked cell, determine the minimum number of steps required to move from the top-left corner (0, 0) to the bottom-right corner (N-1, M-1). You can only move up, down, left...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1282, "level": 1, "question": "Given a grid of size N x M, where each cell may contain either a '.' indicating an open cell or a '#' indicating a blocked cell, determine the minimum number of steps required to move from the top-left corner (0, 0) to the bottom-right corner (N-1, M-1...
def roman_to_int(s): roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} # Handle leading X's x_count = 0 while x_count < len(s) and s[x_count] == 'X': x_count += 1 total = x_count * 10 s_remaining = s[x_count:] # Process the remaining string ...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to convert a given Roman numeral to an integer. In this version, the function should also handle cases where the input numeral string starts with the letter \"X\" repeated multiple times at the beginning, and then the rest of the numeral follows. The function should ret...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1283, "level": 1, "question": "Write a function to convert a given Roman numeral to an integer. In this version, the function should also handle cases where the input numeral string starts with the letter \"X\" repeated multiple times at the beginning, and then the rest of the numer...
def remove_duplicates(s: str) -> str: seen = set() result = [] for char in s: if char not in seen: result.append(char) seen.add(char) return ''.join(result)
simplelr_Data_Structure
[ { "content": "Question:\n**Scenario**:\n\nYou are part of a team working on processing user input strings for a new text analytics tool. To ensure data integrity, you need to remove any additional occurrences of characters within the input strings, while preserving the first occurrence and original ordering.\n\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1284, "level": 1, "question": "**Scenario**:\n\nYou are part of a team working on processing user input strings for a new text analytics tool. To ensure data integrity, you need to remove any additional occurrences of characters within the input strings, while preserving the first o...
from collections import Counter def are_permutations(list1: list, list2: list) -> bool: """ Check if two lists are permutations of each other. Parameters: - list1 (list): A list of integers. - list2 (list): Another list of integers. Returns: - bool: True if the lists are permutations ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are given two lists of integers, `list1` and `list2`. Your task is to determine if these two lists are permutations of each other. Two lists are considered permutations of each other if they contain the same elements with the same frequencies, regardless of ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1285, "level": 1, "question": "### Problem Statement\n\nYou are given two lists of integers, `list1` and `list2`. Your task is to determine if these two lists are permutations of each other. Two lists are considered permutations of each other if they contain the same elements with t...
def length_of_longest_special_subarray(arr): n = len(arr) if n < 3: return 0 last_seen = {} max_length = 0 left = 0 for right in range(n): current = arr[right] if current in last_seen and last_seen[current] >= left: left = last_seen[current] + 1 ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array `arr` consisting of `n` integers. A subarray is called **special** if its length is at least `3` and all its elements are distinct. Your task is to determine the length of the longest **special** subarray in `arr`. If no such subarray exists, return `0`.\nAnswer:\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1286, "level": 1, "question": "You are given an array `arr` consisting of `n` integers. A subarray is called **special** if its length is at least `3` and all its elements are distinct. Your task is to determine the length of the longest **special** subarray in `arr`. If no such sub...
def simulate_math_operation(a, b): """ Computes the element-wise result of the formula c = a * b + a for two input lists a and b of the same length. Args: a (list): The first list of numbers. b (list): The second list of numbers. Returns: list: A list where each element c_i is ...
simplelr_Filter
[ { "content": "Question:\nIs there a way to create a Python function that simulates a mathematical operation where each element in an output array is the result of the formula `c = a * b + a`, where `a` and `b` are elements from two input arrays of the same size? Additionally, how can this function's performance...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1287, "level": 1, "question": "Is there a way to create a Python function that simulates a mathematical operation where each element in an output array is the result of the formula `c = a * b + a`, where `a` and `b` are elements from two input arrays of the same size? Additionally, ...
from collections import Counter def most_frequent_character(s: str) -> str: counts = Counter(s) max_freq = max(counts.values()) candidates = [char for char, count in counts.items() if count == max_freq] return min(candidates)
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are given a string `s` consisting of lowercase English letters. Write a function:\n\n```python\ndef most_frequent_character(s: str) -> str:\n # your implementation here\n```\n\nThe function should return the character that appears the most frequently in the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1288, "level": 1, "question": "### Problem Statement\nYou are given a string `s` consisting of lowercase English letters. Write a function:\n\n```python\ndef most_frequent_character(s: str) -> str:\n # your implementation here\n```\n\nThe function should return the character that...
def count_collections(input_dict): return sum(1 for v in input_dict.values() if isinstance(v, (list, dict)) and not v)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to count the number of collections in a given dictionary, where a collection is defined as a key with a value that is either an empty list or an empty dictionary.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1289, "level": 1, "question": "Write a python function to count the number of collections in a given dictionary, where a collection is defined as a key with a value that is either an empty list or an empty dictionary.", "split": "train" }
def is_anagram(s1, s2): return sorted(s1) == sorted(s2)
simplelr_Apps
[ { "content": "Question:\nGiven two strings s1 and s2, write a function that determines if s1 can be transformed into s2 by rearranging its characters (i.e., checking if s1 is an anagram of s2). If the lengths of the strings do not match, the function should return false.\n\nExamples:\n\n```python\nis_anagram(\"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1290, "level": 1, "question": "Given two strings s1 and s2, write a function that determines if s1 can be transformed into s2 by rearranging its characters (i.e., checking if s1 is an anagram of s2). If the lengths of the strings do not match, the function should return false.\n\nEx...
def transform_string(s, k): n = len(s) if k >= n: return s return s[k:] + s[:k]
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` containing lower case alphabets and an integer `k`, convert the string such that the first `k` characters of the string are moved to the end. If `k` is greater than the length of the string, the resultant string should be the same as the original string. Write a funct...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1291, "level": 1, "question": "Given a string `s` containing lower case alphabets and an integer `k`, convert the string such that the first `k` characters of the string are moved to the end. If `k` is greater than the length of the string, the resultant string should be the same as...
def sum_of_subsequences(n: int) -> int: """ Returns the sum of the sums of all unique subsequences for a sequence from 1 to n. """ sum_sequence = n * (n + 1) // 2 power = 2 ** (n - 1) return sum_sequence * power
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nAlice and Bob are playing a game of summing sequences. In this game, Alice selects a sequence of integers from `1` to `n`, inclusive. Bob’s task is to compute the exact sum of all unique subsequences (including the empty sequence) formed by the integers in Alice...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1292, "level": 1, "question": "### Problem Statement\n\nAlice and Bob are playing a game of summing sequences. In this game, Alice selects a sequence of integers from `1` to `n`, inclusive. Bob’s task is to compute the exact sum of all unique subsequences (including the empty sequen...
def find_first_occurrence(s, ch): return s.find(ch)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a string and a character as input and returns the index of the first occurrence of the character in the string. If the character is not found, return -1. Optimize the function for performance.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1293, "level": 1, "question": "Write a Python function that takes a string and a character as input and returns the index of the first occurrence of the character in the string. If the character is not found, return -1. Optimize the function for performance.", "split": "train" }
from typing import List def find_triplet_with_sum(arr: List[int], target: int) -> bool: n = len(arr) if n < 3: return False arr.sort() for i in range(n - 2): left = i + 1 right = n - 1 while left < right: current_sum = arr[i] + arr[left] + arr[right] ...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nYou are given an unsorted array of integers and a target sum. Your goal is to determine if there are three distinct elements in the array that add up to the given target sum. This is a common problem that requires array manipulation and u...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1294, "level": 1, "question": "### Coding Assessment Question\n\n#### Scenario\nYou are given an unsorted array of integers and a target sum. Your goal is to determine if there are three distinct elements in the array that add up to the given target sum. This is a common problem tha...
def find_max_min(arr): return (max(arr), min(arr))
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the maximum and minimum values in an array of integers using Python. The function should return both the maximum and minimum values as a tuple.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1295, "level": 1, "question": "Write a function to find the maximum and minimum values in an array of integers using Python. The function should return both the maximum and minimum values as a tuple.", "split": "train" }
from typing import List from collections import Counter def sum_of_unique(nums: List[int]) -> int: counts = Counter(nums) return sum(key for key, value in counts.items() if value == 1)
simplelr_Algorithm
[ { "content": "Question:\n### Sum of All Unique Elements\n\nYou are given an integer array `nums` where each element appears either once or exactly twice. Your task is to write a function `sum_of_unique(nums: List[int]) -> int` that returns the sum of all unique elements (elements which appear exactly once) in t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1296, "level": 1, "question": "### Sum of All Unique Elements\n\nYou are given an integer array `nums` where each element appears either once or exactly twice. Your task is to write a function `sum_of_unique(nums: List[int]) -> int` that returns the sum of all unique elements (eleme...
def merge_and_sort(arr1, arr2): # Combine the two arrays combined = arr1 + arr2 # Sort the combined array combined.sort() # Remove duplicates while maintaining order if not combined: return [] result = [combined[0]] for num in combined[1:]: if num != result[-1]: ...
simplelr_Filter
[ { "content": "Question:\nGiven two arrays of integers that overlap in their representations. Your goal is to implement a function that writes a Python program that facilitates merging these two into one orderly sequence while making sure to remove any remedial duplication. As an additional challenge, your funct...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1297, "level": 1, "question": "Given two arrays of integers that overlap in their representations. Your goal is to implement a function that writes a Python program that facilitates merging these two into one orderly sequence while making sure to remove any remedial duplication. As ...
def findPeakElement(nums): """ This function finds the index of a peak element in the input array `nums`. Args: nums (List[int]): The input list of integers. Returns: int: The index of a peak element. """ left, right = 0, len(nums) - 1 while left < right: mid = (lef...
simplelr_Taco
[ { "content": "Question:\nWrite a function `findPeakElement` which takes an integer array `nums` and returns the index of a peak element. A peak element is an element that is greater than its neighbors. The provided array has valid peaks ensured by the input conditions, where `nums[i]` is not necessarily unique....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1298, "level": 1, "question": "Write a function `findPeakElement` which takes an integer array `nums` and returns the index of a peak element. A peak element is an element that is greater than its neighbors. The provided array has valid peaks ensured by the input conditions, where `...
def reverse_string(s): return s[::-1]
simplelr_Evol
[ { "content": "Question:\nWrite a Python function that takes a string as input and returns a new string with the characters in reverse order. Ensure that the function handles all valid input characters, including letters, numbers, punctuation, and whitespace. Example input: \"Hello, World!\" Example output: \"!d...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1299, "level": 1, "question": "Write a Python function that takes a string as input and returns a new string with the characters in reverse order. Ensure that the function handles all valid input characters, including letters, numbers, punctuation, and whitespace. Example input: \"H...