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 sum_of_distinct_elements(lst): sum = 0 result = [] for element in lst: if element not in result: result.append(element) sum += element return sum
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the sum of the distinct elements in a given list of integers. You are required to implement a function that iterates through each element of the list, checks if it is already in a result list, and if not, adds it. Finally, return the sum of all elements in ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 800, "level": 1, "question": "Write a function to calculate the sum of the distinct elements in a given list of integers. You are required to implement a function that iterates through each element of the list, checks if it is already in a result list, and if not, adds it. Finally, ...
def rearrangeArray(arr): write_ptr = 0 for i in range(len(arr)): if arr[i] != 0: arr[write_ptr] = arr[i] write_ptr += 1 for i in range(write_ptr, len(arr)): arr[i] = 0
simplelr_Taco
[ { "content": "Question:\nYou are given an array of integers. Your task is to perform a specific reconstruction of the array: Move every zero to the end of the array while maintaining the relative order of the non-zero elements.\n\nWrite a function `rearrangeArray(arr)` that achieves the described rearrangement ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 801, "level": 1, "question": "You are given an array of integers. Your task is to perform a specific reconstruction of the array: Move every zero to the end of the array while maintaining the relative order of the non-zero elements.\n\nWrite a function `rearrangeArray(arr)` that ach...
from typing import List def enhanced_interpolation_search(array: List[int], search_key: int) -> int: n = len(array) if n == 0: return -1 low = 0 high = n - 1 while low <= high: if array[low] == array[high]: if array[low] == search_key: return low ...
simplelr_Data_Structure
[ { "content": "Question:\nInterpolation Search with Variations and Edge Cases\n\nYou are tasked with implementing an improved version of the Interpolation Search algorithm. The standard interpolation search works effectively on uniformly distributed values but struggles with highly skewed distributions. Your obj...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 802, "level": 1, "question": "Interpolation Search with Variations and Edge Cases\n\nYou are tasked with implementing an improved version of the Interpolation Search algorithm. The standard interpolation search works effectively on uniformly distributed values but struggles with hig...
from typing import List def total_storage(files: List[int]) -> int: return 2 * sum(files)
simplelr_Leetcode
[ { "content": "Question:\n\\[Question 4\\]: Given a list of `n` integers where each integer represents the number of files in a folder, you are tasked with writing a function that calculates the total storage space required. Each file has a size of 1 MB. Additionally, there is an overhead cost for each folder wh...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 803, "level": 1, "question": "\\[Question 4\\]: Given a list of `n` integers where each integer represents the number of files in a folder, you are tasked with writing a function that calculates the total storage space required. Each file has a size of 1 MB. Additionally, there is a...
def are_anagrams(str1, str2): # Normalize both strings: remove non-alphabetic characters and convert to lowercase normalized1 = ''.join([c.lower() for c in str1 if c.isalpha()]) normalized2 = ''.join([c.lower() for c in str2 if c.isalpha()]) # Check if sorted versions of the normalized strings are ...
simplelr_Filter
[ { "content": "Question:\nCreate a function that compares two input strings and determines if they are anagrams of one another. Be sure that your function takes into account letter case and punctuation. The function should first normalize the strings: removing any punctuation and translating all letters to lower...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 804, "level": 1, "question": "Create a function that compares two input strings and determines if they are anagrams of one another. Be sure that your function takes into account letter case and punctuation. The function should first normalize the strings: removing any punctuation an...
def removeKDigits(s, k): if k == 0: return s if k >= len(s): return "0" stack = [] for c in s: while k > 0 and stack and stack[-1] > c: stack.pop() k -= 1 stack.append(c) # Remove remaining k digits from the end if k > 0: ...
simplelr_Taco
[ { "content": "Question:\nGiven a string `str` of lowercase alphabets, the task is to complete the function `removeKDigits()` that removes exactly `k` digits from the string such that the new string formed is the smallest possible. The order of the characters in the string should remain the same.\n\nInput:\n- Th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 805, "level": 1, "question": "Given a string `str` of lowercase alphabets, the task is to complete the function `removeKDigits()` that removes exactly `k` digits from the string such that the new string formed is the smallest possible. The order of the characters in the string shoul...
import json def parse_json(json_str): return json.loads(json_str)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to parse a JSON string into a Python dictionary.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 806, "level": 1, "question": "Write a python function to parse a JSON string into a Python dictionary.", "split": "train" }
def format_integers(input_string): parts = input_string.split() formatted = ['(' + p + ')' for p in parts] return ', '.join(formatted)
simplelr_Evol
[ { "content": "Question:\nGiven a string of integers, you are required to generate and return a new string where each integer is separated by a comma and a space. Additionally, each integer should be enclosed in parentheses.\n\n### Input:\n- A string of integers separated by spaces. For example: `'1 2 3 4 5'`\n\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 807, "level": 1, "question": "Given a string of integers, you are required to generate and return a new string where each integer is separated by a comma and a space. Additionally, each integer should be enclosed in parentheses.\n\n### Input:\n- A string of integers separated by spa...
from functools import lru_cache @lru_cache(maxsize=None) def fibonacci(n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2)
simplelr_Filter
[ { "content": "Question:\nCreate a recursive Fibonacci function using Python that uses memoization to improve performance.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 808, "level": 1, "question": "Create a recursive Fibonacci function using Python that uses memoization to improve performance.", "split": "train" }
from collections import Counter def elements_with_frequency_greater_than_one(input_data): if isinstance(input_data, str): counts = Counter(input_data) seen = set() result = [] for char in input_data: if counts[char] > 1 and char not in seen: result.append...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to return a list of elements with a frequency of occurrence greater than 1. The function should be able to handle a string, list, or a dictionary as input and return the elements with a frequency greater than 1 in the same type as the input. If the input is a dictionary...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 809, "level": 1, "question": "Write a function to return a list of elements with a frequency of occurrence greater than 1. The function should be able to handle a string, list, or a dictionary as input and return the elements with a frequency greater than 1 in the same type as the i...
import itertools def generate_strings(s): if not s: return [] separators = ['_', '|'] n = len(s) if n == 1: return [s] combinations = itertools.product(separators, repeat=n-1) result = [] for combo in combinations: new_str = s[0] for i in range(n-1): ...
simplelr_Filter
[ { "content": "Question:\nStarting with the string `\"ababab\"`, I want to generate a new string by inserting either `\"_\"` or `\"|\"` between every character in the original string. For example, if I start with the string `\"ab\"`, I could generate strings like `\"a_b\"` or `\"a|b\"`. I want all possible combi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 810, "level": 1, "question": "Starting with the string `\"ababab\"`, I want to generate a new string by inserting either `\"_\"` or `\"|\"` between every character in the original string. For example, if I start with the string `\"ab\"`, I could generate strings like `\"a_b\"` or `\...
def is_consecutive_sequence(lst): # Check if input is a list if not isinstance(lst, list): return "Invalid input" # Check if all elements are integers (not including booleans) for num in lst: if type(num) is not int: return "Invalid input" # Check if the list ha...
simplelr_Taco
[ { "content": "Question:\nImplement a function to determine if a given list of integers contains a sequence of consecutive numbers. The sequence of numbers can be either increasing or decreasing, and the length of the sequence should be at least 3. If such a sequence is found, return `true`; otherwise, return `f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 811, "level": 1, "question": "Implement a function to determine if a given list of integers contains a sequence of consecutive numbers. The sequence of numbers can be either increasing or decreasing, and the length of the sequence should be at least 3. If such a sequence is found, r...
def flatten(nested_list): result = [] for element in nested_list: if isinstance(element, list): result.extend(flatten(element)) else: result.append(element) return result # Example usage nested = [1, 2, [3, 4], [5, [6, 7]]] flat = flatten(nested) print(flat) # Outpu...
simplelr_Filter
[ { "content": "Question:\nHow can I convert a nested list into a flat list in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 812, "level": 1, "question": "How can I convert a nested list into a flat list in Python?", "split": "train" }
def is_leap_year(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check if a given year is a leap year or not. A leap year is exactly divisible by 4 except for end-of-century years, which must be divisible by 400. This means that the year 2000 was a leap year, although 1900 was not. Information regarding this was not availab...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 813, "level": 1, "question": "Write a python function to check if a given year is a leap year or not. A leap year is exactly divisible by 4 except for end-of-century years, which must be divisible by 400. This means that the year 2000 was a leap year, although 1900 was not. Informat...
import csv def merge_csv(filenames, output_filename): with open(output_filename, 'w', newline='') as outfile: writer = csv.writer(outfile) first_file = True for filename in filenames: with open(filename, 'r') as infile: reader = csv.reader(infile) ...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to merge multiple CSV files into a single CSV file, ensuring that the header from the first file is included only once in the output file.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 814, "level": 1, "question": "Write a Python function to merge multiple CSV files into a single CSV file, ensuring that the header from the first file is included only once in the output file.", "split": "train" }
def longest_zero_sum_subarray(arr): sum_map = {0: -1} # Stores the first occurrence of each prefix sum current_sum = 0 max_length = 0 for i in range(len(arr)): current_sum += arr[i] if current_sum in sum_map: # Calculate the length of the subarray with sum zero ...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of `n` integers where each element is either `1` or `-1`, find the length of the longest subarray with a sum of `0`. If no such subarray exists, return `0`. For example, if the input array is `[1, -1, 1, 1, -1, -1]`, the longest subarray with a sum of `0` is `[1, -1, 1, 1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 815, "level": 1, "question": "Given an array of `n` integers where each element is either `1` or `-1`, find the length of the longest subarray with a sum of `0`. If no such subarray exists, return `0`. For example, if the input array is `[1, -1, 1, 1, -1, -1]`, the longest subarray ...
def topSellingBooks(sales_report): # Convert the sales report into a list of tuples (book, sales) book_list = list(sales_report.items()) # Sort the list in descending order based on the number of sales book_list.sort(key=lambda x: x[1], reverse=True) # Extract the top three books or fewer if there a...
simplelr_Code_Contests
[ { "content": "Question:\nA bookstore keeps track of their book sales in a weekly report. The bookstore wishes to identify the top-selling books each week. Each book has a unique title, and the sales report is a list of book titles with the number of copies sold for each title.\n\nWrite a function `topSellingBoo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 816, "level": 1, "question": "A bookstore keeps track of their book sales in a weekly report. The bookstore wishes to identify the top-selling books each week. Each book has a unique title, and the sales report is a list of book titles with the number of copies sold for each title.\...
def linear_search(array: list, query: int) -> int: for index, element in enumerate(array): if element == query: return index return -1
simplelr_Data_Structure
[ { "content": "Question:\n#### Scenario\nYou are given the task of implementing a utility function in a library that needs to search for elements within datasets. Due to the nature of these datasets, they can be large and you must handle them efficiently, even if they are not sorted. Given the constraints of not...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 817, "level": 1, "question": "#### Scenario\nYou are given the task of implementing a utility function in a library that needs to search for elements within datasets. Due to the nature of these datasets, they can be large and you must handle them efficiently, even if they are not so...
def is_rotated_version(s1, s2): if len(s1) != len(s2): return False return s2 in s1 + s1
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Question:\nYou are building a function that determines if one string is a rotated version of another string. Two strings are considered rotated versions if they have the same characters in the same order but starting from a different index.\n\n####...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 818, "level": 1, "question": "### Coding Assessment Question\n\n#### Question:\nYou are building a function that determines if one string is a rotated version of another string. Two strings are considered rotated versions if they have the same characters in the same order but starti...
def maxElement(N, A): return sum(A)
simplelr_Taco
[ { "content": "Question:\nJohn has an array A of size N consisting of integers. He wants to perform a series of operations to maximize the sum of the array's elements. In each operation, John can select any two consecutive elements and replace them with their sum. The operation is repeated until there is only on...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 819, "level": 1, "question": "John has an array A of size N consisting of integers. He wants to perform a series of operations to maximize the sum of the array's elements. In each operation, John can select any two consecutive elements and replace them with their sum. The operation ...
from typing import List def find_sorted_distinct_letters(words: List[str]) -> List[str]: """ Return a sorted list of distinct letters present in the given list of words. """ # Collect all unique characters across all words using a set comprehension all_letters = {char for word in words for char in ...
simplelr_Algorithm
[ { "content": "Question:\n### Find the Distinct Letters in a Sorted List of Words\n\n**Scenario**:\n\nYou are given a list of words and your task is to find all the distinct letters present in these words. The result should be a list of these distinct letters sorted in alphabetical order. \n\n#### Task:\n\nImple...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 820, "level": 1, "question": "### Find the Distinct Letters in a Sorted List of Words\n\n**Scenario**:\n\nYou are given a list of words and your task is to find all the distinct letters present in these words. The result should be a list of these distinct letters sorted in alphabeti...
def can_form_palindrome(s): counts = [0] * 26 # Each index represents a letter a-z for c in s: index = ord(c) - ord('a') counts[index] += 1 odd_counts = 0 for count in counts: if count % 2 != 0: odd_counts += 1 return odd_counts <= 1
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` consisting of only lowercase English letters, determine if you can rearrange the letters of `s` to form a valid palindrome. A palindrome is a word that reads the same backward as forward. If such an arrangement exists, return `true`, otherwise return `false`.\n\nA val...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 821, "level": 1, "question": "Given a string `s` consisting of only lowercase English letters, determine if you can rearrange the letters of `s` to form a valid palindrome. A palindrome is a word that reads the same backward as forward. If such an arrangement exists, return `true`, ...
def format_product(product, price): return f"*{product}* (${price})"
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in two strings, one for the product name and another for the price. The function should return a formatted string that includes the product name with an asterisk (*) before and after it, and the price in parentheses, for example: \"*Product Name* ($Price)\"....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 822, "level": 1, "question": "Create a function that takes in two strings, one for the product name and another for the price. The function should return a formatted string that includes the product name with an asterisk (*) before and after it, and the price in parentheses, for exa...
def sort_strings_by_length_desc(strings): return sorted(strings, key=lambda x: len(x), reverse=True)
simplelr_Filter
[ { "content": "Question:\nProvide a Python function that takes a list of strings and returns a new list with the strings sorted in descending order based on their length.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 823, "level": 1, "question": "Provide a Python function that takes a list of strings and returns a new list with the strings sorted in descending order based on their length.", "split": "train" }
import math def common_divisors(a, b): # Check if a and b are integers if type(a) is not int or type(b) is not int: return [] # Check if a and b are positive if a <= 0 or b <= 0: return [] # Compute the greatest common divisor gcd_value = math.gcd(a, b) # Find...
simplelr_Filter
[ { "content": "Question:\nI'll describe a problem and I want you to write a Python function to solve it. Here's the description:\n\n**Problem:**\n\nWrite a Python function to find the common divisors of two input integers, including 1 and the numbers themselves. \n\nFor example, given two numbers 12 and 18, the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 824, "level": 1, "question": "I'll describe a problem and I want you to write a Python function to solve it. Here's the description:\n\n**Problem:**\n\nWrite a Python function to find the common divisors of two input integers, including 1 and the numbers themselves. \n\nFor example,...
def reverse_words(text): """Reverses the order of words in a string. Args: text: The input string. Returns: The string with words in reverse order. """ words = text.split() return " ".join(words[::-1])
simplelr_Filter
[ { "content": "Question:\n**Instructions:\n\nWrite a code in Python that takes the following input as a string of words, and return the words in reverse order.**\n\n**Input:**\n\nThis is a sample string\n\n**Expected Output:**\n\nstring sample a is This\n\n\n```python\ndef reverse_words(text):\n \"\"\"Reverses ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 825, "level": 1, "question": "**Instructions:\n\nWrite a code in Python that takes the following input as a string of words, and return the words in reverse order.**\n\n**Input:**\n\nThis is a sample string\n\n**Expected Output:**\n\nstring sample a is This\n\n\n```python\ndef rever...
import heapq def kth_smallest(matrix, k): if not matrix or k == 0: return None # Handle edge cases heap = [] rows = len(matrix) # Initialize the heap with the first element of each row for i in range(rows): if matrix[i]: # Ensure the row is not empty heapq.he...
simplelr_Leetcode
[ { "content": "Question:\nGiven a 2D integer array `matrix`, where each row is sorted in non-decreasing order, implement a function to find the `k-th` smallest element in the matrix. The function should return the k-th smallest element while maintaining the sorting properties of each row.\nAnswer:\nLet's think s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 826, "level": 1, "question": "Given a 2D integer array `matrix`, where each row is sorted in non-decreasing order, implement a function to find the `k-th` smallest element in the matrix. The function should return the k-th smallest element while maintaining the sorting properties of...
from collections import deque def magic_sequence(n, k): if n == 1: return 1 if n == 2: return 2 dq = deque([1, 2], maxlen=k) current_sum = sum(dq) for _ in range(3, n + 1): next_element = current_sum if len(dq) == k: popped = dq.popleft() ...
simplelr_Codeforces
[ { "content": "Question:\nIn the Kingdom of Far Far Away lives a brilliant mathematician named Alice. She loves playing with numbers and has recently invented a new number sequence called the \"Magic Sequence\". A Magic Sequence is defined as follows:\n\n- The first element of the sequence is always 1.\n- The se...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 827, "level": 1, "question": "In the Kingdom of Far Far Away lives a brilliant mathematician named Alice. She loves playing with numbers and has recently invented a new number sequence called the \"Magic Sequence\". A Magic Sequence is defined as follows:\n\n- The first element of t...
def reverse_words(s: str) -> str: words = s.split() reversed_words = words[::-1] return ' '.join(reversed_words)
simplelr_Algorithm
[ { "content": "Question:\n### Reverse Words in a String\n\n#### Problem Statement\nYou are required to implement a function that reverses the order of words in a given string. The function should maintain the initial order of letters within each word and remove any additional spaces at the beginning and end, als...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 828, "level": 1, "question": "### Reverse Words in a String\n\n#### Problem Statement\nYou are required to implement a function that reverses the order of words in a given string. The function should maintain the initial order of letters within each word and remove any additional sp...
def max_profit(prices): if len(prices) < 2: return 0 min_price = prices[0] max_profit = 0 for price in prices[1:]: current_profit = price - min_price if current_profit > max_profit: max_profit = current_profit if price < min_price: min_price = pric...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the maximum profit from a given list of stock prices where you can only buy and sell a stock once. The function should return the maximum profit possible. If no profit can be made, the function should return 0.\nAnswer:\nLet's think step by step.\n", "role":...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 829, "level": 1, "question": "Write a function to find the maximum profit from a given list of stock prices where you can only buy and sell a stock once. The function should return the maximum profit possible. If no profit can be made, the function should return 0.", "split": "tra...
def can_transform_by_reversing_substring(s, t): if len(s) != len(t): return False if s == t: return True i = 0 n = len(s) while i < n and s[i] == t[i]: i += 1 j = n - 1 while j >= 0 and s[j] == t[j]: j -= 1 substr_s = s[i:j+1] substr_t = t[i:j+1] r...
simplelr_Leetcode
[ { "content": "Question:\nYou are given two strings, `s` and `t`. Determine if `s` can be transformed into `t` by reversing any one of its substrings exactly once. Return `true` if it is possible, otherwise, return `false`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 830, "level": 1, "question": "You are given two strings, `s` and `t`. Determine if `s` can be transformed into `t` by reversing any one of its substrings exactly once. Return `true` if it is possible, otherwise, return `false`.", "split": "train" }
import tempfile def manage_temp_files_and_dirs(text_lines: list) -> str: with tempfile.TemporaryDirectory() as temp_dir: with tempfile.NamedTemporaryFile(mode='w+', dir=temp_dir) as temp_file: for line in text_lines: temp_file.write(line + '\n') temp_file.seek(0) ...
simplelr_Docs
[ { "content": "Question:\n**Question: Temporary File and Directory Management in Python**\n\nYou are tasked with writing a Python function, `manage_temp_files_and_dirs`, that performs the following operations:\n\n1. Creates a temporary directory.\n2. Within this temporary directory, creates a temporary file and ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 831, "level": 1, "question": "**Question: Temporary File and Directory Management in Python**\n\nYou are tasked with writing a Python function, `manage_temp_files_and_dirs`, that performs the following operations:\n\n1. Creates a temporary directory.\n2. Within this temporary direct...
import pandas as pd import numpy as np def fill_missing_values(dataframe): df = dataframe.copy() for col in df.columns: if pd.api.types.is_numeric_dtype(df[col]): mean_val = df[col].mean() df[col] = df[col].fillna(mean_val) return df
simplelr_Package
[ { "content": "Question:\nGiven a pandas DataFrame representing sensor data, write a function to fill any missing (NaN) values in numeric columns with the mean of their respective columns. Additionally, if a column is non-numeric or contains only NaN values, it should be left unchanged. Return the modified DataF...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 832, "level": 1, "question": "Given a pandas DataFrame representing sensor data, write a function to fill any missing (NaN) values in numeric columns with the mean of their respective columns. Additionally, if a column is non-numeric or contains only NaN values, it should be left un...
import math def is_prime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False max_divisor = math.isqrt(n) for d in range(3, max_divisor + 1, 2): if n % d == 0: return False return True
simplelr_Filter
[ { "content": "Question:\nCan you write a Python function to determine if a number is a prime number? I'm looking for a simple and efficient way to check this for numbers in a large range.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 833, "level": 1, "question": "Can you write a Python function to determine if a number is a prime number? I'm looking for a simple and efficient way to check this for numbers in a large range.", "split": "train" }
def validate_account_number(account_number): return account_number.lstrip('0') or '0'
simplelr_Codeforces
[ { "content": "Question:\nA private bank uses a nested system of account numbers to identify its clients. Each account number consists of a series of digits. Sometimes, due to network errors, zeros get added to the start of these account numbers. \n\nYour task is to help the bank implement a function to validate...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 834, "level": 1, "question": "A private bank uses a nested system of account numbers to identify its clients. Each account number consists of a series of digits. Sometimes, due to network errors, zeros get added to the start of these account numbers. \n\nYour task is to help the ban...
import csv def analyze_books(csv_filepath: str) -> dict: total_books = 0 sum_ratings = 0.0 highest_rating = -1.0 highest_title = "" genre_data = {} try: with open(csv_filepath, 'r') as csvfile: reader = csv.reader(csvfile) next(reader) # Skip the header row ...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Task\nYou are required to write a Python program that processes data from a CSV file containing information about various books and their attributes, and calculates specific metrics based on the data.\n\n#### Function Specifications\nWrite a functi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 835, "level": 1, "question": "### Coding Assessment Question\n\n#### Task\nYou are required to write a Python program that processes data from a CSV file containing information about various books and their attributes, and calculates specific metrics based on the data.\n\n#### Funct...
def count_positive_numbers(matrix): count = 0 for row in matrix: for num in row: if num > 0: count += 1 return count
simplelr_Taco
[ { "content": "Question:\n# Task\nGiven a matrix of integers, return the count of positive numbers in the matrix. Positive numbers are those greater than zero.\n\n# Example\n\nFor matrix = \n```\n[ \n [ -1, 2, 3],\n [ 4, 5, -6],\n [ 7, -8, 9]\n]\n```\nthe output should be `6`.\n\nExplanation:\nThe positive ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 836, "level": 1, "question": "# Task\nGiven a matrix of integers, return the count of positive numbers in the matrix. Positive numbers are those greater than zero.\n\n# Example\n\nFor matrix = \n```\n[ \n [ -1, 2, 3],\n [ 4, 5, -6],\n [ 7, -8, 9]\n]\n```\nthe output should be `...
def divideList(lst, n): length = len(lst) q, rem = divmod(length, n) result = [] start = 0 for i in range(n): if i < rem: end = start + q + 1 else: end = start + q result.append(lst[start:end]) start = end return result
simplelr_Filter
[ { "content": "Question:\nWrite a function 'divideList' which takes a list of integers and an integer 'n', and divides the list into 'n' parts of roughly equal size. The elements should remain in their original order in the sublists.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 837, "level": 1, "question": "Write a function 'divideList' which takes a list of integers and an integer 'n', and divides the list into 'n' parts of roughly equal size. The elements should remain in their original order in the sublists.", "split": "train" }
def optimized_euler_totient(n: int) -> int: if n == 1: return 1 result = n # Handle the factor of 2 if n % 2 == 0: result = result - result // 2 while n % 2 == 0: n = n // 2 # Check for odd factors up to sqrt(n) p = 3 while p * p <= n: if n % p == ...
simplelr_Data_Structure
[ { "content": "Question:\n## Coding Assessment Question\n\n### Problem Description\nIn this task, you are required to implement a more optimized variant of Euler's Totient Function. Euler's Totient Function, ϕ(n), counts the number of integers between 1 and n inclusive, which are coprime to n. Two numbers are sa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 838, "level": 1, "question": "## Coding Assessment Question\n\n### Problem Description\nIn this task, you are required to implement a more optimized variant of Euler's Totient Function. Euler's Totient Function, ϕ(n), counts the number of integers between 1 and n inclusive, which ar...
def two_sum(nums, target): seen = {} for index, num in enumerate(nums): complement = target - num if complement in seen: return [seen[complement], index] seen[num] = index return []
simplelr_Filter
[ { "content": "Question:\nCan you explain the \"Two Sum\" problem and provide a solution in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 839, "level": 1, "question": "Can you explain the \"Two Sum\" problem and provide a solution in Python?", "split": "train" }
def compress_text(text: str) -> str: if not text: return "" result = [] current_char = text[0] count = 1 for char in text[1:]: if char == current_char: count += 1 else: result.append(f"{current_char}{count}") current_char = char ...
simplelr_Algorithm
[ { "content": "Question:\n### Implement a Basic Text Compression Algorithm\n\n**Context**:\nYou are developing a basic software tool to compress text data to save storage space. One simple way to compress text is by using Run-Length Encoding (RLE). Run-Length Encoding is a form of lossless data compression in wh...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 840, "level": 1, "question": "### Implement a Basic Text Compression Algorithm\n\n**Context**:\nYou are developing a basic software tool to compress text data to save storage space. One simple way to compress text is by using Run-Length Encoding (RLE). Run-Length Encoding is a form ...
from typing import List def josephus(int_list: List[int], skip: int) -> List[int]: current_list = list(int_list) result = [] current_pos = 0 n = len(current_list) while n > 0: remove_index = (current_pos + skip - 1) % n removed = current_list.pop(remove_index) result.append(...
simplelr_Data_Structure
[ { "content": "Question:\nYou are tasked with solving a variant of the classic Josephus problem. In this problem, you are given a list of individuals sitting in a circular formation. Starting from the first individual, you need to remove every k-th individual from the circle. This process continues until all ind...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 841, "level": 1, "question": "You are tasked with solving a variant of the classic Josephus problem. In this problem, you are given a list of individuals sitting in a circular formation. Starting from the first individual, you need to remove every k-th individual from the circle. Th...
def is_balanced(input_str: str) -> bool: """ Check if the input string has balanced parentheses, brackets, and curly braces. """ open_to_close = {'(': ')', '[': ']', '{': '}'} stack = [] for char in input_str: if char in open_to_close: stack.append(open_to_close[char]) ...
simplelr_Evol
[ { "content": "Question:\nWrite a function that determines if a given string contains balanced parentheses, brackets, and curly braces. The function should return True if the string is balanced and False otherwise. Consider the provided incorrect sample code and fix any errors:\n\ndef faulty_is_balanced(input_st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 842, "level": 1, "question": "Write a function that determines if a given string contains balanced parentheses, brackets, and curly braces. The function should return True if the string is balanced and False otherwise. Consider the provided incorrect sample code and fix any errors:\...
def calculate_review_stats(reviews: list[dict]) -> dict: product_stats = {} for review in reviews: product_id = review['product_id'] rating = review['rating'] if product_id not in product_stats: product_stats[product_id] = { 'sum_ratings': rating, ...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\nYou are a backend engineer tasked with developing new functionalities for a popular customer review platform. Your goal is to demonstrate your ability to handle data processing and aggregation by implementing a function that efficiently calculates aggre...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 843, "level": 1, "question": "### Coding Assessment Question\n\nYou are a backend engineer tasked with developing new functionalities for a popular customer review platform. Your goal is to demonstrate your ability to handle data processing and aggregation by implementing a function...
def is_perfect_square(n): if n < 0: return False low = 0 high = n while low <= high: mid = (low + high) // 2 mid_sq = mid * mid if mid_sq == n: return True elif mid_sq < n: low = mid + 1 else: high = mid - 1 return F...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that checks if a given number is a perfect square. A perfect square is an integer that is the square of an integer. Given a positive integer `n`, your function should return `True` if `n` is a perfect square, and `False` otherwise.\nAnswer:\nLet's think step by step.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 844, "level": 1, "question": "Create a function that checks if a given number is a perfect square. A perfect square is an integer that is the square of an integer. Given a positive integer `n`, your function should return `True` if `n` is a perfect square, and `False` otherwise.", ...
from ipaddress import IPv6Address, AddressValueError def is_valid_ipv6_address(address): try: IPv6Address(address) return True except AddressValueError: return False
simplelr_Filter
[ { "content": "Question:\nHow can I write a Python function to determine if a given IPv6 address is valid?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 845, "level": 1, "question": "How can I write a Python function to determine if a given IPv6 address is valid?", "split": "train" }
def power_set(items): """ Given a collection of items, find all possible subsets of the collection, including the empty set and the set itself. For example: power_set([1,2,3]) == [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] """ result = [[]] for item in items: new_...
simplelr_Filter
[ { "content": "Question:\nThe problem I need to solve is:\n\n**Given a collection of items, find all possible subsets of the collection, including the empty set and the set itself. This is known as the power set of the collection.**\n\n\n\n```python\ndef power_set(items):\n \"\"\"\n Given a collection of i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 846, "level": 1, "question": "The problem I need to solve is:\n\n**Given a collection of items, find all possible subsets of the collection, including the empty set and the set itself. This is known as the power set of the collection.**\n\n\n\n```python\ndef power_set(items):\n \...
from typing import List def four_sum(arr: List[int], target: int) -> List[List[int]]: arr.sort() res = [] n = len(arr) for i in range(n - 3): if i > 0 and arr[i] == arr[i-1]: continue for j in range(i + 1, n - 2): if j != i + 1 and arr[j] == arr[j-1]: ...
simplelr_Evol
[ { "content": "Question:\nWrite a function that receives an array of integers and a target sum. The function should return all unique quadruplets (four-element subsets) from the array that add up to the target sum. The solution set must not contain duplicate quadruplets.\n\nExample:\n```python\nInput: arr = [1, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 847, "level": 1, "question": "Write a function that receives an array of integers and a target sum. The function should return all unique quadruplets (four-element subsets) from the array that add up to the target sum. The solution set must not contain duplicate quadruplets.\n\nExam...
def sum_of_fibonacci(n): a, b = 0, 1 total = 0 for _ in range(n): total += a a, b = b, a + b return total
simplelr_Filter
[ { "content": "Question:\nDevelop a Python function to calculate the sum of the first 'n' Fibonacci numbers. 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 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 848, "level": 1, "question": "Develop a Python function to calculate the sum of the first 'n' Fibonacci numbers. 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 10 Fibonacci n...
def generate_series(length, start, pattern): if length <= 0: return [] series = [] if pattern == 'arithmetic': current = start for _ in range(length): series.append(current) current += 1 elif pattern == 'fibonacci': if length == 1: ...
simplelr_Taco
[ { "content": "Question:\nWrite a function `generate_series` that takes in three parameters: `length`, `start`, and `pattern`.\n\n- `length` (an integer): The length of the series to be generated.\n- `start` (an integer): The starting number of the series.\n- `pattern` (a string): Describing the pattern to follo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 849, "level": 1, "question": "Write a function `generate_series` that takes in three parameters: `length`, `start`, and `pattern`.\n\n- `length` (an integer): The length of the series to be generated.\n- `start` (an integer): The starting number of the series.\n- `pattern` (a string...
from typing import List, Tuple def find_pairs(numbers: List[int], targetSum: int) -> List[Tuple[int, int]]: numbers_sorted = sorted(numbers) left = 0 right = len(numbers_sorted) - 1 result = [] while left < right: a = numbers_sorted[left] b = numbers_sorted[right] curre...
simplelr_Taco
[ { "content": "Question:\nAlice and Bob are two friends who enjoy solving number problems. Alice gives Bob a list of integers and a specific sum value called \"targetSum\". Bob's task is to find all unique pairs of integers in the list that add up to the targetSum.\n\nWrite a function to help Bob solve this prob...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 850, "level": 1, "question": "Alice and Bob are two friends who enjoy solving number problems. Alice gives Bob a list of integers and a specific sum value called \"targetSum\". Bob's task is to find all unique pairs of integers in the list that add up to the targetSum.\n\nWrite a fu...
def square_numbers(s): return ','.join(str(int(x)**2) for x in s.split(','))
simplelr_Taco
[ { "content": "Question:\nYou are given a string containing a list of comma-separated integers. Your task is to return a string where each number is replaced by the square of that number, and the transformed numbers are presented in the original order.\n\nFor example:\n```\n\"1,2,3,4,5\" --> \"1,4,9,16,25\"\n`...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 851, "level": 1, "question": "You are given a string containing a list of comma-separated integers. Your task is to return a string where each number is replaced by the square of that number, and the transformed numbers are presented in the original order.\n\nFor example:\n```\n\"1,...
def longest_substring_without_repeating_characters(s): left = 0 max_length = 0 max_start = 0 char_index_map = {} for right in range(len(s)): char = s[right] if char in char_index_map and char_index_map[char] >= left: left = char_index_map[char] + 1 char_index...
simplelr_Evol
[ { "content": "Question:\nWrite a function in Python that takes a string as input and returns the longest substring without repeating characters. Provide the function signature and a brief explanation of your approach.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 852, "level": 1, "question": "Write a function in Python that takes a string as input and returns the longest substring without repeating characters. Provide the function signature and a brief explanation of your approach.", "split": "train" }
def find_peak_elements(nums): peaks = [] n = len(nums) for i in range(n): if i == 0: if n == 1: peaks.append(nums[i]) else: if nums[i] > nums[i + 1]: peaks.append(nums[i]) elif i == n - 1: if nums[i] > nu...
simplelr_Apps
[ { "content": "Question:\nGiven a list of integers, write a function `find_peak_elements(nums)` to return all the *peak elements*. A peak element is an element that is greater than its neighbors. For example, in the array `nums = [1, 2, 3, 1, 5, 6, 4]`, the peak elements are `[3, 6]` because `3` is greater than ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 853, "level": 1, "question": "Given a list of integers, write a function `find_peak_elements(nums)` to return all the *peak elements*. A peak element is an element that is greater than its neighbors. For example, in the array `nums = [1, 2, 3, 1, 5, 6, 4]`, the peak elements are `[3...
def two_sum(nums, target): seen = {} for i, num in enumerate(nums): complement = target - num if complement in seen: return [seen[complement], i] seen[num] = i return []
simplelr_Filter
[ { "content": "Question:\nThis is a coding problem I am working on.\n\nYou are given an array of integers `nums` and an integer `target`. You must return the indices of the two numbers that add up to the target.\n\nYou may assume that each input will have exactly one solution, and you may not use the same elemen...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 854, "level": 1, "question": "This is a coding problem I am working on.\n\nYou are given an array of integers `nums` and an integer `target`. You must return the indices of the two numbers that add up to the target.\n\nYou may assume that each input will have exactly one solution, a...
from typing import List def count(coins: List[int], value: int) -> int: if value < 0: return 0 if value == 0: return 1 valid_coins = [c for c in coins if c > 0] if not valid_coins: return 0 dp = [0] * (value + 1) dp[0] = 1 # Base case: one way to make 0 cents for co...
simplelr_Data_Structure
[ { "content": "Question:\nYou are given a specific value `value` in cents, and a list of coin denominations `coins`. Your task is to write a function that computes the number of different ways to make up that value using the coins provided. The order of the coins does not matter.\n\n### Function Signature\n\n```...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 855, "level": 1, "question": "You are given a specific value `value` in cents, and a list of coin denominations `coins`. Your task is to write a function that computes the number of different ways to make up that value using the coins provided. The order of the coins does not matter...
def range_sum(nums, lower, upper): total = 0 for num in nums: if lower <= num <= upper: total += num return total
simplelr_Package
[ { "content": "Question:\nYou are required to write a function called `range_sum` that calculates the sum of all numbers within a given range in a list. The function will take a list of integers and two additional integers representing the lower and upper bounds of the range, inclusive.\n\nYour function signatur...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 856, "level": 1, "question": "You are required to write a function called `range_sum` that calculates the sum of all numbers within a given range in a list. The function will take a list of integers and two additional integers representing the lower and upper bounds of the range, in...
import json import os def order_entry_to_json(): # Prompt the user to enter the product name. product_name = input("Enter the product name: ") # Prompt the user to enter the quantity. quantity = int(input("Enter the quantity: ")) # Prompt the user to enter the price per unit. price = ...
simplelr_Package
[ { "content": "Question:\nYou are required to write a function named `order_entry_to_json` which will allow users to add information about a product order to a JSON file. The function should perform the following operations:\n\n1. Prompt the user to enter the product name.\n2. Prompt the user to enter the quanti...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 857, "level": 1, "question": "You are required to write a function named `order_entry_to_json` which will allow users to add information about a product order to a JSON file. The function should perform the following operations:\n\n1. Prompt the user to enter the product name.\n2. P...
def num_subarray_product_less_than_k(nums, k): if k <= 0: return 0 left = 0 product = 1 count = 0 for right in range(len(nums)): product *= nums[right] while product >= k and left <= right: product /= nums[left] left += 1 count += right - left ...
simplelr_Evol
[ { "content": "Question:\nGiven an integer array `nums` and an integer `k`, return the number of contiguous subarrays where the product of all the elements in the subarray is less than `k`.\n\nExample 1:\nInput: nums = [10, 5, 2, 6], k = 100\nOutput: 8\nExplanation: The 8 subarrays that have a product less than ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 858, "level": 1, "question": "Given an integer array `nums` and an integer `k`, return the number of contiguous subarrays where the product of all the elements in the subarray is less than `k`.\n\nExample 1:\nInput: nums = [10, 5, 2, 6], k = 100\nOutput: 8\nExplanation: The 8 subarr...
def normalize_list(values: list) -> list: min_val = min(values) max_val = max(values) if min_val == max_val: return [0.0] * len(values) else: denominator = max_val - min_val return [(x - min_val) / denominator for x in values]
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are to implement a function that normalizes a list of numerical values. Normalization is a process that adjusts the values in a dataset to a common scale, typically within the range [0, 1], without distorting the differences in the ranges of values.\n\n### The...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 859, "level": 1, "question": "### Problem Statement\nYou are to implement a function that normalizes a list of numerical values. Normalization is a process that adjusts the values in a dataset to a common scale, typically within the range [0, 1], without distorting the differences i...
def fibonacci(n): if n <= 0: return [] elif n == 1: return [0] elif n == 2: return [0, 1] else: prev = fibonacci(n - 1) next_num = prev[-1] + prev[-2] return prev + [next_num]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that calculates the Fibonacci sequence up to a given number n using recursion. The function should return the sequence in a list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 860, "level": 1, "question": "Create a function that calculates the Fibonacci sequence up to a given number n using recursion. The function should return the sequence in a list.", "split": "train" }
def find_max(lst): if not lst: return None return max(lst) # Test cases test_cases = [ ([], None), ([-1, -2, -3], -1), ([1, -2, 3, -4], 3), ([5], 5) ] for input_list, expected_output in test_cases: result = find_max(input_list) print(f"Input: {input_list}, Expected: {expected_o...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to find the maximum value in a list of integers. The function should be able to handle an empty list by returning `None`. Ensure your function is efficient and concise. Additionally, provide a simple way to test the function with various inputs, including an empt...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 861, "level": 1, "question": "Write a Python function to find the maximum value in a list of integers. The function should be able to handle an empty list by returning `None`. Ensure your function is efficient and concise. Additionally, provide a simple way to test the function with...
def four_sum(arr, target): arr.sort() res = [] n = len(arr) for i in range(n): if i > 0 and arr[i] == arr[i-1]: continue for j in range(i+1, n): if j != i+1 and arr[j] == arr[j-1]: continue rem = target - arr[i] - arr[j] k =...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `arr`, and an integer `target`, find all unique quadruplets `[a, b, c, d]` in the array which gives the sum of `target`.\n\nNotice that the solution set must not contain duplicate quadruplets. \n\nWrite a function that returns an array of all the quadruplets. ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 862, "level": 1, "question": "Given an array of integers `arr`, and an integer `target`, find all unique quadruplets `[a, b, c, d]` in the array which gives the sum of `target`.\n\nNotice that the solution set must not contain duplicate quadruplets. \n\nWrite a function that returns...
def max_subarray_sum(arr): if not arr: return 0 current_max = max_sum = arr[0] for x in arr[1:]: current_max = max(x, current_max + x) max_sum = max(max_sum, current_max) return max_sum
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the maximum sum of a contiguous subarray within a one-dimensional array of numbers. This function should efficiently compute the sum without recalculating sums of smaller subarrays multiple times.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 863, "level": 1, "question": "Write a function to find the maximum sum of a contiguous subarray within a one-dimensional array of numbers. This function should efficiently compute the sum without recalculating sums of smaller subarrays multiple times.", "split": "train" }
def sort_and_reformat_dates(dates: list) -> list: sorted_dates = sorted(dates) formatted_dates = [] for date in sorted_dates: year, month, day = date.split('-') formatted_dates.append(f"{day}-{month}-{year}") return formatted_dates
simplelr_Apps
[ { "content": "Question:\nYou have a list of strings representing dates in the format \"YYYY-MM-DD\". Write a function that accepts this list and returns a new list where the dates are sorted from the oldest to the newest. However, you must reformat the dates to \"DD-MM-YYYY\" in the resulting list.\n\nFor examp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 864, "level": 1, "question": "You have a list of strings representing dates in the format \"YYYY-MM-DD\". Write a function that accepts this list and returns a new list where the dates are sorted from the oldest to the newest. However, you must reformat the dates to \"DD-MM-YYYY\" i...
def multiply(a, b): return a * b # Example usage: print(multiply(5, 10)) # Output: 50
simplelr_Filter
[ { "content": "Question:\nI am new to Python and I have a simple requirement. I need to create a function that takes two numbers as input, multiplies them, and returns the result. How can I do this in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 865, "level": 1, "question": "I am new to Python and I have a simple requirement. I need to create a function that takes two numbers as input, multiplies them, and returns the result. How can I do this in Python?", "split": "train" }
def count_vowels(s): vowels = {'a', 'e', 'i', 'o', 'u'} count = 0 for char in s.lower(): if char in vowels: count += 1 return count # Example usage: print(count_vowels("Hello, World!")) # Output: 3
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python function that takes a string and returns the number of vowels in it? Please include a simple example of how to use this function.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 866, "level": 1, "question": "Can you provide a Python function that takes a string and returns the number of vowels in it? Please include a simple example of how to use this function.", "split": "train" }
def unique_elements(lst): seen = set() unique = [] for item in lst: if item not in seen: seen.add(item) unique.append(item) return unique # Example usage with the first 10 powers of 2 powers_of_two = [2**i for i in range(10)] # Generates 2^0 to 2^9 unique_powers = uniqu...
simplelr_Filter
[ { "content": "Question:\nPlease write a Python 3 function that takes in a list of integers and returns a new list containing only the unique elements from the original list, in the order they first appeared. Additionally, include a code snippet that demonstrates using the function to compute the unique elements...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 867, "level": 1, "question": "Please write a Python 3 function that takes in a list of integers and returns a new list containing only the unique elements from the original list, in the order they first appeared. Additionally, include a code snippet that demonstrates using the funct...
import math from typing import List def jump_search(arr: List[int], target: int) -> int: if not arr: return -1 n = len(arr) m = int(math.sqrt(n)) left = 0 right = m while right < n and arr[right] < target: left = right right += m right = min(right...
simplelr_Data_Structure
[ { "content": "Question:\n### Jump Search Assessment Question\n\n**Problem Statement**:\nYou are tasked with implementing a jumping-based search function to find an element in a large, sorted list. This will test your understanding of the jump search algorithm, and your ability to handle edge cases and ensure op...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 868, "level": 1, "question": "### Jump Search Assessment Question\n\n**Problem Statement**:\nYou are tasked with implementing a jumping-based search function to find an element in a large, sorted list. This will test your understanding of the jump search algorithm, and your ability ...
def sort_points(points: list) -> list: return sorted(points, key=lambda point: point[0]**2 + point[1]**2)
simplelr_Algorithm
[ { "content": "Question:\nSorting Points Based on Distance\n\n#### Problem Description\nGiven a list of points in a 2D plane, sort them based on their distance from the origin (0, 0). If two points have the same distance, maintain their relative order from the input list.\n\n**Input**: \n1. `points` (List[Tuple[...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 869, "level": 1, "question": "Sorting Points Based on Distance\n\n#### Problem Description\nGiven a list of points in a 2D plane, sort them based on their distance from the origin (0, 0). If two points have the same distance, maintain their relative order from the input list.\n\n**I...
from typing import List def has_pair_with_sum(array: List[int], target: int) -> bool: seen = set() for num in array: complement = target - num if complement in seen: return True seen.add(num) return False
simplelr_Taco
[ { "content": "Question:\nYou are given an array of integers and an integer target. Your task is to determine if there are two distinct indices `i` and `j` in the array such that the sum of the elements at these indices is equal to the target.\n\nConsider this example...\n\narray = [2, 7, 11, 15]\ntarget = 9\n\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 870, "level": 1, "question": "You are given an array of integers and an integer target. Your task is to determine if there are two distinct indices `i` and `j` in the array such that the sum of the elements at these indices is equal to the target.\n\nConsider this example...\n\narra...
from collections import deque def can_finish_courses(n, prerequisites): # Build the adjacency list and in-degree array adj = [[] for _ in range(n)] in_degree = [0] * n for a, b in prerequisites: adj[b].append(a) in_degree[a] += 1 # Initialize queue with nodes of in_degree 0 qu...
simplelr_Leetcode
[ { "content": "Question:\nThere is a list of `n` courses labeled from `0` to `n - 1`. You are given an array `prerequisites` where `prerequisites[i] = [a_i, b_i]` indicates that you must complete course `b_i` before you can take course `a_i`. You want to find out if it is possible to finish all courses given the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 871, "level": 1, "question": "There is a list of `n` courses labeled from `0` to `n - 1`. You are given an array `prerequisites` where `prerequisites[i] = [a_i, b_i]` indicates that you must complete course `b_i` before you can take course `a_i`. You want to find out if it is possib...
def longest_common_prefix(strs): if not strs: return "" shortest_str = min(strs, key=lambda x: len(x)) for i in range(len(shortest_str)): current_char = shortest_str[i] for string in strs: if string[i] != current_char: return shortest_str[:i] ...
simplelr_Filter
[ { "content": "Question:\nHere is the problem: \n\nFind the length of the longest common prefix of the given array of strings `strs`.\n\nExample 1:\n\nInput: strs = [\"flower\",\"flow\",\"flight\"]\nOutput: \"fl\"\n\nExample 2:\n\nInput: strs = [\"dog\",\"racecar\",\"car\"]\nOutput: \"\"\n\nExample 3:\n\nInput: ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 872, "level": 1, "question": "Here is the problem: \n\nFind the length of the longest common prefix of the given array of strings `strs`.\n\nExample 1:\n\nInput: strs = [\"flower\",\"flow\",\"flight\"]\nOutput: \"fl\"\n\nExample 2:\n\nInput: strs = [\"dog\",\"racecar\",\"car\"]\nOut...
def total_time(tasks, breakTime): if not tasks: return 0 return sum(tasks) + (len(tasks) - 1) * breakTime
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of integers representing tasks, where each integer represents the duration of a task in minutes. There is also an integer `breakTime` that represents the mandatory break after each task. Return the minimum amount of time required to complete all the tasks if the tas...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 873, "level": 1, "question": "You are given a list of integers representing tasks, where each integer represents the duration of a task in minutes. There is also an integer `breakTime` that represents the mandatory break after each task. Return the minimum amount of time required to...
def sum_values(dict_list, key): return sum(d.get(key, 0) for d in dict_list)
simplelr_Filter
[ { "content": "Question:\nI have two python dictionaries and I'm trying to get the sum of the values for a given key across both dictionaries. What's the best way to do this? \n\nExample:\n```\ndict1 = {'a': 2, 'b': 3, 'c': 4}\ndict2 = {'a': 1, 'b': 1, 'd': 5}\n```\n\nIf I wanted to sum the values for the key `'...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 874, "level": 1, "question": "I have two python dictionaries and I'm trying to get the sum of the values for a given key across both dictionaries. What's the best way to do this? \n\nExample:\n```\ndict1 = {'a': 2, 'b': 3, 'c': 4}\ndict2 = {'a': 1, 'b': 1, 'd': 5}\n```\n\nIf I wante...
import itertools def all_combinations(s, length=None): """ Generates all possible combinations of a given string's characters. Args: s (str): The input string. length (int, optional): The length of combinations to generate. Defaults to None, which generates combinations of all possible...
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that generates a list of all possible combinations of a given string's characters?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 875, "level": 1, "question": "How can I create a Python function that generates a list of all possible combinations of a given string's characters?", "split": "train" }
def num_ways_to_tile(n: int) -> int: if n == 1: return 1 elif n == 2: return 2 a, b = 1, 2 for _ in range(3, n + 1): c = a + b a, b = b, c return b
simplelr_Algorithm
[ { "content": "Question:\n## Scenario\nTo enhance your understanding of dynamic programming and combinatorics, you will implement an algorithm that efficiently counts the number of ways to tile a 2 x n grid using 1 x 2 and 2 x 1 tiles. This problem requires both mathematical insight and programming skills to opt...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 876, "level": 1, "question": "## Scenario\nTo enhance your understanding of dynamic programming and combinatorics, you will implement an algorithm that efficiently counts the number of ways to tile a 2 x n grid using 1 x 2 and 2 x 1 tiles. This problem requires both mathematical ins...
def find_unique_number(nums): unique = 0 for num in nums: unique ^= num return unique
simplelr_Evol
[ { "content": "Question:\nYou are given a list of integers, where every number appears exactly twice except for one number which appears only once. Write a function in Python to find the number that appears only once. Ensure your solution has an optimal time complexity.\n\n```python\ndef find_unique_number(nums)...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 877, "level": 1, "question": "You are given a list of integers, where every number appears exactly twice except for one number which appears only once. Write a function in Python to find the number that appears only once. Ensure your solution has an optimal time complexity.\n\n```py...
def transform_numbers(nums): return [num ** 2 if num % 2 == 0 else num ** 3 for num in nums]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to create a new list containing the squares of even numbers and the cubes of odd numbers from a given list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 878, "level": 1, "question": "Write a python function to create a new list containing the squares of even numbers and the cubes of odd numbers from a given list.", "split": "train" }
def is_palindrome(s): cleaned = ''.join([c.lower() for c in s if c.isalnum()]) return cleaned == cleaned[::-1]
simplelr_Apps
[ { "content": "Question:\nComplete the function that checks if a given string (consisting of printable ASCII characters) is a valid palindrome after removing non-alphanumeric characters and ignoring case diffe. A palindrome is a word, phrase, or sequence that reads the same backward as forward.\n\nImplement a fu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 879, "level": 1, "question": "Complete the function that checks if a given string (consisting of printable ASCII characters) is a valid palindrome after removing non-alphanumeric characters and ignoring case diffe. A palindrome is a word, phrase, or sequence that reads the same back...
def calculate_left_right_max(heights): n = len(heights) if n == 0: return ([], []) leftMax = [] max_so_far = 0 for num in heights: leftMax.append(max_so_far) if num > max_so_far: max_so_far = num rightMax = [0] * n max_so_far = 0 for i in ran...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a **0-indexed** integer array `heights` representing the heights of buildings in a row. The goal is to construct a new array `leftMax` where `leftMax[i]` is the maximum height of all buildings to the left of building `i` (excluding `i` itself) and a new array `rightMax` wh...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 880, "level": 1, "question": "You are given a **0-indexed** integer array `heights` representing the heights of buildings in a row. The goal is to construct a new array `leftMax` where `leftMax[i]` is the maximum height of all buildings to the left of building `i` (excluding `i` its...
def count_visible_buildings(heights): max_height = 0 count = 0 for h in heights: if h > max_height: count += 1 max_height = h return count
simplelr_Leetcode
[ { "content": "Question:\nYou are given a **0-indexed** integer array `heights` representing the heights of buildings in a city. A building's aesthetic value for a particular observer depends on its relative visibility. A building is considered visible if there are no taller buildings before it in the list of he...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 881, "level": 1, "question": "You are given a **0-indexed** integer array `heights` representing the heights of buildings in a city. A building's aesthetic value for a particular observer depends on its relative visibility. A building is considered visible if there are no taller bui...
def rotate_matrix_90_clockwise(matrix): return [list(row[::-1]) for row in zip(*matrix)]
simplelr_Filter
[ { "content": "Question:\nGiven a matrix, write a program to rotate it 90 degrees clockwise.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 882, "level": 1, "question": "Given a matrix, write a program to rotate it 90 degrees clockwise.", "split": "train" }
def repeat_string(A: str, B: str) -> int: set_A = set(A) for c in B: if c not in set_A: return -1 len_A = len(A) len_B = len(B) min_k = float('inf') for i in range(len_A): max_l = min(len_A - i, len_B) l = 0 while l < max_l and A[i + l] ...
simplelr_Data_Structure
[ { "content": "Question:\nMinimum Repeated Substring Match\n\n#### Problem Statement\nYou are given two non-empty strings `A` and `B`. Your task is to determine the minimum number of times the string `A` must be repeated such that `B` becomes a substring of the resultant repeated string. If it is not possible fo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 883, "level": 1, "question": "Minimum Repeated Substring Match\n\n#### Problem Statement\nYou are given two non-empty strings `A` and `B`. Your task is to determine the minimum number of times the string `A` must be repeated such that `B` becomes a substring of the resultant repeate...
import select import errno def wait_fd(fd, flags, timeout, retry_on_intr=False): read_fds = [] write_fds = [] except_fds = [] if flags & 1: read_fds.append(fd) if flags & 2: write_fds.append(fd) timeout_sec = timeout / 1e6 # Convert microseconds to seconds wh...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that simulates the behavior of the `wait_fd` function from the given C code snippet. The function should accept a file descriptor, a flags parameter that specifies the type of event to wait for (readable, writable, or both), and a timeout duration in microseconds...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 884, "level": 1, "question": "Write a Python function that simulates the behavior of the `wait_fd` function from the given C code snippet. The function should accept a file descriptor, a flags parameter that specifies the type of event to wait for (readable, writable, or both), and ...
def longest_non_repeating_substring(s): char_index = {} left = 0 max_length = 0 start = 0 for right in range(len(s)): char = s[right] if char in char_index and char_index[char] >= left: left = char_index[char] + 1 char_index[char] = right current_length = ...
simplelr_Filter
[ { "content": "Question:\nDesign an algorithm that prints out the longest substring of a given string without repeating characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 885, "level": 1, "question": "Design an algorithm that prints out the longest substring of a given string without repeating characters.", "split": "train" }
def calculate_perimeter(length, width): return 2 * (length + width) # Example usage length = 10 width = 5 perimeter = calculate_perimeter(length, width) print(f"The perimeter of the rectangle is: {perimeter}")
simplelr_Filter
[ { "content": "Question:\nI am looking for a way to calculate the perimeter of a rectangle in a Python program. Can you provide me with a code snippet to do this? Also, could you show me how to use this function by calculating the perimeter of a rectangle with a length of 10 and a width of 5?\nAnswer:\nLet's thi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 886, "level": 1, "question": "I am looking for a way to calculate the perimeter of a rectangle in a Python program. Can you provide me with a code snippet to do this? Also, could you show me how to use this function by calculating the perimeter of a rectangle with a length of 10 and...
def length_of_longest_substring(s): max_len = 0 left = 0 char_index = {} for right in range(len(s)): current_char = s[right] if current_char in char_index and char_index[current_char] >= left: left = char_index[current_char] + 1 char_index[curre...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` consisting of lowercase letters, return the length of the longest substring without repeating characters. A substring is a contiguous sequence of characters within the string. Your solution should be efficient with a linear time complexity.\n\nFor instance, if `s = \"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 887, "level": 1, "question": "Given a string `s` consisting of lowercase letters, return the length of the longest substring without repeating characters. A substring is a contiguous sequence of characters within the string. Your solution should be efficient with a linear time compl...
def check_balanced_unary(s: str) -> bool: s = s.replace(" ", "") stack = [] for char in s: if char == '(': stack.append(char) elif char == ')': if not stack or stack[-1] != '(': return False stack.pop() return len(stack) == 0 # Example...
simplelr_Algorithm
[ { "content": "Question:\n### Balanced Parentheses Check with Unary Operators\n\nWrite a method `check_balanced_unary` that checks whether a string containing parentheses and unary operators ('+' and '-') is balanced or not. A string is considered balanced if:\n\n1. Every opening parenthesis '(' has a correspond...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 888, "level": 1, "question": "### Balanced Parentheses Check with Unary Operators\n\nWrite a method `check_balanced_unary` that checks whether a string containing parentheses and unary operators ('+' and '-') is balanced or not. A string is considered balanced if:\n\n1. Every openin...
def longest_mountain(arr): n = len(arr) if n < 3: return 0 inc = [1] * n for i in range(1, n): if arr[i] > arr[i-1]: inc[i] = inc[i-1] + 1 else: inc[i] = 1 dec = [1] * n for i in range(n-2, -1, -1): if arr[i] > arr[i+1]: ...
simplelr_Evol
[ { "content": "Question:\nGiven a list of integers, a \"mountain\" subarray is defined as a contiguous subarray where the elements strictly increase up to a peak element, and then strictly decrease. The length of the mountain must be at least 3. Write a function in Python that takes a list of integers as input a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 889, "level": 1, "question": "Given a list of integers, a \"mountain\" subarray is defined as a contiguous subarray where the elements strictly increase up to a peak element, and then strictly decrease. The length of the mountain must be at least 3. Write a function in Python that t...
def findUnique(arr): result = 0 for num in arr: result ^= num return result
simplelr_Taco
[ { "content": "Question:\nYou are given an array of unique integers where each integer is present exactly twice, except for one integer which is present only once. Write a function to find and return the unique integer that is present only once.\n\nYou are required to complete the `findUnique` function, which ta...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 890, "level": 1, "question": "You are given an array of unique integers where each integer is present exactly twice, except for one integer which is present only once. Write a function to find and return the unique integer that is present only once.\n\nYou are required to complete t...
def reverse_string(s): """Reverses the input string and returns the reversed string. Args: s (str): The input string to be reversed. Returns: str: The reversed string. """ return s[::-1]
simplelr_Filter
[ { "content": "Question:\nCreate a function in Python that takes a string as input and returns the string in reverse order. For example, if the input is \"hello\", the output should be \"olleh\". Make sure to include a docstring that explains what the function does.\nAnswer:\nLet's think step by step.\n", "r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 891, "level": 1, "question": "Create a function in Python that takes a string as input and returns the string in reverse order. For example, if the input is \"hello\", the output should be \"olleh\". Make sure to include a docstring that explains what the function does.", "split":...
def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False max_divisor = int(n ** 0.5) + 1 for d in range(3, max_divisor, 2): if n % d == 0: return False return True
simplelr_Prefill
[ { "content": "Question:\nCreate a function that checks if a given number is a prime number. A prime number is a number that has exactly two distinct divisors: 1 and itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 892, "level": 1, "question": "Create a function that checks if a given number is a prime number. A prime number is a number that has exactly two distinct divisors: 1 and itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.", "split": "train" }
def run_length_encode(s): if not s: return "" result = [] current_char = s[0] count = 1 for i in range(1, len(s)): if s[i] == current_char: count += 1 else: result.append(str(count) + current_char) current_char = s[i] count = 1 ...
simplelr_Code_Contests
[ { "content": "Question:\n**Data Compression with Run-Length Encoding**\n\nTo help you practice working with arrays and strings, here's a problem related to data compression in computer science. A common technique is run-length encoding (RLE) where consecutive data elements (runs) are stored as a single data val...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 893, "level": 1, "question": "**Data Compression with Run-Length Encoding**\n\nTo help you practice working with arrays and strings, here's a problem related to data compression in computer science. A common technique is run-length encoding (RLE) where consecutive data elements (run...
def rolling_average(data, window_size): if not data: return [] values = [d[1] for d in data] n = len(values) prefix = [0.0] * (n + 1) for i in range(n): prefix[i + 1] = prefix[i] + values[i] averages = [] for i in range(n): if i >= window_size - 1: ...
simplelr_Algorithm
[ { "content": "Question:\n#### Scenario:\nYou are developing a system to analyze the performance metrics of an application over time. Specifically, you need to compute rolling averages over a series of time-stamped data points. This is crucial for identifying trends and fluctuations in the application's performa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 894, "level": 1, "question": "#### Scenario:\nYou are developing a system to analyze the performance metrics of an application over time. Specifically, you need to compute rolling averages over a series of time-stamped data points. This is crucial for identifying trends and fluctuat...
def length_of_longest_substring(s): last_seen = [-1] * 26 max_length = 0 start = 0 for end in range(len(s)): char = s[end] idx = ord(char) - ord('a') if last_seen[idx] >= start: start = last_seen[idx] + 1 last_seen[idx] = end current_length = end - sta...
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes in a string consisting of lowercase letters and returns the length of the longest substring with all unique characters. Implement this function without using built-in library functions for finding substrings or sets.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 895, "level": 1, "question": "Write a function that takes in a string consisting of lowercase letters and returns the length of the longest substring with all unique characters. Implement this function without using built-in library functions for finding substrings or sets.", "spl...
def min_window_substring(s: str, t: str) -> str: from collections import defaultdict if not s or not t: return "" t_count = defaultdict(int) for char in t: t_count[char] += 1 required = len(t_count) s_count = defaultdict(int) have = 0 min_length = float('i...
simplelr_Algorithm
[ { "content": "Question:\n### Question: Minimum Window Substring\n\n#### Context\nYou are tasked with finding a small window within a given string that contains all the characters of another string. This problem is crucial in scenarios such as text processing, where you need to identify patterns or substrings ef...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 896, "level": 1, "question": "### Question: Minimum Window Substring\n\n#### Context\nYou are tasked with finding a small window within a given string that contains all the characters of another string. This problem is crucial in scenarios such as text processing, where you need to ...
def square_list(lst): return [x ** 2 for x in lst]
simplelr_Evol
[ { "content": "Question:\nWrite a function in Python that takes a list of integers and returns a new list with each element squared. Make sure to handle the case where the input list is empty by returning an empty list.\n\nExample:\n```python\nsquare_list([1, 2, 3, 4]) # Output: [1, 4, 9, 16]\nsquare_list([]) ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 897, "level": 1, "question": "Write a function in Python that takes a list of integers and returns a new list with each element squared. Make sure to handle the case where the input list is empty by returning an empty list.\n\nExample:\n```python\nsquare_list([1, 2, 3, 4]) # Output...
def sliding_window_concatenate(lst, k): result = [] n = len(lst) if n < k: return result for i in range(n - k + 1): window = lst[i:i+k] result.append(''.join(window)) return result
simplelr_Apps
[ { "content": "Question:\nCreate a function that takes a list of strings and an integer k as arguments, and returns a list of strings with a sliding window of length k concatenated together. The returned list should contain the k-length sliding window of string concatenations from the initial list. Each element ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 898, "level": 1, "question": "Create a function that takes a list of strings and an integer k as arguments, and returns a list of strings with a sliding window of length k concatenated together. The returned list should contain the k-length sliding window of string concatenations fr...
def categorize_team_members(members): role_members = {} for member in members: name, role = member.rsplit(maxsplit=1) if role in role_members: role_members[role].append(name) else: role_members[role] = [name] return role_members
simplelr_Evol
[ { "content": "Question:\nDesign a function that takes a list of strings representing names of members in a project team including their roles, and categorizes the members into distinct categories based on their roles. Each category should contain names of the team members assigned to that role. Ensure to handle...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 899, "level": 1, "question": "Design a function that takes a list of strings representing names of members in a project team including their roles, and categorizes the members into distinct categories based on their roles. Each category should contain names of the team members assig...