target
stringlengths
29
3.65k
data_source
stringclasses
12 values
prompt
listlengths
1
1
ability
stringclasses
1 value
reward_model
dict
extra_info
dict
import heapq def kth_smallest(nums, k): if k == 0: return None # Assuming k is 1-based and valid heap = [] for num in nums: if len(heap) < k: heapq.heappush(heap, -num) else: if num < -heap[0]: heapq.heappop(heap) heapq.heappu...
simplelr_Filter
[ { "content": "Question:\nWrite a code snippet to find the kth smallest element in a list. The list can contain duplicates and the kth smallest element can be negative. The list may also be very large, containing millions of elements. However, you are only allowed to use a constant amount of extra space and your...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8600, "level": 1, "question": "Write a code snippet to find the kth smallest element in a list. The list can contain duplicates and the kth smallest element can be negative. The list may also be very large, containing millions of elements. However, you are only allowed to use a cons...
def get_diagonally_adjacent_flags(matrix, i, j): adjacent_flags = [] # Directions for diagonal movements: up-left, up-right, down-left, down-right directions = [(-1, -1), (-1, 1), (1, -1), (1, 1)] for direction in directions: newi, newj = i + direction[0], j + direction[1] # Check if new...
simplelr_Filter
[ { "content": "Question:\nThe flags of six nations are arranged in two rows containing three flags in each row. Assuming that the flags are stored in the computer memory as a 2x3 matrix, find the row and column number for the flag that is diagonally adjacent to the flag in the second row and second column.\n ' F...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8601, "level": 1, "question": "The flags of six nations are arranged in two rows containing three flags in each row. Assuming that the flags are stored in the computer memory as a 2x3 matrix, find the row and column number for the flag that is diagonally adjacent to the flag in the ...
def sum_of_odds(n): if n <= 1: return 0 m = n // 2 return m * m
simplelr_Filter
[ { "content": "Question:\nGiven the erroneous piece of Python code as a basis, identify the bugs and modify the function such that it calculates the sum of all odd numbers up to a given number, not including that number itself. You will also need to implement unit tests to check the correctness of your solution....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8602, "level": 1, "question": "Given the erroneous piece of Python code as a basis, identify the bugs and modify the function such that it calculates the sum of all odd numbers up to a given number, not including that number itself. You will also need to implement unit tests to chec...
def count_zero_substrings(s): total = 0 current = 0 for char in s: if char == '0': current += 1 else: total += current * (current + 1) // 2 current = 0 total += current * (current + 1) // 2 return total
simplelr_Leetcode
[ { "content": "Question:\nGiven a binary string `s`, return the number of substrings with all characters `0`. A substring is defined as a contiguous sequence of characters within the string. You need to count all possible substrings within the given string that consist solely of the character `0`.\n\nFor example...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8603, "level": 1, "question": "Given a binary string `s`, return the number of substrings with all characters `0`. A substring is defined as a contiguous sequence of characters within the string. You need to count all possible substrings within the given string that consist solely o...
import os def update_latex_commands(directory): """ Processes all markdown files in the given directory, enclosing '&&' with '$' signs. """ for filename in os.listdir(directory): if filename.endswith('.md'): file_path = os.path.join(directory, filename) try: ...
simplelr_Filter
[ { "content": "Question:\nWrite me a small python code to do the following: Given a directory with a set of markdown files, the code should search for the characters '&&' in a line and assume this to be a latex command. The code should proceed to enclose these commands with single dollar signs '$'. Additionally,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8604, "level": 1, "question": "Write me a small python code to do the following: Given a directory with a set of markdown files, the code should search for the characters '&&' in a line and assume this to be a latex command. The code should proceed to enclose these commands with sin...
def maximize_teams(groups): sum_g = sum(groups) if sum_g < 4: return 0 count = sum(1 for g in groups if g > 0) if count < 4: return 0 return sum_g // 4
simplelr_Evol
[ { "content": "Question:\nWrite a function `maximize_teams` that takes a list of integers, where each integer represents the number of students in a respective group. The function should return the maximum number of teams that can be formed if each team must consist of exactly 4 students from different groups.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8605, "level": 1, "question": "Write a function `maximize_teams` that takes a list of integers, where each integer represents the number of students in a respective group. The function should return the maximum number of teams that can be formed if each team must consist of exactly ...
def create_brain_network_plot(): import seaborn.objects as so from seaborn import load_dataset # Step 1: Data Import and Preprocessing networks = ( load_dataset( "brain_networks", header=[0, 1, 2], index_col=0 ) .rename_axis("timepoint") ...
simplelr_Docs
[ { "content": "Question:\nAdvanced Data Visualization with seaborn.objects\n\n#### Objective:\nDemonstrate your comprehension of seaborn's `seaborn.objects` module and its capabilities by performing data preprocessing and creating a detailed plot.\n\n#### Problem Statement:\n\n1. **Data Import and Preprocessing*...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8606, "level": 1, "question": "Advanced Data Visualization with seaborn.objects\n\n#### Objective:\nDemonstrate your comprehension of seaborn's `seaborn.objects` module and its capabilities by performing data preprocessing and creating a detailed plot.\n\n#### Problem Statement:\n\n...
from collections import deque def calculate_averages(errors): """ Calculate the average number of errors for each 3-day window. Args: errors (list): A list of integers representing the number of errors on the first 15 days of the month. Returns: list: A list of averages for ea...
simplelr_Filter
[ { "content": "Question:\nHere is a list of integers representing the number of errors on the first 15 days of the month:\n1, 5, 3, 2, 7, 0, 2, 5, 1, 4, 3, 8, 6, 0, 4\n\nUsing a queue data structure, implement a function in Python to calculate the average number of errors for a 3-day window. \n\nThe queue will b...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8607, "level": 1, "question": "Here is a list of integers representing the number of errors on the first 15 days of the month:\n1, 5, 3, 2, 7, 0, 2, 5, 1, 4, 3, 8, 6, 0, 4\n\nUsing a queue data structure, implement a function in Python to calculate the average number of errors for a...
def reverse_words(input_str): words = input_str.split() reversed_words = words[::-1] return ' '.join(reversed_words)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to reverse the words in a string. For example, if the input string is \"I am a student\", the output should be \"student a am I\".\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8608, "level": 1, "question": "Write a python function to reverse the words in a string. For example, if the input string is \"I am a student\", the output should be \"student a am I\".", "split": "train" }
def max_subarray_sum(arr): if not arr: return 0 # Handles empty array case max_current = max_global = arr[0] for num in arr[1:]: max_current = max(num, max_current + num) if max_current > max_global: max_global = max_current return max_global
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the maximum subarray sum in an array that contains both positive and negative integers. This is known as Kadane's algorithm. How would you code this in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8609, "level": 1, "question": "Write a function to find the maximum subarray sum in an array that contains both positive and negative integers. This is known as Kadane's algorithm. How would you code this in Python?", "split": "train" }
def groupby_sum(data, group_by, sum_key): groups = {} for row in data: # Create a tuple key based on the group_by keys key = tuple(row[gb] for gb in group_by) # Get the value to sum, defaulting to 0 if not present value = row.get(sum_key, 0) # Update the groups dictionary...
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that implements a simplified version of the `groupby` and `sum` operations on a list of dictionaries, similar to how it's done in pandas. The function should take a list of dictionaries, where each dictionary represents a row of data with column names as keys. I...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8610, "level": 1, "question": "Create a Python function that implements a simplified version of the `groupby` and `sum` operations on a list of dictionaries, similar to how it's done in pandas. The function should take a list of dictionaries, where each dictionary represents a row o...
def is_anagram(s: str, t: str) -> bool: if len(s) != len(t): return False count_s = [0] * 26 count_t = [0] * 26 for c in s: count_s[ord(c) - ord('a')] += 1 for c in t: count_t[ord(c) - ord('a')] += 1 return count_s == count_t
simplelr_Codeforces
[ { "content": "Question:\nGiven two strings, `s` and `t`, determine whether `t` is an anagram of `s`. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Note that the comparison is case-sensitive and whitespace is...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8611, "level": 1, "question": "Given two strings, `s` and `t`, determine whether `t` is an anagram of `s`. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Note that the comparison ...
import re def extract_urls(text): # Regular expression pattern to find URLs starting with http://, https://, or www. pattern = r'(https?://\S+|www\.\S+)' # Find all matches in the text urls = re.findall(pattern, text) return urls
simplelr_Filter
[ { "content": "Question:\nCreate a Python function to extract all URLs from a given string using regular expressions.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8612, "level": 1, "question": "Create a Python function to extract all URLs from a given string using regular expressions.", "split": "train" }
import string from collections import defaultdict def word_frequency(text: str) -> dict: if not text.strip(): return {} words = text.lower().split() frequency = defaultdict(int) for word in words: # Strip leading and trailing punctuation word_clean = word.strip(string.punctuatio...
simplelr_Algorithm
[ { "content": "Question:\n### Question: Develop a Simple Text Analysis Tool\n\n#### Context\nText analysis is an essential aspect of natural language processing, where words and their frequencies in a document are often analyzed to understand better the document's content. This task requires implementing a basic...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8613, "level": 1, "question": "### Question: Develop a Simple Text Analysis Tool\n\n#### Context\nText analysis is an essential aspect of natural language processing, where words and their frequencies in a document are often analyzed to understand better the document's content. This...
def calculate_average(numbers): if not numbers: return 0 return sum(numbers) / len(numbers) # Example usage numbers_list = [1, 2, 3, 4, 5] average = calculate_average(numbers_list) print(f"The average is: {average}")
simplelr_Filter
[ { "content": "Question:\nWrite a simple Python script that implements a function to calculate the average of a given list of numbers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8614, "level": 1, "question": "Write a simple Python script that implements a function to calculate the average of a given list of numbers.", "split": "train" }
def reorder_products(inventory: dict, threshold: int) -> list: # Check if inventory is empty if not inventory: raise Exception("Inventory cannot be empty") # Check if threshold is non-negative if threshold < 0: raise Exception("Threshold must be a non-negative integer") # C...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\nYou have been tasked to develop a new system for managing the inventory of products in a retail store. One of the functionalities needed is a feature to reorder products when their quantities fall below a certain threshold. You need to write a function ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8615, "level": 1, "question": "### Coding Assessment Question\n\nYou have been tasked to develop a new system for managing the inventory of products in a retail store. One of the functionalities needed is a feature to reorder products when their quantities fall below a certain thres...
def cubes_dict(N): """Returns a dictionary with keys from 1 to N and values as their cubes.""" return {i: i ** 3 for i in range(1, N + 1)}
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to create a dictionary with keys as numbers from 1 to N and values as their cubes. For example, if N=3, the output should be `{1: 1, 2: 8, 3: 27}`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8616, "level": 1, "question": "Write a python function to create a dictionary with keys as numbers from 1 to N and values as their cubes. For example, if N=3, the output should be `{1: 1, 2: 8, 3: 27}`.", "split": "train" }
import bisect def insertion_sort_unique(arr): sorted_arr = [] for num in arr: if not sorted_arr: sorted_arr.append(num) else: idx = bisect.bisect_left(sorted_arr, num) if idx < len(sorted_arr) and sorted_arr[idx] == num: continue s...
simplelr_Data_Structure
[ { "content": "Question:\n### Coding Challenge: Enhanced Insertion Sort\n\n#### Problem Statement\nYou are provided with an array of integers. Your task is to implement an enhanced version of the Insertion Sort algorithm that not only sorts the array but also:\n - Removes all duplicate elements during the sorti...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8617, "level": 1, "question": "### Coding Challenge: Enhanced Insertion Sort\n\n#### Problem Statement\nYou are provided with an array of integers. Your task is to implement an enhanced version of the Insertion Sort algorithm that not only sorts the array but also:\n - Removes all ...
from collections import Counter import heapq def reorder_string(s: str) -> str: if not s: return '' count = Counter(s) n = len(s) max_freq = max(count.values()) if max_freq > (n + 1) // 2: return '' heap = [] for char, cnt in count.items(): heapq.heapp...
simplelr_Taco
[ { "content": "Question:\nYou are given a string consisting of lowercase alphabets. Your task is to reorder the string in such a way that no two adjacent characters are the same. If it is not possible to reorder the string in such a way, return an empty string.\n\nImplement a function `reorder_string(s: str) -> ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8618, "level": 1, "question": "You are given a string consisting of lowercase alphabets. Your task is to reorder the string in such a way that no two adjacent characters are the same. If it is not possible to reorder the string in such a way, return an empty string.\n\nImplement a f...
import numpy as np def can_divide_evenly(arr, value): """ Checks if a singular value can divide evenly into each element of a NumPy array. Parameters: arr (numpy.ndarray): The NumPy array to check. value (int or float): The value to check for even division. Returns: bool: True if ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check if a singular value can divide evenly into a NumPy array.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8619, "level": 1, "question": "Write a python function to check if a singular value can divide evenly into a NumPy array.", "split": "train" }
def twos_complement_custom(number: int) -> str: if not isinstance(number, int): raise ValueError("Input must be an integer.") if number >= 0: raise ValueError("Input must be a negative integer.") value = (1 << 32) + number bits = [] for i in range(31, -1, -1): bit = (val...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are developing a component of a low-level operating system that requires converting signed integers into their binary two’s complement representation. Given a negative integer, your task is to implement a function that converts this integer into its correspond...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8620, "level": 1, "question": "### Problem Statement\nYou are developing a component of a low-level operating system that requires converting signed integers into their binary two’s complement representation. Given a negative integer, your task is to implement a function that conver...
from collections import deque def shortest_path(graph, start, end): if start not in graph or end not in graph: return [] queue = deque([start]) visited = {start: None} # Using a dictionary to track the parent of each node while queue: current = queue.popleft() if curr...
simplelr_Data_Structure
[ { "content": "Question:\n### Graph Traversal Assessment\n\n#### Objective\nImplement a function to determine the shortest path between two nodes in an unweighted graph using Breadth First Search (BFS). You may assume that the graph is represented using an adjacency list.\n\n#### Specifications\n\n* **Input**:\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8621, "level": 1, "question": "### Graph Traversal Assessment\n\n#### Objective\nImplement a function to determine the shortest path between two nodes in an unweighted graph using Breadth First Search (BFS). You may assume that the graph is represented using an adjacency list.\n\n##...
def square_root(x): """ This function calculates the square root of a given number. Args: x: The number to calculate the square root of. Returns: The square root of the number, or None if the input is negative. """ if x < 0: return None else: return x ** 0.5
simplelr_Filter
[ { "content": "Question:\nThis is the code:\n\n```python\ndef square_root(x):\n \"\"\"\n This function calculates the square root of a given number.\n\n Args:\n x: The number to calculate the square root of.\n\n Returns:\n The square root of the number, or None if the input is negative.\n \"\"\"\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8622, "level": 1, "question": "This is the code:\n\n```python\ndef square_root(x):\n \"\"\"\n This function calculates the square root of a given number.\n\n Args:\n x: The number to calculate the square root of.\n\n Returns:\n The square root of the number, or None if...
import bisect def max_buffer_time(packet_sizes, total_buffer_size): n = len(packet_sizes) if n == 0: return 0 # Assuming buffer time is 0 when there are no packets prefix_sum = [0] * (n + 1) for i in range(1, n + 1): prefix_sum[i] = prefix_sum[i - 1] + packet_sizes[i - 1] ...
simplelr_Algorithm
[ { "content": "Question:\n### Context\nYou are developing a video streaming service that needs to buffer video data efficiently. To optimize performance, you have been assigned to implement a feature that calculates the maximum buffer time that can be provided without disrupting the streaming service. This invol...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8623, "level": 1, "question": "### Context\nYou are developing a video streaming service that needs to buffer video data efficiently. To optimize performance, you have been assigned to implement a feature that calculates the maximum buffer time that can be provided without disruptin...
import math def jump_search(arr, target): if not arr: return -1 n = len(arr) m = int(math.sqrt(n)) left, right = 0, 0 # Find the block where the target could be while right < n and arr[right] < target: left = right right += m # Adjust right to be within array bounds ...
simplelr_Data_Structure
[ { "content": "Question:\n### Jump Search Algorithm | Advanced Coding Assessment\n\nGiven a sorted array of integers and a target value, implement the Jump Search algorithm to find the index of the target value in the array. If the target value is not present in the array, the function should return `-1`.\n\n###...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8624, "level": 1, "question": "### Jump Search Algorithm | Advanced Coding Assessment\n\nGiven a sorted array of integers and a target value, implement the Jump Search algorithm to find the index of the target value in the array. If the target value is not present in the array, the ...
from typing import List def can_split_array(nums: List[int]) -> bool: total = sum(nums) if total % 2 != 0: return False target = total // 2 dp = {0: 0} # Maps sum to the minimum number of elements needed to achieve it for num in nums: new_dp = dp.copy() for s in dp: ...
simplelr_Algorithm
[ { "content": "Question:\n### Array Splitter Problem\n\nYou are given an array consisting of `N` integers. Your task is to determine if you can split this array into two non-empty subsets such that the sum of the elements in both subsets is equal. Return `True` if such a split is possible, otherwise, return `Fal...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8625, "level": 1, "question": "### Array Splitter Problem\n\nYou are given an array consisting of `N` integers. Your task is to determine if you can split this array into two non-empty subsets such that the sum of the elements in both subsets is equal. Return `True` if such a split ...
from datetime import datetime import pytz def convert_timezone(timestamp, timezone): # Parse the input timestamp into a naive datetime object naive_datetime = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S') # Localize the naive datetime to UTC utc_datetime = naive_datetime.replace(tzinfo=pytz.UT...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to perform timezone conversion for a given UTC timestamp. The function should take two arguments: `timestamp` (a string representing the UTC time in the format `%Y-%m-%d %H:%M:%S`) and `timezone` (a string representing the target timezone, e.g., 'US/Pacific', 'Eu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8626, "level": 1, "question": "Write a Python function to perform timezone conversion for a given UTC timestamp. The function should take two arguments: `timestamp` (a string representing the UTC time in the format `%Y-%m-%d %H:%M:%S`) and `timezone` (a string representing the targe...
import bisect from typing import List, Optional def two_sum_indices(array: List[int], target: int) -> Optional[List[int]]: for i in range(len(array)): needed = target - array[i] j = bisect.bisect_left(array, needed, i + 1) if j < len(array) and array[j] == needed: return [i, j] ...
simplelr_Apps
[ { "content": "Question:\nGiven a sorted array of unique integers and a target integer, write a function that returns the indices of the first two numbers that add up to the target. If no such numbers exist, return `null`.\n\nFor example:\n```\n array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n target = 10\n```\nThe p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8627, "level": 1, "question": "Given a sorted array of unique integers and a target integer, write a function that returns the indices of the first two numbers that add up to the target. If no such numbers exist, return `null`.\n\nFor example:\n```\n array = [1, 2, 3, 4, 5, 6, 7, 8...
from collections import Counter def count_characters(words, chars): chars_count = Counter(chars) total_length = 0 for word in words: word_count = Counter(word) is_good = True for char, count in word_count.items(): if chars_count.get(char, 0) < count: is_g...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of strings `words` and a string `chars`. A string is considered **good** if it can be formed by characters in `chars` (each character can only be used once). Return the length of the total number of characters in all **good** strings in `words`. You may assume the s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8628, "level": 1, "question": "You are given a list of strings `words` and a string `chars`. A string is considered **good** if it can be formed by characters in `chars` (each character can only be used once). Return the length of the total number of characters in all **good** strin...
import math def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False max_divisor = int(math.sqrt(n)) + 1 for d in range(3, max_divisor, 2): if n % d == 0: return False return True
simplelr_Filter
[ { "content": "Question:\nWrite a python script that can determine if a given number is a prime number or not. The script should be efficient and concise.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8629, "level": 1, "question": "Write a python script that can determine if a given number is a prime number or not. The script should be efficient and concise.", "split": "train" }
from typing import List def min_cost(matrix: List[List[int]]) -> int: if not matrix or not matrix[0]: return 0 m = len(matrix) n = len(matrix[0]) # Initialize the previous row dp_prev = [0] * n dp_prev[0] = matrix[0][0] for j in range(1, n): dp_prev[j] = dp_prev[j - 1] ...
simplelr_Code_Contests
[ { "content": "Question:\nConsider a matrix of integers where each element represents the cost to visit that cell. You start at the top-left cell and want to reach the bottom-right cell while minimizing the cost. You can move only right or down at each step.\n\nWrite a function that determines the minimum cost t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8630, "level": 1, "question": "Consider a matrix of integers where each element represents the cost to visit that cell. You start at the top-left cell and want to reach the bottom-right cell while minimizing the cost. You can move only right or down at each step.\n\nWrite a function...
from collections import defaultdict def count_rectangles(points): x_to_ys = defaultdict(set) for x, y in points: x_to_ys[x].add(y) xs = [x for x in x_to_ys if len(x_to_ys[x]) >= 2] total = 0 n = len(xs) for i in range(n): for j in range(i + 1, n): x1 = xs[i...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a **0-indexed** integer array `points` where `points[i] = [xi, yi]` represents a point in a 2D coordinate plane. A **rectangle** is defined by its diagonal points `(x1, y1)` and `(x2, y2)` such that its sides are parallel to the `x`-axis and `y`-axis. You are asked to det...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8631, "level": 1, "question": "You are given a **0-indexed** integer array `points` where `points[i] = [xi, yi]` represents a point in a 2D coordinate plane. A **rectangle** is defined by its diagonal points `(x1, y1)` and `(x2, y2)` such that its sides are parallel to the `x`-axis ...
def digital_root(n): if n == 0: return 0 return 9 if n % 9 == 0 else n % 9
simplelr_Taco
[ { "content": "Question:\n# Objective\n\nWrite a function `digital_root` to compute the digital root of a non-negative integer `n`. The digital root of a non-negative integer is defined as the single digit obtained by iteratively summing the digits of the number until a single digit is produced.\n\n## Examples\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8632, "level": 1, "question": "# Objective\n\nWrite a function `digital_root` to compute the digital root of a non-negative integer `n`. The digital root of a non-negative integer is defined as the single digit obtained by iteratively summing the digits of the number until a single ...
import random import math def estimate_pi(n): points_inside = 0 for _ in range(n): x = random.uniform(0, 1) y = random.uniform(0, 1) if x**2 + y**2 <= 1: points_inside += 1 return 4 * points_inside / n # Number of points to simulate n = 1000000 pi_estimate = estimate_pi...
simplelr_Filter
[ { "content": "Question:\nSo, I want to demonstrate a Monte Carlo simulation that estimates π (pi), using Python. That seems like a wonderful way to see how it works. Can you write it with me?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8633, "level": 1, "question": "So, I want to demonstrate a Monte Carlo simulation that estimates π (pi), using Python. That seems like a wonderful way to see how it works. Can you write it with me?", "split": "train" }
def maxProfit(prices): if len(prices) < 2: return 0 buy1 = -float('inf') sell1 = 0 buy2 = -float('inf') sell2 = 0 for price in prices: new_buy1 = max(buy1, -price) new_sell1 = max(sell1, buy1 + price) new_buy2 = max(buy2, sell1 - price) new_sell2...
simplelr_Evol
[ { "content": "Question:\nConsider a stock market scenario where you are given an array of stock prices for consecutive days. Each element in the array represents the stock price on a particular day. Your goal is to determine the maximum possible profit you can achieve by making at most two transactions (a trans...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8634, "level": 1, "question": "Consider a stock market scenario where you are given an array of stock prices for consecutive days. Each element in the array represents the stock price on a particular day. Your goal is to determine the maximum possible profit you can achieve by makin...
def longest_substring_without_repeating_characters(s: str) -> str: """ Finds the longest substring without repeating characters. Args: s: The input string. Returns: The longest substring without repeating characters. """ if not s: return "" last_seen = {} m...
simplelr_Filter
[ { "content": "Question:\nThis is a Python string manipulation problem:\n\n**Problem: Given a string s, return the longest substring without repeating characters.**\n\n**Example:**\n\n```\nInput: s = \"abcabcbb\"\nOutput: \"abc\"\n\nInput: s = \"bbbbb\"\nOutput: \"b\"\n\nInput: s = \"pwwkew\"\nOutput: \"wke\"\n`...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8635, "level": 1, "question": "This is a Python string manipulation problem:\n\n**Problem: Given a string s, return the longest substring without repeating characters.**\n\n**Example:**\n\n```\nInput: s = \"abcabcbb\"\nOutput: \"abc\"\n\nInput: s = \"bbbbb\"\nOutput: \"b\"\n\nInput:...
import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import Ridge, Lasso from sklearn.metrics import mean_squared_error from typing import Tuple def evaluate_linear_models( X: np.ndarray, y: np.ndarray, test_size: float = 0.2, random_state: int = 42, ...
simplelr_Docs
[ { "content": "Question:\n### Task\n\nYou are required to implement a Python function to perform that makes use of Ridge Regression and Lasso Regression from the `scikit-learn` library. This function should split the provided dataset into training and testing sets, train both models on the training set, and eval...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8636, "level": 1, "question": "### Task\n\nYou are required to implement a Python function to perform that makes use of Ridge Regression and Lasso Regression from the `scikit-learn` library. This function should split the provided dataset into training and testing sets, train both m...
def discrete_difference(arr, step): if step <= 0: raise ValueError("Step must be a positive integer.") return [arr[i] - arr[i - step] for i in range(step, len(arr))]
simplelr_Filter
[ { "content": "Question:\nDesign a Python function that performs a more general discrete difference calculation on a given array. The function should accept two parameters: the array (`arr`) from which to calculate the differences, and the step size (`step`) for the differencing. The function should return a new...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8637, "level": 1, "question": "Design a Python function that performs a more general discrete difference calculation on a given array. The function should accept two parameters: the array (`arr`) from which to calculate the differences, and the step size (`step`) for the differencin...
from collections import defaultdict def max_energy(knights): freq = defaultdict(int) for x in knights: freq[x] += 1 while True: changed = False # Get the current keys and sort them xs = sorted(freq.keys()) for x in xs: if x in freq: # Ensure x is st...
simplelr_Taco
[ { "content": "Question:\n# Task\nThe Magic Kingdom needs to transport a group of knights to a distant land. To conserve energy on the long journey, they have decided to use a special teleportation system that works as follows:\n- Knights are represented by an array of positive integers where each integer repres...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8638, "level": 1, "question": "# Task\nThe Magic Kingdom needs to transport a group of knights to a distant land. To conserve energy on the long journey, they have decided to use a special teleportation system that works as follows:\n- Knights are represented by an array of positive...
def find_unique_rows_with_highest_sum(matrix): if not matrix: return [] # Compute the sum for each row once sums = [sum(row) for row in matrix] max_sum = max(sums) seen = set() result = [] for i in range(len(matrix)): if sums[i] == max_sum: row = matrix[i] ...
simplelr_Filter
[ { "content": "Question:\nGiven a matrix of integers, write a Python program to find all unique rows that have the highest sum of elements. If there are multiple rows with the same highest sum, include all of them in the output. Also, check if any of the rows are exactly the same (i.e., identical elements in the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8639, "level": 1, "question": "Given a matrix of integers, write a Python program to find all unique rows that have the highest sum of elements. If there are multiple rows with the same highest sum, include all of them in the output. Also, check if any of the rows are exactly the sa...
import re def count_distinct_words(text): words = re.findall(r"[a-zA-Z'-]+", text) unique_words = set(word.lower() for word in words) return len(unique_words)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to count the number of distinct words in a given text.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8640, "level": 1, "question": "Write a function to count the number of distinct words in a given text.", "split": "train" }
def prime_factors(n): factors = [] if n < 2: return factors while n % 2 == 0: factors.append(2) n = n // 2 i = 3 while i * i <= n: while n % i == 0: factors.append(i) n = n // i i += 2 if n > 1: factors.append(n) return ...
simplelr_Filter
[ { "content": "Question:\nDevelop a Python function that accepts a positive integer as input and returns a list of its prime factors, arranged in ascending order. This task requires the function to identify and list all the prime numbers that, when multiplied together, reconstruct the original input number.\nAns...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8641, "level": 1, "question": "Develop a Python function that accepts a positive integer as input and returns a list of its prime factors, arranged in ascending order. This task requires the function to identify and list all the prime numbers that, when multiplied together, reconstr...
from typing import List def find_longest_arith_seq(arr: List[int]) -> int: n = len(arr) if n == 0: return 0 # Though the problem states n >= 1, this handles edge cases. max_length = 1 dp = [{} for _ in range(n)] for i in range(n): for j in range(i): d = arr[i] - ar...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Problem Statement\nWrite a function `find_longest_arith_seq(arr: List[int]) -> int` that determines the length of the longest arithmetic subsequence in a given list of integers.\n\n### Function Signature\n```python\ndef find_longest_arith_seq(arr: ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8642, "level": 1, "question": "### Coding Assessment Question\n\n#### Problem Statement\nWrite a function `find_longest_arith_seq(arr: List[int]) -> int` that determines the length of the longest arithmetic subsequence in a given list of integers.\n\n### Function Signature\n```pytho...
def climb_stairs_k(steps: int, k: int) -> int: if steps == 0: return 1 dp = [0] * (steps + 1) dp[0] = 1 current_sum = 0 for i in range(1, steps + 1): current_sum += dp[i - 1] if i > k: current_sum -= dp[i - k - 1] dp[i] = current_sum return dp[steps]
simplelr_Data_Structure
[ { "content": "Question:\nYou are given a problem where you need to find out the number of distinct ways to reach the top of a staircase. The staircase has `steps` number of steps, and you can either climb 1, 2, 3, ..., up to `k` steps at a time. Your goal is to write an optimized function to determine the numbe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8643, "level": 1, "question": "You are given a problem where you need to find out the number of distinct ways to reach the top of a staircase. The staircase has `steps` number of steps, and you can either climb 1, 2, 3, ..., up to `k` steps at a time. Your goal is to write an optimi...
def sum_of_evens(numbers): total = 0 for num in numbers: if num % 2 == 0: total += num return total
simplelr_Filter
[ { "content": "Question:\nThis is an exercise for practicing Python lists.\n\nYou will be given a list of integers, and your task is to write a Python function that returns the sum of all the even numbers in the list.\n\n**For example:**\n\n```python\nnumbers = [1, 2, 3, 4, 5, 6]\nsum_of_evens(numbers) == 12\n``...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8644, "level": 1, "question": "This is an exercise for practicing Python lists.\n\nYou will be given a list of integers, and your task is to write a Python function that returns the sum of all the even numbers in the list.\n\n**For example:**\n\n```python\nnumbers = [1, 2, 3, 4, 5, ...
from itertools import combinations def four_sum(nums, target): n = len(nums) if n < 4: return [] result = set() for quad_indices in combinations(range(n), 4): a, b, c, d = quad_indices current_sum = nums[a] + nums[b] + nums[c] + nums[d] if current_sum == target: ...
simplelr_Taco
[ { "content": "Question:\nYou are given a list of integers `nums` and a target integer `target`. Your task is to determine if there exist four elements in the list whose sum is equal to `target`. Write a function that takes a list of integers and their target sum, and returns all unique quadruplets `[nums[a], nu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8645, "level": 1, "question": "You are given a list of integers `nums` and a target integer `target`. Your task is to determine if there exist four elements in the list whose sum is equal to `target`. Write a function that takes a list of integers and their target sum, and returns a...
def merge_intervals(intervals): if not intervals: return [] # Sort the intervals by their start and then end points sorted_intervals = sorted(intervals, key=lambda x: (x[0], x[1])) merged = [list(sorted_intervals[0])] for i in range(1, len(sorted_intervals)): current_start,...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of intervals, `intervals`, where `intervals[i] = [starti, endi]` represents a closed interval `[starti, endi]`. The interval length is defined as `endi - starti`. Merge all overlapping intervals, and return _a list of the merged intervals sorted by the starting poin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8646, "level": 1, "question": "You are given a list of intervals, `intervals`, where `intervals[i] = [starti, endi]` represents a closed interval `[starti, endi]`. The interval length is defined as `endi - starti`. Merge all overlapping intervals, and return _a list of the merged in...
def count_and_get_indices(lst, elem): indices = [i for i, x in enumerate(lst) if x == elem] return (len(indices), indices)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that not only counts the number of occurrences of a specified element in a list, but also returns the indices of those occurrences. For example, if you're dealing with the list `[1, 2, 3, 2, 4, 2]` and the specified element is `2`, your function should return a tuple `...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8647, "level": 1, "question": "Create a function that not only counts the number of occurrences of a specified element in a list, but also returns the indices of those occurrences. For example, if you're dealing with the list `[1, 2, 3, 2, 4, 2]` and the specified element is `2`, yo...
import csv from collections import defaultdict def process_expense_data(file_path): """ Process financial data from a CSV file and return a summary of expenses by category. Args: file_path (str): Path to the CSV file containing transaction data. Returns: dict: A dictionary summarizing...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question:\n\n#### Context:\nYou are developing a system that helps users manage their personal expenses. Part of this system requires the extraction and processing of financial data from various sources such as bank statements in CSV format. You need to ensure the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8648, "level": 1, "question": "### Coding Assessment Question:\n\n#### Context:\nYou are developing a system that helps users manage their personal expenses. Part of this system requires the extraction and processing of financial data from various sources such as bank statements in ...
from collections import Counter def rearrange_string(s): cnt = Counter(s) max_freq = max(cnt.values()) if cnt else 0 if max_freq > (len(s) + 1) // 2: return "" result = [] last_char = None while cnt: # Collect all possible candidates that are not the last character and...
simplelr_Code_Contests
[ { "content": "Question:\nGiven a string `$s$` consisting of lowercase letters, rearrange the characters of the string so that no two adjacent characters are the same. If it is not possible to do this, return an empty string.\n\nConstraints:\n\n* The length of the string will be in the range $[1, 5000]$.\n\nInpu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8649, "level": 1, "question": "Given a string `$s$` consisting of lowercase letters, rearrange the characters of the string so that no two adjacent characters are the same. If it is not possible to do this, return an empty string.\n\nConstraints:\n\n* The length of the string will b...
def remove_duplicates(nums): seen = set() result = [] for num in nums: if num not in seen: result.append(num) seen.add(num) return result
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of integers and returns a new list with all duplicates removed. The order of the elements in the returned list should be the same as the order in which they first appeared in the input list. Use the `set` data structure to help you solve this pr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8650, "level": 1, "question": "Write a Python function that takes a list of integers and returns a new list with all duplicates removed. The order of the elements in the returned list should be the same as the order in which they first appeared in the input list. Use the `set` data ...
def maximum_product_of_three(nums): nums.sort() candidate1 = nums[-1] * nums[-2] * nums[-3] candidate2 = nums[0] * nums[1] * nums[-1] return max(candidate1, candidate2)
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers, find the maximum product of any three numbers in the array. Return the maximum product.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8651, "level": 1, "question": "Given an array of integers, find the maximum product of any three numbers in the array. Return the maximum product.", "split": "train" }
def LongestSubstring(s): char_index = {} left = 0 max_len = 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_len = right - left + 1 if current...
simplelr_Taco
[ { "content": "Question:\n## Longest Substring Without Repeating Characters\n\n* Write a function named ```LongestSubstring``` that takes a string parameter and returns the length of the longest substring without repeating characters.\n\n* A substring is a contiguous sequence of characters within a string. Ident...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8652, "level": 1, "question": "## Longest Substring Without Repeating Characters\n\n* Write a function named ```LongestSubstring``` that takes a string parameter and returns the length of the longest substring without repeating characters.\n\n* A substring is a contiguous sequence o...
def is_palindrome(s): # Clean the string by keeping only alphanumeric characters and converting to lowercase cleaned = [c.lower() for c in s if c.isalnum()] cleaned_str = ''.join(cleaned) # Check if the cleaned string is the same forwards and backwards return cleaned_str == cleaned_str[::-1]
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes a string as input and returns True if the string is a palindrome, ignoring spaces, punctuation, and capitalization, and False otherwise. Ensure that the function handles a variety of character types, including letters, numbers, and symbols, and performs effic...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8653, "level": 1, "question": "Write a function that takes a string as input and returns True if the string is a palindrome, ignoring spaces, punctuation, and capitalization, and False otherwise. Ensure that the function handles a variety of character types, including letters, numbe...
from bs4 import BeautifulSoup def extract_links(html_content): soup = BeautifulSoup(html_content, 'html.parser') links = [] for tag in soup.find_all('a'): href = tag.get('href') if href: links.append(href) return links
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that extracts all the links from an HTML document?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8654, "level": 1, "question": "How can I create a Python function that extracts all the links from an HTML document?", "split": "train" }
def ensure_sorted(arr): if len(arr) <= 1: return arr is_sorted = True for i in range(len(arr) - 1): if arr[i] > arr[i+1]: is_sorted = False break return arr if is_sorted else sorted(arr)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that checks if an array is sorted in non-decreasing order. If not, sort the array and then return it. If the array is already sorted, simply return the array as is.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8655, "level": 1, "question": "Create a function that checks if an array is sorted in non-decreasing order. If not, sort the array and then return it. If the array is already sorted, simply return the array as is.", "split": "train" }
def product_except_self(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:\nCreate a function that accepts a list of positive integers and returns a new list where each element is the product of all the numbers in the original list except the one at the current position.\n\nThe function should not use division to solve this problem. The length of the input list...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8656, "level": 1, "question": "Create a function that accepts a list of positive integers and returns a new list where each element is the product of all the numbers in the original list except the one at the current position.\n\nThe function should not use division to solve this pr...
from typing import List, Optional def average_excluding_extremes(scores: List[int]) -> Optional[float]: if len(scores) < 3: return None sorted_scores = sorted(scores) trimmed_scores = sorted_scores[1:-1] average = sum(trimmed_scores) / len(trimmed_scores) return round(average, 2)
simplelr_Algorithm
[ { "content": "Question:\n### Scenario\nYou have been contacted by an educational platform that wants to analyze students' performance. They need a function to help determine the average scores of students, excluding the highest and lowest scores to avoid potential biases from outliers.\n\n### Problem Statement\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8657, "level": 1, "question": "### Scenario\nYou have been contacted by an educational platform that wants to analyze students' performance. They need a function to help determine the average scores of students, excluding the highest and lowest scores to avoid potential biases from ...
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 # Example usage print(f"Is 17 a prime? {is_prime(17)}...
simplelr_Filter
[ { "content": "Question:\nDesign a Python function that determines if a given number is a prime number. The function should be named `is_prime` and should take a single integer as an argument. Additionally, provide a code snippet that uses this function to check and print whether the numbers 17 and 20 are prime....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8658, "level": 1, "question": "Design a Python function that determines if a given number is a prime number. The function should be named `is_prime` and should take a single integer as an argument. Additionally, provide a code snippet that uses this function to check and print wheth...
def group_anagrams(words): groups = {} for word in words: key = ''.join(sorted(word)) if key in groups: groups[key].append(word) else: groups[key] = [word] return list(groups.values())
simplelr_Apps
[ { "content": "Question:\nAn anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Given a list of words, your task is to group the anagrams together. Two words are anagrams if they contain the exact same characters wit...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8659, "level": 1, "question": "An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Given a list of words, your task is to group the anagrams together. Two words are anagrams if they co...
import json def extract_properties(json_file_path): try: with open(json_file_path, 'r') as file: data = json.load(file) properties = { 'name': data.get('name'), 'version': data.get('version'), 'author': data.get('author') }...
simplelr_Filter
[ { "content": "Question:\nIf I have a document that contains a property list with various properties and a properties.json file, how can I generate a Python code snippet to read this properties.json file and extract specific properties like 'name', 'version', and 'author'?\nAnswer:\nLet's think step by step.\n",...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8660, "level": 1, "question": "If I have a document that contains a property list with various properties and a properties.json file, how can I generate a Python code snippet to read this properties.json file and extract specific properties like 'name', 'version', and 'author'?", ...
def count_letters(s): counts = {} for char in s: if char.isalpha(): lower_char = char.lower() counts[lower_char] = counts.get(lower_char, 0) + 1 return counts
simplelr_Filter
[ { "content": "Question:\nPlease create a Python function that takes a string as an input and returns a dictionary where the keys are lowercase letters and the values are the counts of those letters in the string. Non-letter characters should be ignored.\nAnswer:\nLet's think step by step.\n", "role": "user"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8661, "level": 1, "question": "Please create a Python function that takes a string as an input and returns a dictionary where the keys are lowercase letters and the values are the counts of those letters in the string. Non-letter characters should be ignored.", "split": "train" }
def is_sorted(lst): if len(lst) <= 1: return True for i in range(len(lst) - 1): if lst[i] > lst[i+1]: return False return True
simplelr_Filter
[ { "content": "Question:\nThis exercise asks us to build a function that takes a single argument, a list of integers, and returns True if the list is sorted in ascending order, and False otherwise.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8662, "level": 1, "question": "This exercise asks us to build a function that takes a single argument, a list of integers, and returns True if the list is sorted in ascending order, and False otherwise.", "split": "train" }
def rotate(nums, k): n = len(nums) if n == 0 or k == 0: return nums k = k % n if k == 0: return nums nums.reverse() nums[:k] = nums[:k][::-1] nums[k:] = nums[k:][::-1] return nums
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers, rotate the array to the right by `k` steps, where `k` is a non-negative integer.\n\n-----Task-----\nCreate a function that rotates an array of `n` integers to the right by `k` steps. The rotation should be performed in-place, meaning you cannot use extra spac...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8663, "level": 1, "question": "Given an array of integers, rotate the array to the right by `k` steps, where `k` is a non-negative integer.\n\n-----Task-----\nCreate a function that rotates an array of `n` integers to the right by `k` steps. The rotation should be performed in-place...
def reverse_string(s): if len(s) <= 1: return s else: return s[-1] + reverse_string(s[:-1])
simplelr_Filter
[ { "content": "Question:\nCan you explain how to implement a function `reverse_string` in Python using a recursive approach?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8664, "level": 1, "question": "Can you explain how to implement a function `reverse_string` in Python using a recursive approach?", "split": "train" }
import itertools def generate_combinations(input_list: list, k: int) -> list: return list(itertools.combinations(input_list, k))
simplelr_Package
[ { "content": "Question:\nCreate a Python function called `generate_combinations` that returns all possible k-combinations of a given list of unique integers. A k-combination is a subset of k distinct elements from the list.\n\nThe function should:\n1. Take two input parameters, `input_list` (a list of unique in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8665, "level": 1, "question": "Create a Python function called `generate_combinations` that returns all possible k-combinations of a given list of unique integers. A k-combination is a subset of k distinct elements from the list.\n\nThe function should:\n1. Take two input parameters...
def first_non_repeating_character(s): if not s: return None counts = {} for char in s: counts[char] = counts.get(char, 0) + 1 for char in s: if counts[char] == 1: return char return None
simplelr_Filter
[ { "content": "Question:\nCreate a program that takes a string as input and returns the first non-repeating character in the string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8666, "level": 1, "question": "Create a program that takes a string as input and returns the first non-repeating character in the string.", "split": "train" }
def bubble_sort(arr): n = len(arr) for i in range(n): swapped = False for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] swapped = True if not swapped: break return arr
simplelr_Filter
[ { "content": "Question:\nWrite an algorithm to implement bubble sort on an array of integers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8667, "level": 1, "question": "Write an algorithm to implement bubble sort on an array of integers.", "split": "train" }
def length_of_shortest_word(text): words = text.split() if not words: return 0 return min(len(word) for word in words)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that accepts a string of text and returns the length of the shortest word in the text. Assume that the length is measured in terms of characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8668, "level": 1, "question": "Create a function that accepts a string of text and returns the length of the shortest word in the text. Assume that the length is measured in terms of characters.", "split": "train" }
def are_parentheses_balanced(expr: str) -> bool: stack = [] for char in expr: if char == '(': stack.append(char) elif char == ')': if not stack: return False stack.pop() return len(stack) == 0
simplelr_Algorithm
[ { "content": "Question:\n### Question: Balancing Parentheses in Mathematical Expressions\n\n**Context**:\nParentheses are used to indicate the order of operations in mathematical expressions. Given an expression string consisting of numbers, operators (`+`, `-`, `*`, `/`), and parentheses, it may be necessary t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8669, "level": 1, "question": "### Question: Balancing Parentheses in Mathematical Expressions\n\n**Context**:\nParentheses are used to indicate the order of operations in mathematical expressions. Given an expression string consisting of numbers, operators (`+`, `-`, `*`, `/`), and...
def merge_sorted_arrays(arr1, arr2): result = [] i = j = 0 while i < len(arr1) and j < len(arr2): if arr1[i] <= arr2[j]: result.append(arr1[i]) i += 1 else: result.append(arr2[j]) j += 1 while i < len(arr1): result.append(arr1[i]) ...
simplelr_Package
[ { "content": "Question:\nImplement a function called `merge_sorted_arrays` that takes two parameters:\n\n1. `arr1`: A list of integers sorted in non-decreasing order.\n2. `arr2`: A list of integers sorted in non-decreasing order.\n\nThe function should return a single list containing all the elements from both ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8670, "level": 1, "question": "Implement a function called `merge_sorted_arrays` that takes two parameters:\n\n1. `arr1`: A list of integers sorted in non-decreasing order.\n2. `arr2`: A list of integers sorted in non-decreasing order.\n\nThe function should return a single list con...
def min_carries(weights, limit): if not weights: return 0 weights.sort(reverse=True) left = 0 right = len(weights) - 1 count = 0 while left <= right: if left == right: count += 1 break if weights[left] + weights[right] <= limit: count +...
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `weights` where `weights[i]` is the weight of the `i-th` item, and an integer limit. Each time you can carry at most two items as long as their combined weight is not greater than the limit. Return the minimum number of times you need to carry items to move all of...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8671, "level": 1, "question": "Given an integer array `weights` where `weights[i]` is the weight of the `i-th` item, and an integer limit. Each time you can carry at most two items as long as their combined weight is not greater than the limit. Return the minimum number of times you...
def find_max_length(arr): max_length = 0 current_length = 0 for num in arr: if num % 2 == 0: current_length += 1 if current_length > max_length: max_length = current_length else: current_length = 0 return max_length
simplelr_Filter
[ { "content": "Question:\ndef find_max_length(arr):\n max_length = 0\n current_length = 0\n for num in arr:\n if num % 2 == 0:\n current_length += 1\n max_length = max(max_length, current_length)\n else:\n current_length = 0\n return max_length\nAnswer:\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8672, "level": 1, "question": "def find_max_length(arr):\n max_length = 0\n current_length = 0\n for num in arr:\n if num % 2 == 0:\n current_length += 1\n max_length = max(max_length, current_length)\n else:\n current_length =...
from typing import List def remove_duplicates(nums: List[int]) -> List[int]: result = [] seen = set() for num in nums: if num not in seen: result.append(num) seen.add(num) return result
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Context\nAs part of an optimization project, your company needs to simplify data structures by removing duplicate elements. One of the requirements is to address lists of integers and ensure all elements are unique, while also preserving the order ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8673, "level": 1, "question": "### Coding Assessment Question\n\n#### Context\nAs part of an optimization project, your company needs to simplify data structures by removing duplicate elements. One of the requirements is to address lists of integers and ensure all elements are uniqu...
def factorial(n): if n < 0: raise ValueError("Factorial is not defined for negative numbers.") result = 1 for i in range(1, n + 1): result *= i return result
simplelr_Filter
[ { "content": "Question:\nShow me the code for a Python function that calculates the factorial of a given number.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8674, "level": 1, "question": "Show me the code for a Python function that calculates the factorial of a given number.", "split": "train" }
def rotate_2d_matrix(matrix): n = len(matrix) # Transpose the matrix for i in range(n): for j in range(i, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # Reverse each row for row in matrix: row.reverse()
simplelr_Apps
[ { "content": "Question:\nCreate a function `rotate_2d_matrix` that rotates a given nxn 2D matrix 90 degrees clockwise. The function should modify the matrix in-place and not return anything.\n\nFor example:\n```python\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\nrotate_2d_matrix(matrix)\nprint...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8675, "level": 1, "question": "Create a function `rotate_2d_matrix` that rotates a given nxn 2D matrix 90 degrees clockwise. The function should modify the matrix in-place and not return anything.\n\nFor example:\n```python\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\...
def largest_prime(n: int) -> int: if n < 2: return 0 sieve = [True] * (n + 1) sieve[0], sieve[1] = False, False for i in range(2, int(n ** 0.5) + 1): if sieve[i]: sieve[i*i : n+1 : i] = [False] * len(sieve[i*i : n+1 : i]) for i in range(n, 1, -1): if sieve[i]: ...
simplelr_Algorithm
[ { "content": "Question:\n## Problem Statement\n\nWrite a function that determines the largest prime number less than or equal to a given positive integer `n`. The function should be implemented efficiently to handle large values.\n\n### Function Signature\n```python\ndef largest_prime(n: int) -> int:\n```\n\n##...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8676, "level": 1, "question": "## Problem Statement\n\nWrite a function that determines the largest prime number less than or equal to a given positive integer `n`. The function should be implemented efficiently to handle large values.\n\n### Function Signature\n```python\ndef large...
def maximal_perimeter_of_triangle(numbers): numbers.sort() n = len(numbers) if n < 3: return 0 for i in range(n-1, 1, -1): a = numbers[i-2] b = numbers[i-1] c = numbers[i] if a + b > c: return a + b + c return 0
simplelr_Apps
[ { "content": "Question:\n# Maximal Perimeter of Triangle\n\nWrite a function that takes an array of positive integers and returns the maximum perimeter of a triangle that can be formed with three of these integers. If it is impossible to form any triangle with the given integers, return 0. \n\n**Note**: A trian...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8677, "level": 1, "question": "# Maximal Perimeter of Triangle\n\nWrite a function that takes an array of positive integers and returns the maximum perimeter of a triangle that can be formed with three of these integers. If it is impossible to form any triangle with the given intege...
def calculate_total_spent(customers): for customer in customers: total_spent = sum(purchase['amount'] for purchase in customer['purchases']) customer['total_spent'] = total_spent return customers
simplelr_Filter
[ { "content": "Question:\nI need help creating a custom function to process a dataset in Python. The dataset is a list of dictionaries, each representing a customer with keys 'id', 'name', 'age', and 'purchases'. 'purchases' is a list of dictionaries where each dictionary represents a purchase with keys 'item', ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8678, "level": 1, "question": "I need help creating a custom function to process a dataset in Python. The dataset is a list of dictionaries, each representing a customer with keys 'id', 'name', 'age', and 'purchases'. 'purchases' is a list of dictionaries where each dictionary repre...
from typing import List def closest_three_sum(nums: List[int], target: int) -> int: nums.sort() closest = None n = len(nums) for i in range(n - 2): j = i + 1 k = n - 1 while j < k: current_sum = nums[i] + nums[j] + nums[k] if closest is None or abs(curren...
simplelr_Apps
[ { "content": "Question:\n## Closest Three-Sum\n\nGiven an array of integers and a target integer, write a function that finds three integers in the array such that the sum is closest to the target integer. Return the sum of the three integers. You may assume that each input would have exactly one solution.\n\nF...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8679, "level": 1, "question": "## Closest Three-Sum\n\nGiven an array of integers and a target integer, write a function that finds three integers in the array such that the sum is closest to the target integer. Return the sum of the three integers. You may assume that each input wo...
def reverse_list(lst): reversed_list = [] for i in range(len(lst)-1, -1, -1): reversed_list.append(lst[i]) return reversed_list
simplelr_Prefill
[ { "content": "Question:\nCreate a function that reverses the order of the elements in a given list. The function should take a list as an input and return a new list with the elements in reverse order. Make sure to do this without using built-in reverse functions.\nAnswer:\nLet's think step by step.\n", "ro...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8680, "level": 1, "question": "Create a function that reverses the order of the elements in a given list. The function should take a list as an input and return a new list with the elements in reverse order. Make sure to do this without using built-in reverse functions.", "split":...
def first_non_repeating_character(s): counts = {} for char in s: counts[char] = counts.get(char, 0) + 1 for char in s: if counts[char] == 1: return char return '_'
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the first non-repeating character in a given string. If all characters are repeating, return an underscore ('_').\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8681, "level": 1, "question": "Write a function to find the first non-repeating character in a given string. If all characters are repeating, return an underscore ('_').", "split": "train" }
import heapq def dijkstra_shortest_path(graph: list[list[int]], start: int) -> list[int]: """ Find the shortest paths from the start node to all other nodes using Dijkstra's algorithm. Args: - graph: A 2D list where graph[i][j] represents the weight of the edge from node i to node j. If t...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Challenge: Implement a Dijkstra's Shortest Path Algorithm\n\n#### Context\nDijkstra's algorithm is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge weights, producing a shortest path tree. This algorithm is often ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8682, "level": 1, "question": "### Coding Challenge: Implement a Dijkstra's Shortest Path Algorithm\n\n#### Context\nDijkstra's algorithm is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge weights, producing a shortest ...
import numpy as np def normalize_data(data, norm_min=0.0, norm_max=1.0): # Check if the input array is empty if data.size == 0: return data # Calculate the minimum and maximum values for each feature data_min = np.min(data, axis=0) data_max = np.max(data, axis=0) # Avoid divis...
simplelr_Algorithm
[ { "content": "Question:\n### Data Normalization Implementation\n\nImplement a function to normalize a numeric dataset to a specified range using Min-Max scaling. The dataset should be normalized for each feature independently.\n\n### Input and Output\n\n#### Input\n* `data`: A 2D numpy array where each row repr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8683, "level": 1, "question": "### Data Normalization Implementation\n\nImplement a function to normalize a numeric dataset to a specified range using Min-Max scaling. The dataset should be normalized for each feature independently.\n\n### Input and Output\n\n#### Input\n* `data`: A...
from collections import Counter def can_form(s1, s2): count1 = Counter(s1) count2 = Counter(s2) for char in count2: if count2[char] > count1.get(char, 0): return "No" return "Yes"
simplelr_Apps
[ { "content": "Question:\nYou are given two strings s1 and s2. Your task is to determine if you can form s2 using some of the characters (including duplicates) from s1. If it's possible, return \"Yes\". Otherwise, return \"No\". \n\nExample 1:\n\nInput: s1 = \"aabbcc\", s2 = \"abc\"\nOutput: \"Yes\"\nExplanation...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8684, "level": 1, "question": "You are given two strings s1 and s2. Your task is to determine if you can form s2 using some of the characters (including duplicates) from s1. If it's possible, return \"Yes\". Otherwise, return \"No\". \n\nExample 1:\n\nInput: s1 = \"aabbcc\", s2 = \"...
def recommend(users, movies): # Initialize movie_averages with sum and count for each movie movie_averages = {movie: {'sum': 0, 'count': 0} for movie in movies} # Calculate sum and count for each movie for user in users: for movie, rating in user['ratings'].items(): if movie in ...
simplelr_Taco
[ { "content": "Question:\nYou are given the task of implementing a movie recommendation system. The system receives a list of users, each with their own list of movie ratings. Each user rates movies they have watched on a scale of 1 to 5. The system needs to recommend a single movie for each user that they have ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8685, "level": 1, "question": "You are given the task of implementing a movie recommendation system. The system receives a list of users, each with their own list of movie ratings. Each user rates movies they have watched on a scale of 1 to 5. The system needs to recommend a single ...
import itertools def generate_subsets(s, subsetSize=None): elements = list(s) if subsetSize is not None: if subsetSize < 0 or subsetSize > len(elements): return [] combs = itertools.combinations(elements, subsetSize) else: combs = itertools.chain.from_iterable(itertools....
simplelr_Prefill
[ { "content": "Question:\nCreate a function that generates all possible subsets of a given set and returns a list of these subsets. This function should include an optional parameter `subsetSize` that allows the user to retrieve subsets of a specific size. If `subsetSize` is not provided, the function should ret...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8686, "level": 1, "question": "Create a function that generates all possible subsets of a given set and returns a list of these subsets. This function should include an optional parameter `subsetSize` that allows the user to retrieve subsets of a specific size. If `subsetSize` is no...
def merge_intervals(intervals): if not intervals: return [] # Sort intervals based on start time sorted_intervals = sorted(intervals, key=lambda x: x[0]) # Initialize the result with the first interval, converted to list for easy modification result = [list(sorted_intervals[0])] ...
simplelr_Leetcode
[ { "content": "Question:\nGiven a list of intervals where each interval is represented as a tuple `(start, end)`, merge all overlapping intervals and return the list of merged intervals. The intervals in the output list should be sorted by their start time. For example, given `[(1, 3), (2, 6), (8, 10), (15, 18)]...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8687, "level": 1, "question": "Given a list of intervals where each interval is represented as a tuple `(start, end)`, merge all overlapping intervals and return the list of merged intervals. The intervals in the output list should be sorted by their start time. For example, given `...
import re from collections import Counter from typing import List def top_three_words(text: str) -> List[str]: text_lower = text.lower() words = re.findall(r'[a-z]+', text_lower) word_counts = Counter(words) top_words = [word for word, count in word_counts.most_common(3)] return top_words
simplelr_Package
[ { "content": "Question:\nYou are tasked with writing a function that calculates the top-three most common words in a given text. Your function should be efficient and capable of handling relatively large input strings.\n\n### Function Signature\n```python\ndef top_three_words(text: str) -> List[str]:\n pass\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8688, "level": 1, "question": "You are tasked with writing a function that calculates the top-three most common words in a given text. Your function should be efficient and capable of handling relatively large input strings.\n\n### Function Signature\n```python\ndef top_three_words(...
from typing import List def sort_special_array(arr: List[int]) -> List[int]: return sorted(arr)
simplelr_Algorithm
[ { "content": "Question:\n### Question:\n\nYou are tasked with improving a sorting algorithm for a special case of integer sequences. Your goal is to implement a function that sorts an array of integers where each integer appears at most twice. The function must run in O(n log n) time complexity and be able to h...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8689, "level": 1, "question": "### Question:\n\nYou are tasked with improving a sorting algorithm for a special case of integer sequences. Your goal is to implement a function that sorts an array of integers where each integer appears at most twice. The function must run in O(n log ...
def most_common_char(s): counts = {} max_count = 0 result = None for char in s: counts[char] = counts.get(char, 0) + 1 if counts[char] > max_count: max_count = counts[char] result = char return result
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as input and returns the most common character in the string. If there are multiple characters with the same maximum frequency, return the character that appears first in the string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8690, "level": 1, "question": "Create a function that takes a string as input and returns the most common character in the string. If there are multiple characters with the same maximum frequency, return the character that appears first in the string.", "split": "train" }
def has_pair_with_sum(arr, target): seen = set() for num in arr: complement = target - num if complement in seen: return True seen.add(num) return False
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `arr` and an integer `target`, you need to find out if there are two distinct indices `i` and `j` in the array such that `arr[i]` and `arr[j]` sum up to the `target`. If such indices exist, return `true`, otherwise return `false`. \n\nFor example, given `arr =...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8691, "level": 1, "question": "Given an array of integers `arr` and an integer `target`, you need to find out if there are two distinct indices `i` and `j` in the array such that `arr[i]` and `arr[j]` sum up to the `target`. If such indices exist, return `true`, otherwise return `fa...
def maximumProduct(numbers): numbers.sort() product1 = numbers[-1] * numbers[-2] * numbers[-3] product2 = numbers[0] * numbers[1] * numbers[-1] return max(product1, product2)
simplelr_Taco
[ { "content": "Question:\nYou are given a list of integers, and your task is to determine the largest possible product of any three distinct numbers from the list. Each number in the list is unique and the list contains at least three integers.\n\n**Example:**\n\nFor the input list $numbers = [1, 10, 2, 6, 5, 3]...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8692, "level": 1, "question": "You are given a list of integers, and your task is to determine the largest possible product of any three distinct numbers from the list. Each number in the list is unique and the list contains at least three integers.\n\n**Example:**\n\nFor the input ...
import re def find_consecutive_digits(text, n): if n < 1: return [] pattern = rf'\d{{{n},}}' return re.findall(pattern, text)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a string `text` and a number `n`. The function should use the `re` module to find all occurrences of `n` or more consecutive digits in the `text` and return a list of these occurrences.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8693, "level": 1, "question": "Write a Python function that takes a string `text` and a number `n`. The function should use the `re` module to find all occurrences of `n` or more consecutive digits in the `text` and return a list of these occurrences.", "split": "train" }
def merge_and_sort(list1: list, list2: list) -> list: i = 0 j = 0 result = [] while i < len(list1) and j < len(list2): if list1[i] <= list2[j]: result.append(list1[i]) i += 1 else: result.append(list2[j]) j += 1 if i < len(list1): ...
simplelr_Package
[ { "content": "Question:\nYou are required to write a function named `merge_and_sort` that merges two sorted lists into a single sorted list. This problem will help you understand and effectively use list operations and merging algorithms.\n\n#### Function Signature\n```python\ndef merge_and_sort(list1: list, li...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8694, "level": 1, "question": "You are required to write a function named `merge_and_sort` that merges two sorted lists into a single sorted list. This problem will help you understand and effectively use list operations and merging algorithms.\n\n#### Function Signature\n```python\...
import bisect def count_best_friends(nums, k): # Create a sorted list of unique elements unique_sorted = sorted(set(nums)) result = [] for x in nums: low = x - k high = x + k # Find the left and right positions in the sorted unique list left = bisect.bisect_left(unique_s...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of integers `nums` and an integer `k`. A best friend is defined as a distinct number within `nums` that differs from a given number by at most `k`. Return the total number of best friends for each number in `nums`. Two different numbers are considered best friends i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8695, "level": 1, "question": "You are given a list of integers `nums` and an integer `k`. A best friend is defined as a distinct number within `nums` that differs from a given number by at most `k`. Return the total number of best friends for each number in `nums`. Two different nu...
def max_area(height): if len(height) < 2: return 0 left = 0 right = len(height) - 1 max_area = 0 while left < right: current_area = min(height[left], height[right]) * (right - left) if current_area > max_area: max_area = current_area if height[left] < heig...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of non-negative integers representing the heights of a series of vertical lines drawn on an x-axis, where the distance between each consecutive pair of lines is exactly 1. Each line represents a point `(i, height[i])` on the coordinate plane. Two lines form a contai...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8696, "level": 1, "question": "You are given a list of non-negative integers representing the heights of a series of vertical lines drawn on an x-axis, where the distance between each consecutive pair of lines is exactly 1. Each line represents a point `(i, height[i])` on the coordi...
def minDifference(N, arr): total_sum = sum(arr) if total_sum == 0: return 0 dp = [False] * (total_sum + 1) dp[0] = True # Base case: sum 0 is always possible for num in arr: for s in range(total_sum, num - 1, -1): if dp[s - num]: dp[s] = True min_di...
simplelr_Taco
[ { "content": "Question:\nYou are given an integer array `arr` of size `N`. Your task is to split the array into two subarrays such that the difference between the sums of the two subarrays is minimized. Return the minimal difference.\n\nExample 1:\n Input:\n N = 4\n arr = [1, 6, 11, 5]\n \n Output:\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8697, "level": 1, "question": "You are given an integer array `arr` of size `N`. Your task is to split the array into two subarrays such that the difference between the sums of the two subarrays is minimized. Return the minimal difference.\n\nExample 1:\n Input:\n N = 4\n arr ...
def csv_to_dict(s): d = {} if not s: return d pairs = s.split(',') for pair in pairs: if ':' in pair: key, value = pair.split(':', 1) d[key] = value return d
simplelr_Filter
[ { "content": "Question:\nI need to write a function that converts a string of comma-separated values into a dictionary in Python. The string will have key-value pairs, where each pair is separated by a comma, and the key and value within the pair are separated by a colon. For example, the input string \"name:Jo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8698, "level": 1, "question": "I need to write a function that converts a string of comma-separated values into a dictionary in Python. The string will have key-value pairs, where each pair is separated by a comma, and the key and value within the pair are separated by a colon. For ...
from sklearn.metrics import confusion_matrix, classification_report def evaluate_classifier(predicted_labels, true_labels): # Calculate the confusion matrix cm = confusion_matrix(true_labels, predicted_labels) print("Confusion Matrix:") print(cm) # Print a newline before the classification rep...
simplelr_Package
[ { "content": "Question:\nYou are required to create a function that evaluates the performance of a logistic regression classifier by calculating the confusion matrix and the classification report, which includes measures like precision, recall, F1-score, and accuracy. The function should take as input the predi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8699, "level": 1, "question": "You are required to create a function that evaluates the performance of a logistic regression classifier by calculating the confusion matrix and the classification report, which includes measures like precision, recall, F1-score, and accuracy. The func...