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_positive_divisors(n): if n <= 1: return 0 total = 1 # 1 is a proper divisor for n > 1 sqrt_n = int(n ** 0.5) for i in range(2, sqrt_n + 1): if n % i == 0: total += i j = n // i if j != i and j != n: total += j return tot...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the sum of all positive divisors of a given number, excluding the number itself. For example, if the input number is 15, the function should return 1 + 3 + 5 = 9. How can I implement this in Python?\nAnswer:\nLet's think step by step.\n", "role": "user"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 700, "level": 1, "question": "Write a function to calculate the sum of all positive divisors of a given number, excluding the number itself. For example, if the input number is 15, the function should return 1 + 3 + 5 = 9. How can I implement this in Python?", "split": "train" }
def max_sum_2d_array(arr): return sum(sum(row) for row in arr)
simplelr_Filter
[ { "content": "Question:\nI need you to create a python function that given a 2D array, it will return the maximum sum of all the cells inside it. You can assume that the array can only have positive integers and it will always have at least one row and one column.\nAnswer:\nLet's think step by step.\n", "ro...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 701, "level": 1, "question": "I need you to create a python function that given a 2D array, it will return the maximum sum of all the cells inside it. You can assume that the array can only have positive integers and it will always have at least one row and one column.", "split": ...
def sum_even_numbers(array): total = 0 for num in array: if num % 2 == 0: total += num return total
simplelr_Filter
[ { "content": "Question:\nHere's my code for finding a sum of all even numbers in a list without using any built-in functions:\n\n```python\ndef sum_even_numbers(array):\n total = 0\n for num in array:\n if num % 2 == 0:\n total += num\n return total\nAnswer:\nLet's think step by step....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 702, "level": 1, "question": "Here's my code for finding a sum of all even numbers in a list without using any built-in functions:\n\n```python\ndef sum_even_numbers(array):\n total = 0\n for num in array:\n if num % 2 == 0:\n total += num\n return total",...
def smallest_lexicographical_string(s): return ''.join(sorted(s))
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` which consists of lowercase English letters. You are allowed to perform the following operation any number of times:\n\n- Choose any two adjacent characters in the string and replace them with their \"sorted\" version, meaning the lexicographically smaller cha...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 703, "level": 1, "question": "You are given a string `s` which consists of lowercase English letters. You are allowed to perform the following operation any number of times:\n\n- Choose any two adjacent characters in the string and replace them with their \"sorted\" version, meaning...
from typing import List, Tuple def recommend_books(reading_history: List[str], available_books: List[Tuple[str, float]], n: int) -> List[str]: # Create a set of read books for quick lookup read_books = set(reading_history) # Filter out books that are already read filtered_books = [book for book in avai...
simplelr_Algorithm
[ { "content": "Question:\n## Scenario\nYou are tasked with improving the customer experience in an online bookstore. A new feature requirement is to implement a book recommendation system that suggests books based on a customer's reading history. However, the bookstore wants to specifically promote books that ar...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 704, "level": 1, "question": "## Scenario\nYou are tasked with improving the customer experience in an online bookstore. A new feature requirement is to implement a book recommendation system that suggests books based on a customer's reading history. However, the bookstore wants to ...
import pandas as pd from sklearn.preprocessing import MinMaxScaler def normalize_dataframe(df: pd.DataFrame) -> pd.DataFrame: # Identify numeric columns numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns new_df = df.copy() for col in numeric_cols: scaler = MinMaxScaler()...
simplelr_Package
[ { "content": "Question:\nWrite a function named `normalize_dataframe` that normalizes the numeric columns in a given pandas DataFrame. The function should scale each numeric column to a range between 0 and 1. For this task, use the `MinMaxScaler` from the `sklearn.preprocessing` module.\n\n### Function Signatur...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 705, "level": 1, "question": "Write a function named `normalize_dataframe` that normalizes the numeric columns in a given pandas DataFrame. The function should scale each numeric column to a range between 0 and 1. For this task, use the `MinMaxScaler` from the `sklearn.preprocessing...
def first_non_repeating_char(s): if not s: return None char_count = {} for char in s: char_count[char] = char_count.get(char, 0) + 1 for char in s: if char_count[char] == 1: return char return None
simplelr_Filter
[ { "content": "Question:\nHow can I efficiently find the first non-repeating character in a string using Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 706, "level": 1, "question": "How can I efficiently find the first non-repeating character in a string using Python?", "split": "train" }
def productExceptSelf(nums): n = len(nums) prefix = [1] * n for i in range(1, n): prefix[i] = prefix[i-1] * nums[i-1] suffix = [1] * n for i in range(n-2, -1, -1): suffix[i] = suffix[i+1] * nums[i+1] result = [prefix[i] * suffix[i] for i in range(n)] return result
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers, return a new array where each element at index *i* is the product of all the numbers in the original array except the one at *i*. Do this without using division and in O(n) time complexity.\n\n```\nEXAMPLES:\n\nproductExceptSelf([1,2,3,4]) = [24,12,8,6]\nprod...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 707, "level": 1, "question": "Given an array of integers, return a new array where each element at index *i* is the product of all the numbers in the original array except the one at *i*. Do this without using division and in O(n) time complexity.\n\n```\nEXAMPLES:\n\nproductExceptS...
def canRearrange(s): ones = sum(int(c) for c in s) zeros = len(s) - ones return ones <= zeros + 1
simplelr_Filter
[ { "content": "Question:\nI've been having trouble solving this problem and I was hoping you could help. \n\nThe problem is: \n\nGiven a string with only 0s and 1s, determine whether it can be rearranged into a string with no consecutive 1s.\n\nThe goal is to return a boolean value indicating whether such a rear...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 708, "level": 1, "question": "I've been having trouble solving this problem and I was hoping you could help. \n\nThe problem is: \n\nGiven a string with only 0s and 1s, determine whether it can be rearranged into a string with no consecutive 1s.\n\nThe goal is to return a boolean va...
def sum_excluding_min_max(arr): if len(arr) < 3: return 0 min_val = min(arr) max_val = max(arr) if min_val == max_val: return (len(arr) - 2) * min_val else: new_arr = list(arr) new_arr.remove(min_val) new_arr.remove(max_val) return sum(new_arr)
simplelr_Taco
[ { "content": "Question:\nIn this Kata, you must find the sum of the elements in the array excluding the maximum and minimum elements. If there are multiple occurrences of the maximum or minimum elements, exclude each occurrence at most once. If the array is empty or contains less than three elements, return 0.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 709, "level": 1, "question": "In this Kata, you must find the sum of the elements in the array excluding the maximum and minimum elements. If there are multiple occurrences of the maximum or minimum elements, exclude each occurrence at most once. If the array is empty or contains le...
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_Evol
[ { "content": "Question:\nGiven a list of integers, write a function to find two numbers in the list that add up to a given target sum. If such a pair exists, return the indices of the two numbers. If there are multiple pairs, return any one of them. If no such pair exists, return an empty list.\n\nExample:\nInp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 710, "level": 1, "question": "Given a list of integers, write a function to find two numbers in the list that add up to a given target sum. If such a pair exists, return the indices of the two numbers. If there are multiple pairs, return any one of them. If no such pair exists, retu...
def is_prime(n): if n <= 1: return "This number is not prime." elif n == 2: return "This number is prime." elif n % 2 == 0: return "This number is not prime." else: max_divisor = int(n ** 0.5) + 1 for d in range(3, max_divisor, 2): if n % d == 0: ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that checks if a number is a prime number or not. If it is prime, return \"This number is prime.\" Otherwise, return \"This number is not prime.\"\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 711, "level": 1, "question": "Create a function that checks if a number is a prime number or not. If it is prime, return \"This number is prime.\" Otherwise, return \"This number is not prime.\"", "split": "train" }
def rotate_grid_90_degrees(grid): return [list(row[::-1]) for row in zip(*grid)]
simplelr_Filter
[ { "content": "Question:\nWe will give you a list of lists, where each sublist represents a row of a 2D grid. The grid will consist of either 0s or 1s. Write a function that rotates the grid 90 degrees clockwise and returns it.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 712, "level": 1, "question": "We will give you a list of lists, where each sublist represents a row of a 2D grid. The grid will consist of either 0s or 1s. Write a function that rotates the grid 90 degrees clockwise and returns it.", "split": "train" }
def increasing_triplet(nums): first = second = float('inf') for num in nums: if num <= first: first = num elif num <= second: second = num else: return True return False
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `nums`, return `true` if there exists a subsequence of the array of length `3` that forms an increasing triplet subsequence. Otherwise, return `false`. \n- An increasing triplet subsequence is a subsequence of three indices `i`, `j`, `k` such that `i < j < k` and...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 713, "level": 1, "question": "Given an integer array `nums`, return `true` if there exists a subsequence of the array of length `3` that forms an increasing triplet subsequence. Otherwise, return `false`. \n- An increasing triplet subsequence is a subsequence of three indices `i`, ...
def find_min_max(num_list): return (min(num_list), max(num_list))
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the minimum number (`min_num`) and maximum number (`max_num`) in a list of numbers, and return them as a tuple.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 714, "level": 1, "question": "Write a python function to find the minimum number (`min_num`) and maximum number (`max_num`) in a list of numbers, and return them as a tuple.", "split": "train" }
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_Apps
[ { "content": "Question:\n# Task\nGiven an array of integers and a target integer, return the indices of the two numbers in the array that add up to the target. Assume that each input would have exactly one solution, and you may not use the same element twice.\n\n# Example\n\nFor `nums = [2, 7, 11, 15]` and `tar...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 715, "level": 1, "question": "# Task\nGiven an array of integers and a target integer, return the indices of the two numbers in the array that add up to the target. Assume that each input would have exactly one solution, and you may not use the same element twice.\n\n# Example\n\nFo...
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 i in range(3, max_divisor + 1, 2): if n % i == 0: return False return True
simplelr_Filter
[ { "content": "Question:\nWrite a Python function `is_prime` that determines if a given integer is a prime number. A prime number is defined as a natural number greater than 1 that is divisible by exactly two distinct natural numbers: 1 and itself. Your function should take a single integer as input and return `...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 716, "level": 1, "question": "Write a Python function `is_prime` that determines if a given integer is a prime number. A prime number is defined as a natural number greater than 1 that is divisible by exactly two distinct natural numbers: 1 and itself. Your function should take a si...
def longest_palindromic_subsequence_length(s: str) -> int: """ This function calculates the length of the longest palindromic subsequence in a given string. Args: s (str): The input string. Returns: int: The length of the longest palindromic subsequence. """ # Get ...
simplelr_Filter
[ { "content": "Question:\nYour task is to implement a function `longest_palindromic_subsequence_length` that takes a string `s` as input and returns the length of the longest palindromic subsequence in that string. This function will use dynamic programming to solve the problem.\n\nHere's a step-by-step breakdow...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 717, "level": 1, "question": "Your task is to implement a function `longest_palindromic_subsequence_length` that takes a string `s` as input and returns the length of the longest palindromic subsequence in that string. This function will use dynamic programming to solve the problem....
def can_see_buildings(heights): if not heights: return [] max_height = heights[0] result = [] for i in range(1, len(heights)): if heights[i] > max_height: result.append(i) max_height = heights[i] return result
simplelr_Leetcode
[ { "content": "Question:\nYou are given a **0-indexed** integer array `heights` representing the heights of buildings, where `heights[i]` is the height of the `i-th` building. An observer is standing on the rooftop of the building at index `0`. From this rooftop, the observer can see another building if all the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 718, "level": 1, "question": "You are given a **0-indexed** integer array `heights` representing the heights of buildings, where `heights[i]` is the height of the `i-th` building. An observer is standing on the rooftop of the building at index `0`. From this rooftop, the observer ca...
from typing import List def maxProfit(prices: List[int], fee: int) -> int: if not prices: return 0 # Initialize buy as -prices[0] because we start by buying the first day's stock buy = -prices[0] # Initialize sell as 0 because we start with no profit and not holding any stock sell = 0 f...
simplelr_Codeforces
[ { "content": "Question:\nYou are given a sequence of integers representing the stock prices of a company over a period of days. The prices are given as a list of positive integers where each integer represents the price of the stock on a particular day. A \"buy\" transaction consists of buying the stock on a gi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 719, "level": 1, "question": "You are given a sequence of integers representing the stock prices of a company over a period of days. The prices are given as a list of positive integers where each integer represents the price of the stock on a particular day. A \"buy\" transaction co...
def check_subarray_sum(arr, k): prefix_map = {0: -1} current_sum = 0 for j in range(len(arr)): current_sum += arr[j] rem = current_sum % k if rem in prefix_map: i = prefix_map[rem] if j - i >= k: return True else: prefix_map...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of integers `arr` and an integer `k`. Write a function that will return `true` if there is a continuous subarray of size at least `k` that sums up to a multiple of `k`, otherwise return `false`. A continuous subarray of size at least `k` means it has `k` or more c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 720, "level": 1, "question": "You are given an array of integers `arr` and an integer `k`. Write a function that will return `true` if there is a continuous subarray of size at least `k` that sums up to a multiple of `k`, otherwise return `false`. A continuous subarray of size at le...
import math def min_num_perfect_squares(n): """ Returns the smallest number of perfect squares that sum to the specified number. :param n: int, the number to be summed to using smallest number of perfect squares :return: int between 1 - 4, the minimum number of perfect squares that sum to the spec...
simplelr_Data_Structure
[ { "content": "Question:\n### Question: Minimum Number of Perfect Squares\n\nGiven a positive integer `n`, write a Python function `min_num_perfect_squares(n)` that returns the smallest number of perfect squares that sum to `n`. \n\n#### Input\n- A single integer `n` where 1 ≤ n ≤ 10^4.\n\n#### Output\n- An inte...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 721, "level": 1, "question": "### Question: Minimum Number of Perfect Squares\n\nGiven a positive integer `n`, write a Python function `min_num_perfect_squares(n)` that returns the smallest number of perfect squares that sum to `n`. \n\n#### Input\n- A single integer `n` where 1 ≤ n...
def filter_and_modify_dicts(input_list): return [{'id': d['id'] + '_even', 'value': d['value']} for d in input_list if d['value'] % 2 == 0]
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that applies the following logic to a list of dictionaries, each containing an `id` and `value`. The function should return a new list of dictionaries with the same structure, but only include those entries where the `value` is even. Additionally, modify the `id...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 722, "level": 1, "question": "Create a Python function that applies the following logic to a list of dictionaries, each containing an `id` and `value`. The function should return a new list of dictionaries with the same structure, but only include those entries where the `value` is ...
def first_non_repeating_character(s): # Create a frequency dictionary to count occurrences of each character freq = {} for char in s: if char in freq: freq[char] += 1 else: freq[char] = 1 # Iterate through the string to find the first character with count 1 ...
simplelr_Codeforces
[ { "content": "Question:\nGiven a string consisting of lowercase alphabets, write a function that returns the first non-repeating character in it. If there is no unique character, return '_'. \n\nInput Format:\n- A single input string containing only lowercase alphabets.\n\nOutput Format:\n- A single character w...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 723, "level": 1, "question": "Given a string consisting of lowercase alphabets, write a function that returns the first non-repeating character in it. If there is no unique character, return '_'. \n\nInput Format:\n- A single input string containing only lowercase alphabets.\n\nOutp...
def fun(l): return [i ** 2 for i in l] # Example usage numbers = [1, 2, 3, 4, 5] result = fun(numbers) print(result) # Output: [1, 4, 9, 16, 25]
simplelr_Filter
[ { "content": "Question:\nHere's a Python list problem: create a new list containing the sum of the squares of each element in a list, using list comprehension. \n\nFor example, `fun([1, 2, 3, 4, 5])` should return `[1, 4, 9, 16, 25]`. \n\nAdditionally, provide an example code of how this can be applied in pract...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 724, "level": 1, "question": "Here's a Python list problem: create a new list containing the sum of the squares of each element in a list, using list comprehension. \n\nFor example, `fun([1, 2, 3, 4, 5])` should return `[1, 4, 9, 16, 25]`. \n\nAdditionally, provide an example code o...
def is_palindrome(s): cleaned = [] for c in s: if c.isalnum(): cleaned.append(c.lower()) cleaned_str = ''.join(cleaned) return cleaned_str == cleaned_str[::-1]
simplelr_Filter
[ { "content": "Question:\nYou are a programmer responsible for creating a function that determines if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward.\n\nFunction Specifications:\n\n Function Name: is_palindrome\n In...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 725, "level": 1, "question": "You are a programmer responsible for creating a function that determines if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward.\n\nFunction Specifications:\n\n...
def count_buildings_with_sunset_view(heights): count = 0 max_so_far = 0 for h in reversed(heights): if h > max_so_far: count += 1 max_so_far = h return count
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of integers `heights` representing the heights of buildings in a skyline. The width of each building is `1`. The skyline view is blocked when a taller or equal building is in front of a shorter one from left to right. Return the number of buildings that can see th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 726, "level": 1, "question": "You are given an array of integers `heights` representing the heights of buildings in a skyline. The width of each building is `1`. The skyline view is blocked when a taller or equal building is in front of a shorter one from left to right. Return the n...
MOD = 2 ** 63 - 1 def lcg(seed): a = 1664525 c = 1013904223 return (a * seed + c) % MOD
simplelr_Filter
[ { "content": "Question:\nOne approach to creating plausible-sounding pseudorandom numbers is to use a Linear Congruential Generator (LCG). An LCG works by iterating over a recurrence relation of the form:\n\n X[i + 1] = (aX[i] + c) mod m,\n\nwhere a, c, and m are large positive integers. The values of X are ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 727, "level": 1, "question": "One approach to creating plausible-sounding pseudorandom numbers is to use a Linear Congruential Generator (LCG). An LCG works by iterating over a recurrence relation of the form:\n\n X[i + 1] = (aX[i] + c) mod m,\n\nwhere a, c, and m are large posit...
def max_visible_buildings(heights): if not heights: return 0 sorted_heights = sorted(heights) count = 0 current_max = 0 for height in sorted_heights: if height > current_max: count += 1 current_max = height return count
simplelr_Leetcode
[ { "content": "Question:\nYou are given an integer array `heights` representing the heights of buildings in a city. Arrange the buildings such that the skyline formed shows the maximum possible number of buildings when viewed from the front in silhouette form. You can change the order of buildings but cannot cha...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 728, "level": 1, "question": "You are given an integer array `heights` representing the heights of buildings in a city. Arrange the buildings such that the skyline formed shows the maximum possible number of buildings when viewed from the front in silhouette form. You can change the...
from typing import List def find_optimal_zero_to_flip(arr: List[int]) -> int: n = len(arr) if n == 0: return -1 # Assuming the function should handle empty arrays, though constraints say n >=1 # Compute left array where left[i] is the number of consecutive 1's ending at i left = [0] * n ...
simplelr_Data_Structure
[ { "content": "Question:\n#### Scenario:\nYou are a software engineer tasked with improving the efficiency of a binary data stream by increasing the consecutive `1`s. Given a binary array, you need to identify the optimal position to switch a `0` to a `1` to maximize the consecutive sequence of `1`s.\n\n#### Tas...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 729, "level": 1, "question": "#### Scenario:\nYou are a software engineer tasked with improving the efficiency of a binary data stream by increasing the consecutive `1`s. Given a binary array, you need to identify the optimal position to switch a `0` to a `1` to maximize the consecu...
def longest_substring_with_k_distinct(s, k): if k == 0: return "" distinct_count = len(set(s)) if k >= distinct_count: return s window_start = 0 max_length = 0 max_substring = "" char_frequency = {} for window_end in range(len(s)): right_char = s[window_end] ...
simplelr_Filter
[ { "content": "Question:\nI'm trying to solve this code challenge where I need to implement a function to find the longest substring with K distinct characters in a string. \n\nHere's my attempt:\n```\ndef longest_substring_with_k_distinct(s, k):\n if k == 0:\n return \"\"\n window_start = 0\n ma...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 730, "level": 1, "question": "I'm trying to solve this code challenge where I need to implement a function to find the longest substring with K distinct characters in a string. \n\nHere's my attempt:\n```\ndef longest_substring_with_k_distinct(s, k):\n if k == 0:\n return ...
def square(x): return x ** 2
simplelr_Filter
[ { "content": "Question:\nHow can I define a function in Python that takes a single argument and returns the square of that argument?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 731, "level": 1, "question": "How can I define a function in Python that takes a single argument and returns the square of that argument?", "split": "train" }
def remove_duplicates(input_list): seen = set() result = [] for item in input_list: if item not in seen: result.append(item) seen.add(item) return result
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to remove duplicates from a list while preserving the original order of the elements. You can only use basic list operations and Python built-in functions without using any special libraries.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 732, "level": 1, "question": "Write a python function to remove duplicates from a list while preserving the original order of the elements. You can only use basic list operations and Python built-in functions without using any special libraries.", "split": "train" }
def find_max_min_sum(numbers): """ Find and return the sum of the maximum and minimum values in the list. Args: numbers (list): A list of integers. Returns: int: The sum of the maximum and minimum values, or None if the list is empty. """ if not numbers: return None ...
simplelr_Package
[ { "content": "Question:\nYou are tasked with creating a function named `find_max_min_sum` that takes a single parameter: `numbers`. The function will return the sum of the maximum and minimum values in the list.\n\n#### Parameters:\n- `numbers`: A list of integers.\n\n#### Requirements:\n- The function should f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 733, "level": 1, "question": "You are tasked with creating a function named `find_max_min_sum` that takes a single parameter: `numbers`. The function will return the sum of the maximum and minimum values in the list.\n\n#### Parameters:\n- `numbers`: A list of integers.\n\n#### Requ...
def sum_of_squares(numbers): return sum(x ** 2 for x in numbers) # Example usage numbers = [1, 2, 3, 4, 5] result = sum_of_squares(numbers) print(result) # Output: 55
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that takes a list of numbers as input and returns the sum of the squares of the numbers. Use the function to find the sum of the squares of the numbers in the list [1, 2, 3, 4, 5].\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 734, "level": 1, "question": "Create a Python function that takes a list of numbers as input and returns the sum of the squares of the numbers. Use the function to find the sum of the squares of the numbers in the list [1, 2, 3, 4, 5].", "split": "train" }
def can_form_palindrome(s: str) -> bool: freq = {} for c in s: if c.isalpha(): lower_c = c.lower() if lower_c in freq: freq[lower_c] += 1 else: freq[lower_c] = 1 odd_count = 0 for count in freq.values(): if count % 2 != ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nWrite a function to determine if a given string is re-arrangeable into a palindrome. A palindrome is a word, phrase, or sequence that reads the same backward as forward.\n\nYour function should return `True` if the string can be rearranged into a palindrome, and...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 735, "level": 1, "question": "### Problem Statement\n\nWrite a function to determine if a given string is re-arrangeable into a palindrome. A palindrome is a word, phrase, or sequence that reads the same backward as forward.\n\nYour function should return `True` if the string can be...
def find_nodes_with_no_incoming_edges(n, edges): in_degree = [0] * n for u, v in edges: in_degree[v] += 1 result = [i for i in range(n) if in_degree[i] == 0] return result
simplelr_Leetcode
[ { "content": "Question:\nGiven a directed acyclic graph (DAG) with `n` nodes labeled from `0` to `n - 1` and an array `edges` where `edges[i] = [u, v]` represents a directed edge from node `u` to node `v`, return an array containing all nodes with no incoming edges (i.e., nodes with in-degree of zero). Implemen...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 736, "level": 1, "question": "Given a directed acyclic graph (DAG) with `n` nodes labeled from `0` to `n - 1` and an array `edges` where `edges[i] = [u, v]` represents a directed edge from node `u` to node `v`, return an array containing all nodes with no incoming edges (i.e., nodes...
def people_in_room(arr): total = sum(arr) return max(total, 0)
simplelr_Apps
[ { "content": "Question:\n# Kata Task\n\nYou are given an array containing integers, where each element represents the number of people entering (+ number) or leaving (- number) a room.\n\nFor example, the array `[5, -3, 10, -2]` means:\n* 5 people entered the room\n* 3 people left the room\n* 10 additional peop...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 737, "level": 1, "question": "# Kata Task\n\nYou are given an array containing integers, where each element represents the number of people entering (+ number) or leaving (- number) a room.\n\nFor example, the array `[5, -3, 10, -2]` means:\n* 5 people entered the room\n* 3 people l...
def product_of_digits(n): n = abs(n) product = 1 for digit in str(n): product *= int(digit) return product
simplelr_Prefill
[ { "content": "Question:\nCreate a function that receives a number and returns the product of its digits.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 738, "level": 1, "question": "Create a function that receives a number and returns the product of its digits.", "split": "train" }
def is_palindrome(text): """ Checks if a given string is a palindrome. Args: text: The string to check. Returns: True if the string is a palindrome, False otherwise. """ processed = [] for c in text: if c.isalnum(): processed.append(c.lower()) left =...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to check if a given string is a palindrome.\n\nA palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, ignoring spaces, punctuation, and capitalization.\n\nHere are some examples:\n\n \"racecar\" is a pali...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 739, "level": 1, "question": "Write a Python function to check if a given string is a palindrome.\n\nA palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, ignoring spaces, punctuation, and capitalization.\n\nHere are some e...
from typing import List def format_phone_numbers(phone_numbers: List[str]) -> List[str]: formatted_numbers = [] for phone_num in phone_numbers: # Extract all digits from the phone number digits = ''.join([c for c in phone_num if c.isdigit()]) # Split into the required parts area...
simplelr_Algorithm
[ { "content": "Question:\n### Scenario\nYou work as a data analyst, and part of your job involves ensuring data consistency and formatting. You need to implement a function that standardizes phone numbers in a given format.\n\n### Task\nYou are required to write a function `format_phone_numbers` that takes a lis...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 740, "level": 1, "question": "### Scenario\nYou work as a data analyst, and part of your job involves ensuring data consistency and formatting. You need to implement a function that standardizes phone numbers in a given format.\n\n### Task\nYou are required to write a function `form...
def longest_subarray_with_sum_at_most_x(arr, x): max_length = 0 current_sum = 0 left = 0 for right in range(len(arr)): current_sum += arr[right] while current_sum > x and left <= right: current_sum -= arr[left] left += 1 if current_sum <= x: wi...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a **0-indexed** integer array `arr` and an integer `x`. You need to find the length of the longest subarray that has a sum less than or equal to `x`. The subarray must be non-empty.\n\nGiven `arr = [2, 1, 5, 1, 3, 2]` and `x = 8`, the longest subarray with sum ≤ 8 is `[2, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 741, "level": 1, "question": "You are given a **0-indexed** integer array `arr` and an integer `x`. You need to find the length of the longest subarray that has a sum less than or equal to `x`. The subarray must be non-empty.\n\nGiven `arr = [2, 1, 5, 1, 3, 2]` and `x = 8`, the long...
def max_non_overlapping_intervals(intervals: list[tuple[int, int]]) -> int: # Sort the intervals based on their end times sorted_intervals = sorted(intervals, key=lambda x: x[1]) count = 0 last_end = -float('inf') # Initialize with negative infinity for interval in sorted_intervals: if...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Challenge: Dynamic Non-overlapping Intervals Finder\n\n#### Context\nManaging schedules or reservations often involves working with time intervals. Efficiently finding the maximum set of non-overlapping intervals is a common optimization problem in various fields such as mach...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 742, "level": 1, "question": "### Coding Challenge: Dynamic Non-overlapping Intervals Finder\n\n#### Context\nManaging schedules or reservations often involves working with time intervals. Efficiently finding the maximum set of non-overlapping intervals is a common optimization prob...
import pandas as pd def filter_and_operate(df: pd.DataFrame, filter_col: str, logic_col1: str, logic_col2: str, fill_value: bool) -> pd.DataFrame: # Make a copy of the input DataFrame to avoid modifying the original df_copy = df.copy() # Step 1: Filter rows where the specified column has True values ...
simplelr_Docs
[ { "content": "Question:\nBooleanArray Operations with NA Handling\n\n#### Objective:\nDesign a function that performs complex data manipulation and logical operations over a DataFrame using pandas' nullable boolean data type.\n\n#### Task:\nWrite a function `filter_and_operate` that takes in a DataFrame with bo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 743, "level": 1, "question": "BooleanArray Operations with NA Handling\n\n#### Objective:\nDesign a function that performs complex data manipulation and logical operations over a DataFrame using pandas' nullable boolean data type.\n\n#### Task:\nWrite a function `filter_and_operate`...
def find_primes_interval(start: int, end: int) -> list[int]: if end < 2: return [] sieve = [True] * (end + 1) sieve[0], sieve[1] = False, False for i in range(2, int(end ** 0.5) + 1): if sieve[i]: sieve[i*i::i] = [False] * len(sieve[i*i::i]) primes = [i for i, is_prime in...
simplelr_Algorithm
[ { "content": "Question:\n### Prime Numbers Between Two Intervals\n\nWrite a function `find_primes_interval` that determines all prime numbers between two given positive integers `start` and `end` (inclusive). The function should return a list of prime numbers found within the given interval.\n\n### Function Sig...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 744, "level": 1, "question": "### Prime Numbers Between Two Intervals\n\nWrite a function `find_primes_interval` that determines all prime numbers between two given positive integers `start` and `end` (inclusive). The function should return a list of prime numbers found within the g...
from typing import List def selection_sort_descending(arr: List[int]) -> List[int]: """ Sorts an array in ascending order using a modified selection sort algorithm. Parameters: arr (List[int]): List of integers to sort. Returns: List[int]: Sorted list of integers. """ n = len(arr)...
simplelr_Data_Structure
[ { "content": "Question:\n### Question:\nYou are designing a warehouse management system that needs to sort lists of items by their prices to facilitate various operations. Your task is to implement a variant of the Selection Sort algorithm which, instead of moving the minimum element to the beginning, moves the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 745, "level": 1, "question": "### Question:\nYou are designing a warehouse management system that needs to sort lists of items by their prices to facilitate various operations. Your task is to implement a variant of the Selection Sort algorithm which, instead of moving the minimum e...
def calculate_sum(numbers): total = 0 for num in numbers: total += num max_value = max(numbers) min_value = min(numbers) return { 'sum': total, 'max': max_value, 'min': min_value } my_numbers = [1, 2, 3, 4, 5] result = calculate_sum(my_numbers) print("The sum is...
simplelr_Filter
[ { "content": "Question:\nHere is the code:\n```python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total += num\n return total\n\nmy_numbers = [1, 2, 3, 4, 5]\nresult = calculate_sum(my_numbers)\nprint(\"The sum is:\", result)\n```\nNow I want to modify the code to not only c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 746, "level": 1, "question": "Here is the code:\n```python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total += num\n return total\n\nmy_numbers = [1, 2, 3, 4, 5]\nresult = calculate_sum(my_numbers)\nprint(\"The sum is:\", result)\n```\nNow I wan...
def find_subset(arr, target): dp = {0: []} for num in arr: temp = {} for s in list(dp.keys()): new_sum = s + num if new_sum == target: subset = dp[s] + [num] return subset if new_sum not in dp and new_sum not in temp: ...
simplelr_Codeforces
[ { "content": "Question:\nGiven an array of integers, your task is to determine if there exists a subset of the array whose sum is equal to a given target value. If such a subset exists, return the subset in the form of a list. If multiple subsets satisfy the condition, return any one of them. If no such subset ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 747, "level": 1, "question": "Given an array of integers, your task is to determine if there exists a subset of the array whose sum is equal to a given target value. If such a subset exists, return the subset in the form of a list. If multiple subsets satisfy the condition, return a...
def square_elements(numbers: list[int]) -> list[int]: """ This function takes a list of integers and returns a new list where each element is the square of the corresponding element in the original list. Args: numbers: A list of integers. Returns: A new list containing the squares...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of integers and returns a new list where each element is the square of the original element. The function should be named `square_elements` and should follow the best practices for Python code, including appropriate documentation and type hints....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 748, "level": 1, "question": "Write a Python function that takes a list of integers and returns a new list where each element is the square of the original element. The function should be named `square_elements` and should follow the best practices for Python code, including appropr...
def factorial(n): if n < 0 or n > 12: return "Input out of range" result = 1 for i in range(1, n + 1): result *= i return result
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes an integer n and returns its factorial if n is between 0 and 12 (inclusive). If n is outside this range, return a message \"Input out of range\".\n\nInput\nA single integer n\n\nOutput\nThe factorial of n if 0 <= n <= 12, otherwise the message \"Input out of ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 749, "level": 1, "question": "Write a function that takes an integer n and returns its factorial if n is between 0 and 12 (inclusive). If n is outside this range, return a message \"Input out of range\".\n\nInput\nA single integer n\n\nOutput\nThe factorial of n if 0 <= n <= 12, oth...
def capitalize_vowels(s): vowels = {'a', 'e', 'i', 'o', 'u'} result = [] for char in s: if char.isalpha(): if char.lower() in vowels: result.append(char.upper()) else: result.append(char.lower()) else: result.append(char) ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as input and returns the string with all vowels capitalized and all consonants in lower case. For example, if the input string is \"Hello World!\", the function should return \"hElLo wOrld!\". How can this be done in Python?\nAnswer:\nLet's think st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 750, "level": 1, "question": "Create a function that takes a string as input and returns the string with all vowels capitalized and all consonants in lower case. For example, if the input string is \"Hello World!\", the function should return \"hElLo wOrld!\". How can this be done i...
def reverse_strings(strings): reversed_list = [] for s in strings: reversed_string = '' for char in s: reversed_string = char + reversed_string reversed_list.append(reversed_string) return reversed_list # Example usage: strings = ["hello", "world", "!"] print(reverse_str...
simplelr_Evol
[ { "content": "Question:\nCreate a function that accepts a list of strings and returns a new list where each string is reversed. Ensure that the function does not use inherent string reversal functions or methods but instead manually iterates over the characters. Test your function with edge cases such as empty ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 751, "level": 1, "question": "Create a function that accepts a list of strings and returns a new list where each string is reversed. Ensure that the function does not use inherent string reversal functions or methods but instead manually iterates over the characters. Test your funct...
def list_intersection(list1, list2): set2 = set(list2) result = [] added = set() for num in list1: if num in set2 and num not in added: result.append(num) added.add(num) return result
simplelr_Filter
[ { "content": "Question:\nHello, I'm trying to create a Python function that takes two lists of integers as input and returns a new list containing the intersection of the two lists. The intersection should include each element only once, regardless of how many times it appears in the input lists. How can I achi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 752, "level": 1, "question": "Hello, I'm trying to create a Python function that takes two lists of integers as input and returns a new list containing the intersection of the two lists. The intersection should include each element only once, regardless of how many times it appears ...
def cyclic_shift(s: str, n: int) -> str: if not s or n == 0: return s len_s = len(s) k = n % len_s if k == 0: return s return s[-k:] + s[:-k]
simplelr_Taco
[ { "content": "Question:\nGiven a string `s` consisting of lowercase letters and an integer `n`, perform a right cyclic shift on the string `n` times. A right cyclic shift on a string moves the last character to the front of the string and shifts all the other characters one place to the right.\n\nFor example:\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 753, "level": 1, "question": "Given a string `s` consisting of lowercase letters and an integer `n`, perform a right cyclic shift on the string `n` times. A right cyclic shift on a string moves the last character to the front of the string and shifts all the other characters one pla...
def max_adjacent_sum(arr): if len(arr) < 2: return None max_sum = float('-inf') for i in range(len(arr) - 1): current_sum = arr[i] + arr[i + 1] if current_sum > max_sum: max_sum = current_sum return max_sum
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an array of integers and returns the maximum sum of any two adjacent elements.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 754, "level": 1, "question": "Create a function that takes an array of integers and returns the maximum sum of any two adjacent elements.", "split": "train" }
def remove_duplicates(s): seen = set() result = [] for char in s: if char not in seen: seen.add(char) result.append(char) return ''.join(result)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to remove duplicates from a string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 755, "level": 1, "question": "Write a python function to remove duplicates from a string.", "split": "train" }
def median(numbers): sorted_numbers = sorted(numbers) n = len(sorted_numbers) if n == 0: raise ValueError("Cannot compute median of empty list") if n % 2 == 1: return sorted_numbers[n // 2] else: left = sorted_numbers[(n // 2) - 1] right = sorted_numbers[n // 2] ...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to compute the median of a list of numbers. The function should accept a list of numbers as input and return the median.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 756, "level": 1, "question": "Write a Python function to compute the median of a list of numbers. The function should accept a list of numbers as input and return the median.", "split": "train" }
from collections import deque def shortest_path(grid): N = len(grid) if N == 0: return -1 if grid[0][0] != 0 or grid[N-1][N-1] != 0: return -1 if N == 1: return 0 visited = [[False for _ in range(N)] for _ in range(N)] queue = deque() queue.append((0, 0, 0)) ...
simplelr_Codeforces
[ { "content": "Question:\nYou are working with a two-dimensional NxN grid, where each cell can either be empty or contain an obstacle. Your task is to find the shortest path from the top-left corner of the grid to the bottom-right corner, while avoiding obstacles. You can move up, down, left, or right, but you c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 757, "level": 1, "question": "You are working with a two-dimensional NxN grid, where each cell can either be empty or contain an obstacle. Your task is to find the shortest path from the top-left corner of the grid to the bottom-right corner, while avoiding obstacles. You can move u...
def string_to_number(s): return int(s)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to convert a string to a number. This number is to be returned as an integer.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 758, "level": 1, "question": "Write a function to convert a string to a number. This number is to be returned as an integer.", "split": "train" }
def find_missing_number(nums): m = len(nums) + 1 expected_sum = m * (m + 1) // 2 actual_sum = sum(nums) return expected_sum - actual_sum
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the missing number in a list of numbers from 1 to n. The function should take the list as input and return the missing number. For example, if the input list is [1, 2, 4, 5], then the function should return 3, as 3 is the missing number.\nAnswer:\nLet's t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 759, "level": 1, "question": "Write a python function to find the missing number in a list of numbers from 1 to n. The function should take the list as input and return the missing number. For example, if the input list is [1, 2, 4, 5], then the function should return 3, as 3 is the...
def compress_string(s): if not s: return "" compressed = [] current_char = s[0] count = 1 for char in s[1:]: if char == current_char: count += 1 else: compressed.append(f"{current_char}{count}") current_char = char count = 1 ...
simplelr_Taco
[ { "content": "Question:\nYou are given the task of creating a simple compression algorithm. The algorithm takes a string of lowercase Latin letters and reduces it by replacing any sequence of consecutive identical letters with that letter followed by the number of occurrences in the sequence. For example, the s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 760, "level": 1, "question": "You are given the task of creating a simple compression algorithm. The algorithm takes a string of lowercase Latin letters and reduces it by replacing any sequence of consecutive identical letters with that letter followed by the number of occurrences i...
def unique_elements(lst): seen = set() unique_list = [] for element in lst: if element not in seen: unique_list.append(element) seen.add(element) return unique_list
simplelr_Evol
[ { "content": "Question:\nConstruct a function that takes in a list of integers and returns a new list containing only the unique elements from the original list, maintaining their original order of appearance. Ensure that the function handles cases where the list might be empty or contain only duplicates effici...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 761, "level": 1, "question": "Construct a function that takes in a list of integers and returns a new list containing only the unique elements from the original list, maintaining their original order of appearance. Ensure that the function handles cases where the list might be empty...
from collections import Counter def find_intersection_with_frequency(list1, list2): """ Find the intersection of two lists, accounting for the frequency of each integer. Parameters: list1 (list): The first list of integers, possibly containing duplicates. list2 (list): The second list of integ...
simplelr_Package
[ { "content": "Question:\nIn this problem, you are given two lists of integers `list1` and `list2`. Each list may contain duplicate integers. Your goal is to find the intersection of these two lists, but you must account for the frequency of each integer in both lists. For example, if an integer appears three ti...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 762, "level": 1, "question": "In this problem, you are given two lists of integers `list1` and `list2`. Each list may contain duplicate integers. Your goal is to find the intersection of these two lists, but you must account for the frequency of each integer in both lists. For examp...
def filter_words_by_length(word_list, min_length): return [word for word in word_list if len(word) >= min_length]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of strings and returns a list of words that have a length greater than or equal to a specified minimum length.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 763, "level": 1, "question": "Create a function that takes a list of strings and returns a list of words that have a length greater than or equal to a specified minimum length.", "split": "train" }
def contains_duplicates(arr): return len(arr) != len(set(arr))
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check if an array contains duplicate values. The function should return True if there are any duplicate values in the array, and False otherwise.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 764, "level": 1, "question": "Write a python function to check if an array contains duplicate values. The function should return True if there are any duplicate values in the array, and False otherwise.", "split": "train" }
import bisect def two_sum_closest(nums, target): if len(nums) < 2: return [-1, -1] # Create a sorted list of tuples containing value and original index sorted_list = sorted(((nums[i], i) for i in range(len(nums))), key=lambda x: x[0]) sorted_values = [x[0] for x in sorted_list] be...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `nums` and an integer `target`, return _the indices of two distinct elements from the array whose sums are closest to_ `target`_. If there are multiple answers, return the pair with the smallest left index_. If there is still a tie, return the pair with the sm...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 765, "level": 1, "question": "Given an array of integers `nums` and an integer `target`, return _the indices of two distinct elements from the array whose sums are closest to_ `target`_. If there are multiple answers, return the pair with the smallest left index_. If there is still ...
def contains_duplicates(input_list: list) -> bool: """ Checks if a list contains any duplicate elements. """ seen = set() for element in input_list: if element in seen: return True seen.add(element) return False if __name__ == "__main__": test_cases = [ [...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Question\n\n#### Objective\nWrite a Python function that determines whether a list contains any duplicate elements.\n\n### Function Signature\n```python\ndef contains_duplicates(input_list: list) -> bool:\n \"\"\"\n Checks if a list contains any duplicate elements.\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 766, "level": 1, "question": "### Coding Question\n\n#### Objective\nWrite a Python function that determines whether a list contains any duplicate elements.\n\n### Function Signature\n```python\ndef contains_duplicates(input_list: list) -> bool:\n \"\"\"\n Checks if a list con...
def generate_fibonacci(n): if n <= 0: return [] elif n == 1: return [0] else: fib_sequence = [0, 1] while len(fib_sequence) < n: next_term = fib_sequence[-1] + fib_sequence[-2] fib_sequence.append(next_term) return fib_sequence
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python function that generates a Fibonacci sequence up to a specified number of terms? If the number of terms is less than or equal to 0, the function should return an empty list. If the number of terms is 1, it should return a list containing only the first Fibonacci ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 767, "level": 1, "question": "Can you provide a Python function that generates a Fibonacci sequence up to a specified number of terms? If the number of terms is less than or equal to 0, the function should return an empty list. If the number of terms is 1, it should return a list co...
def largest_rectangle_area(heights): stack = [-1] # Initialize stack with -1 to handle boundary cases max_area = 0 n = len(heights) for i in range(n): while stack[-1] != -1 and heights[i] < heights[stack[-1]]: # Pop the top element height = heights[stack.pop()] ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of integers called `heights`, representing the heights of buildings in a cityscape. The width of each building is 1. You need to calculate and return the maximum area of a rectangle formed by consecutive buildings. The rectangle's height is defined by the shortest...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 768, "level": 1, "question": "You are given an array of integers called `heights`, representing the heights of buildings in a cityscape. The width of each building is 1. You need to calculate and return the maximum area of a rectangle formed by consecutive buildings. The rectangle's...
from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report, confusion_matrix def classification_task(): # Generate the da...
simplelr_Docs
[ { "content": "Question:\n### Objective\n\nYou are required to generate a synthetic dataset for a classification task using the `make_classification` function from the scikit-learn library, perform data preprocessing, and implement a basic classifier to evaluate the performance on the generated dataset.\n\n### T...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 769, "level": 1, "question": "### Objective\n\nYou are required to generate a synthetic dataset for a classification task using the `make_classification` function from the scikit-learn library, perform data preprocessing, and implement a basic classifier to evaluate the performance ...
def find_min_path(grid: list[list[int]]) -> int: if not grid: return 0 m = len(grid) n = len(grid[0]) if m > 0 else 0 if m == 0 or n == 0: return 0 # Initialize the previous row with the first row of the grid previous = [0] * n previous[0] = grid[0][0] for j in range...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are tasked to write a program that finds the optimal path through a grid, starting from the top-left corner and moving to the bottom-right corner. The grid contains weights for each cell, and you can only move right or down at each step. The goal is to find ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 770, "level": 1, "question": "### Problem Statement\n\nYou are tasked to write a program that finds the optimal path through a grid, starting from the top-left corner and moving to the bottom-right corner. The grid contains weights for each cell, and you can only move right or down ...
def merge_dicts(dict1, dict2): merged = {} all_keys = set(dict1.keys()) | set(dict2.keys()) for key in all_keys: if key in dict1 and key in dict2: value1 = dict1[key] value2 = dict2[key] if isinstance(value1, dict) and isinstance(value2, dict): mer...
simplelr_Filter
[ { "content": "Question:\nWrite a Python code to merge two given dictionaries into one. If any clashes occur, prefer the highest value. The dictionaries may contain lists, sets, and other dictionaries as their values. For nested dictionaries, merge them recursively.\nAnswer:\nLet's think step by step.\n", "r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 771, "level": 1, "question": "Write a Python code to merge two given dictionaries into one. If any clashes occur, prefer the highest value. The dictionaries may contain lists, sets, and other dictionaries as their values. For nested dictionaries, merge them recursively.", "split":...
def zero_anti_diagonal(matrix: list[list[int]]) -> list[list[int]]: """ Zeroes out the anti-diagonal elements in a square matrix. :param matrix: A list of lists representing an n x n matrix. :returns: The modified matrix with anti-diagonal elements set to zero. """ n = len(matrix) resul...
simplelr_Algorithm
[ { "content": "Question:\n### Matrix Diagonal Manipulation\n\n#### Scenario\nAn innovative matrix operation requires modifying a square matrix by zeroing out all the elements in its anti-diagonal. In a square matrix, the anti-diagonal runs from the bottom-left to the top-right of the matrix. \n\n#### Task\nWrite...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 772, "level": 1, "question": "### Matrix Diagonal Manipulation\n\n#### Scenario\nAn innovative matrix operation requires modifying a square matrix by zeroing out all the elements in its anti-diagonal. In a square matrix, the anti-diagonal runs from the bottom-left to the top-right o...
def assign_identifiers(registrations, max_attendees): identifiers = [] current_total = 0 reg_num = 0 # Starts at 0, will be incremented before use for reg in registrations: reg_num += 1 # Current registration number attendee_num = 0 for name in reg: attendee_num += ...
simplelr_Taco
[ { "content": "Question:\nYou are working on managing event registrations for a large conference. Each registration can have multiple attendees, and every attendee should receive a unique identifier. The conference has limited seating, so a maximum number of attendees is specified. The registrations are stored i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 773, "level": 1, "question": "You are working on managing event registrations for a large conference. Each registration can have multiple attendees, and every attendee should receive a unique identifier. The conference has limited seating, so a maximum number of attendees is specifi...
def cocktail_shaker_sort(arr: list) -> list: n = len(arr) if n == 0: return arr start = 0 end = n - 1 swapped = True while swapped: swapped = False last_swap = -1 # Left to right pass for i in range(start, end): if arr[i] > arr[i + 1]: ...
simplelr_Data_Structure
[ { "content": "Question:\nTitle: Cocktail Shaker Sort Implementation\n\n#### Context\nYou have been tasked with sorting an array efficiently using a less commonly used but intriguing sorting method. This method, known as Cocktail Shaker Sort, is a bi-directional variant of Bubble Sort. This algorithm is particul...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 774, "level": 1, "question": "Title: Cocktail Shaker Sort Implementation\n\n#### Context\nYou have been tasked with sorting an array efficiently using a less commonly used but intriguing sorting method. This method, known as Cocktail Shaker Sort, is a bi-directional variant of Bubbl...
def reverse_words_order(s): return ' '.join(s.split()[::-1])
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to reverse the order of words in a string, but keep the characters in each word in the same order. For example, given the string \"Hello world from Alibaba Cloud\", the function should return \"Cloud Alibaba from world Hello\".\nAnswer:\nLet's think step by step....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 775, "level": 1, "question": "Write a python function to reverse the order of words in a string, but keep the characters in each word in the same order. For example, given the string \"Hello world from Alibaba Cloud\", the function should return \"Cloud Alibaba from world Hello\".",...
from collections import Counter def is_balanced(s): if not s: return True counts = Counter(s) return len(set(counts.values())) == 1
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `str` containing only lowercase letters. A string is called **balanced** if every letter appears in it exactly the same number of times. Your task is to determine whether the given string is balanced. Return `true` _if_ `str` _is balanced_. Otherwise, return `fals...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 776, "level": 1, "question": "You are given a string `str` containing only lowercase letters. A string is called **balanced** if every letter appears in it exactly the same number of times. Your task is to determine whether the given string is balanced. Return `true` _if_ `str` _is ...
def balance_parentheses(s: str) -> str: # First pass: left to right, removing excess closing parentheses filtered = [] balance = 0 for char in s: if char == '(': filtered.append(char) balance += 1 else: if balance > 0: filtered.append(c...
simplelr_Package
[ { "content": "Question:\nImplement a function `balance_parentheses(s: str) -> str` that takes a string containing only parentheses characters `(` and `)`, and returns a balanced version of the string by removing the minimum number of parentheses. A string is considered balanced if every opening parenthesis `(` ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 777, "level": 1, "question": "Implement a function `balance_parentheses(s: str) -> str` that takes a string containing only parentheses characters `(` and `)`, and returns a balanced version of the string by removing the minimum number of parentheses. A string is considered balanced...
def distribute_cakes(cakes, guests): if cakes == 0: return "No cakes available for distribution!" elif guests == 0: return "We need to invite some guests first!" else: base = cakes // guests remainder = cakes % guests distribution = [] for i in range(guests): ...
simplelr_Taco
[ { "content": "Question:\nYou've been hired by a local cake shop to help manage their cake distribution for a big event. The shop has a number of cakes ready, and each guest at the event should get at least one cake. If possible, all guests should receive an equal number of cakes. If it's not possible to distrib...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 778, "level": 1, "question": "You've been hired by a local cake shop to help manage their cake distribution for a big event. The shop has a number of cakes ready, and each guest at the event should get at least one cake. If possible, all guests should receive an equal number of cake...
import bisect def target_occurrences(arr, target): left = bisect.bisect_left(arr, target) right = bisect.bisect_right(arr, target) return right - left
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the number of occurrences of a target value in a sorted array. The function should efficiently search the array to find the target value and return its count.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 779, "level": 1, "question": "Write a function to calculate the number of occurrences of a target value in a sorted array. The function should efficiently search the array to find the target value and return its count.", "split": "train" }
from typing import List def find_most_frequent_string(strings: List[str]) -> str: if not strings: return "" counts = {} for s in strings: counts[s] = counts.get(s, 0) + 1 max_freq = max(counts.values()) candidates = [s for s, cnt in counts.items() if cnt == max_freq] return min(...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are given a list of strings which may contain duplicate strings. Your task is to implement a function `find_most_frequent_string` that finds the string which appears the most frequently in the list. If there are ties, return the lexicographically smallest st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 780, "level": 1, "question": "### Problem Statement\n\nYou are given a list of strings which may contain duplicate strings. Your task is to implement a function `find_most_frequent_string` that finds the string which appears the most frequently in the list. If there are ties, return...
def reverse_file_content(input_filename, output_filename): with open(input_filename, 'r') as file: content = file.read() reversed_content = content[::-1] with open(output_filename, 'w') as file: file.write(reversed_content)
simplelr_Filter
[ { "content": "Question:\nI'm stuck on a programming problem and could use some help. I'm trying to create a function in Python that reads a file, reverses the content of the file, and writes it to a new file. How can I achieve this?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 781, "level": 1, "question": "I'm stuck on a programming problem and could use some help. I'm trying to create a function in Python that reads a file, reverses the content of the file, and writes it to a new file. How can I achieve this?", "split": "train" }
def common_elements(matrix): if not matrix: return [] common = set(matrix[0]) for row in matrix[1:]: row_set = set(row) common.intersection_update(row_set) if not common: break return sorted(common)
simplelr_Leetcode
[ { "content": "Question:\nGiven a matrix of integers, write a function to find all the elements that are present in every row of the matrix in increasing order. The function should return the list of these elements sorted in ascending order. \n\nFor example, consider the following matrix:\n```\n[[1, 2, 3, 4, 5],...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 782, "level": 1, "question": "Given a matrix of integers, write a function to find all the elements that are present in every row of the matrix in increasing order. The function should return the list of these elements sorted in ascending order. \n\nFor example, consider the followi...
def max_subarray_sum(nums): """ Finds the sum of the contiguous subarray with the largest sum using Kadane's Algorithm. Args: nums: A list of integers. Returns: An integer representing the sum of the contiguous subarray with the largest sum. """ if not nums: return 0 #...
simplelr_Filter
[ { "content": "Question:\nThis is a problem statement:\n\n**Problem Statement:**\n\nGiven an array of integers, find the contiguous subarray with the largest sum and return its sum.\n\n**Input:** An array of integers.\n\n**Output:** An integer representing the sum of the contiguous subarray with the largest sum....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 783, "level": 1, "question": "This is a problem statement:\n\n**Problem Statement:**\n\nGiven an array of integers, find the contiguous subarray with the largest sum and return its sum.\n\n**Input:** An array of integers.\n\n**Output:** An integer representing the sum of the contigu...
def custom_compress(data: str) -> str: if not data: return "" current_char = data[0] count = 1 result = [] for char in data[1:]: if char == current_char: count += 1 else: if count > 1: result.append(f"{current_char}{count}") ...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Scenario: Optimizing File Storage with Custom Compression\n\nYou are tasked with developing a file storage system that optimizes space usage by compressing files. While standard compression algorithms like gzip or zip are useful, your task is to im...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 784, "level": 1, "question": "### Coding Assessment Question\n\n#### Scenario: Optimizing File Storage with Custom Compression\n\nYou are tasked with developing a file storage system that optimizes space usage by compressing files. While standard compression algorithms like gzip or ...
def longest_winning_streak(nums): if not nums: return 0 n = len(nums) if n == 1: return 0 max_length = 0 current_length = 1 for i in range(1, n): if nums[i] > nums[i - 1]: current_length += 1 if current_length > max_length: max_leng...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of integers `nums` representing the number of points each player scored in a series of games. A player who scores more than the previous one is considered to have a \"winning streak\". Return the **length** of the longest winning streak in the series. If there is no...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 785, "level": 1, "question": "You are given a list of integers `nums` representing the number of points each player scored in a series of games. A player who scores more than the previous one is considered to have a \"winning streak\". Return the **length** of the longest winning st...
from typing import Dict def deep_merge_dicts(dict1: Dict, dict2: Dict) -> Dict: new_dict = {} all_keys = set(dict1.keys()).union(set(dict2.keys())) for key in all_keys: if key in dict1 and key in dict2: val1 = dict1[key] val2 = dict2[key] if isinstance(val1, dict...
simplelr_Package
[ { "content": "Question:\n**Deep Copy Nested Dictionary Merging**\n\nIn Python, dictionaries are essential structures often used for various tasks. A common problem arises when you need to deeply merge nested dictionaries, combining their contents while retaining the full hierarchy.\n\nYour task is to write a fu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 786, "level": 1, "question": "**Deep Copy Nested Dictionary Merging**\n\nIn Python, dictionaries are essential structures often used for various tasks. A common problem arises when you need to deeply merge nested dictionaries, combining their contents while retaining the full hierar...
def longest_common_subsequence(str1: str, str2: str) -> int: m = len(str1) n = len(str2) # Create a DP table with (m+1) rows and (n+1) columns dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if str1[i - 1] == str2[j - 1]: ...
simplelr_Code_Contests
[ { "content": "Question:\n### Finding Common Subsequence\n\nGiven two strings, determine the length of the longest subsequence present in both strings. A subsequence is defined as a sequence derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n\nWri...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 787, "level": 1, "question": "### Finding Common Subsequence\n\nGiven two strings, determine the length of the longest subsequence present in both strings. A subsequence is defined as a sequence derived from another sequence by deleting some or no elements without changing the order...
def compute_avg_response_time(logs: list) -> dict: endpoint_stats = {} for log in logs: parts = log.split(',') if len(parts) != 3: continue endpoint = parts[0] status = parts[1] response_time_str = parts[2] try: response_time = float(respon...
simplelr_Algorithm
[ { "content": "Question:\n### Scenario\n\nIn a large-scale software system, managing and processing logs are critical for monitoring and debugging. A common task involves parsing log records and extracting summary statistics for analysis. You are tasked to implement a log processing function to compute the avera...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 788, "level": 1, "question": "### Scenario\n\nIn a large-scale software system, managing and processing logs are critical for monitoring and debugging. A common task involves parsing log records and extracting summary statistics for analysis. You are tasked to implement a log proces...
def unique_paths_with_obstacles(grid): """ Calculate the number of unique paths in a grid with obstacles. Parameters: grid (List[List[int]]): The input grid with obstacles. Returns: int: The number of unique paths from the top-left to bottom-right corner. """ m = len(grid) if m == ...
simplelr_Package
[ { "content": "Question:\nYour task is to implement a function called `unique_paths_with_obstacles` that calculates the number of unique paths from the top-left corner to the bottom-right corner of a grid, where some cells contain obstacles. This problem will help you understand dynamic programming techniques, p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 789, "level": 1, "question": "Your task is to implement a function called `unique_paths_with_obstacles` that calculates the number of unique paths from the top-left corner to the bottom-right corner of a grid, where some cells contain obstacles. This problem will help you understand...
def find_even_divisible_by_3(n): count = 0 for i in range(1, n + 1): if i % 6 == 0: print(i) count += 1 return count
simplelr_Filter
[ { "content": "Question:\nWrite a function in Python that takes an integer input n and prints all even numbers between 1 and n, but only if the number is also divisible by 3. Additionally, the function should return the count of such numbers found.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 790, "level": 1, "question": "Write a function in Python that takes an integer input n and prints all even numbers between 1 and n, but only if the number is also divisible by 3. Additionally, the function should return the count of such numbers found.", "split": "train" }
def longest_same_char_substring(s): if not s: return 0 max_length = 1 current_length = 1 for i in range(1, len(s)): if s[i] == s[i-1]: current_length += 1 else: if current_length > max_length: max_length = current_length current...
simplelr_Taco
[ { "content": "Question:\nYou are given a string, and you need to determine the length of the longest substring that consists of the same character repeated.\n\nWrite a function that takes a single string as an argument and returns an integer representing the length of the longest substring where all characters ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 791, "level": 1, "question": "You are given a string, and you need to determine the length of the longest substring that consists of the same character repeated.\n\nWrite a function that takes a single string as an argument and returns an integer representing the length of the longe...
def third_stutter(stack: list) -> None: n = len(stack) if n == 0: return stack += [0] * n for i in range(n-1, -1, -1): stack[2*i] = stack[i] stack[2*i + 1] = stack[i]
simplelr_Data_Structure
[ { "content": "Question:\n### Question\nYou are given an implementation of two functions that `stutter` the elements of a stack. The `stutter` function replaces every value in a stack with two occurrences of that value:\n```python\nbottom [3, 7, 1, 14, 9] top\n```\nwill become:\n```python\nbottom [3, 3, 7, 7, 1,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 792, "level": 1, "question": "### Question\nYou are given an implementation of two functions that `stutter` the elements of a stack. The `stutter` function replaces every value in a stack with two occurrences of that value:\n```python\nbottom [3, 7, 1, 14, 9] top\n```\nwill become:\...
def final_string_length(s): a = s.count('a') b = s.count('b') c = s.count('c') max_count = max(a, b, c) sum_others = a + b + c - max_count if max_count > sum_others: return max_count - sum_others else: return (a + b + c) % 2
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` containing only characters 'a', 'b', and 'c'. In one move, you can choose any two adjacent characters of the string and remove them if they are different. Your task is to determine the length of the final string after performing any number of such moves. Retur...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 793, "level": 1, "question": "You are given a string `s` containing only characters 'a', 'b', and 'c'. In one move, you can choose any two adjacent characters of the string and remove them if they are different. Your task is to determine the length of the final string after performi...
import bisect def insert_into_sorted_list(sorted_list, value): if not sorted_list: return [value] new_list = sorted_list.copy() index = bisect.bisect_left(new_list, value) new_list.insert(index, value) return new_list
simplelr_Apps
[ { "content": "Question:\n### Problem: Sorted Array Insertion\n\nWrite a Python function that takes two arguments: a list of integers that is already sorted in ascending order, and an integer value to insert. The function should insert the value into the list in appropriate position to maintain the sorted order ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 794, "level": 1, "question": "### Problem: Sorted Array Insertion\n\nWrite a Python function that takes two arguments: a list of integers that is already sorted in ascending order, and an integer value to insert. The function should insert the value into the list in appropriate posi...
def missing_number(arr): positives = set() for num in arr: if num > 0: positives.add(num) i = 1 while True: if i not in positives: return i i += 1
simplelr_Taco
[ { "content": "Question:\nWrite a function `missing_number(arr)` that takes a list of integers `arr` and returns the smallest positive integer that is missing from the array. The array may contain duplicates and both positive and negative numbers. Ensure that your solution is efficient in time complexity. \n\nFo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 795, "level": 1, "question": "Write a function `missing_number(arr)` that takes a list of integers `arr` and returns the smallest positive integer that is missing from the array. The array may contain duplicates and both positive and negative numbers. Ensure that your solution is ef...
def find_first_occurrence(lst, target): for index, element in enumerate(lst): if element == target: return index return -1
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of strings and a target string, and returns the index of the first occurrence of the target string in the list, or -1 if the target string is not found.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 796, "level": 1, "question": "Write a Python function that takes a list of strings and a target string, and returns the index of the first occurrence of the target string in the list, or -1 if the target string is not found.", "split": "train" }
def string_to_hex(s): return s.encode('utf-8').hex()
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python code snippet to convert a string into its corresponding hexadecimal representation?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 797, "level": 1, "question": "Can you provide a Python code snippet to convert a string into its corresponding hexadecimal representation?", "split": "train" }
def longest_substring_k_distinct(s: str, k: int) -> int: max_length = 0 left = 0 freq = {} for right in range(len(s)): char = s[right] if char in freq: freq[char] += 1 else: freq[char] = 1 # If the number of distinct characters exceeds k, ...
simplelr_Taco
[ { "content": "Question:\nGiven a string `s` consisting of lowercase English letters and an integer `k`, return the length of the longest substring of `s` that contains at most `k` distinct characters.\n\n**Function Signature:**\n```python\ndef longest_substring_k_distinct(s: str, k: int) -> int:\n pass\n```\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 798, "level": 1, "question": "Given a string `s` consisting of lowercase English letters and an integer `k`, return the length of the longest substring of `s` that contains at most `k` distinct characters.\n\n**Function Signature:**\n```python\ndef longest_substring_k_distinct(s: st...
def process_and_write_data(text_file: str, binary_file: str) -> None: try: with open(text_file, 'r', encoding='utf-8') as text_in: with open(binary_file, 'wb') as bin_out: for line in text_in: stripped = line.rstrip('\n') reversed_line = st...
simplelr_Docs
[ { "content": "Question:\n### Python 3.10 I/O Module Assessment\n\n#### Objective:\nDesign a function that reads data from a text file, processes the data, and then writes both the processed and original data to a binary file using efficient buffering techniques.\n\n#### Task:\n1. Implement a function `process_a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 799, "level": 1, "question": "### Python 3.10 I/O Module Assessment\n\n#### Objective:\nDesign a function that reads data from a text file, processes the data, and then writes both the processed and original data to a binary file using efficient buffering techniques.\n\n#### Task:\n...