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 intersection(l1, l2): """This function returns a list of elements that are common to the input lists l1 and l2.""" set_l2 = set(l2) return [element for element in l1 if element in set_l2]
simplelr_Filter
[ { "content": "Question:\ndef intersection(l1, l2):\n \"\"\"This function returns a list of elements that are common to the input lists l1 and l2.\"\"\"\n return [element for element in l1 if element in l2]\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1400, "level": 1, "question": "def intersection(l1, l2):\n \"\"\"This function returns a list of elements that are common to the input lists l1 and l2.\"\"\"\n return [element for element in l1 if element in l2]", "split": "train" }
def words_from_string(s): return s.split()
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as input and returns a list of words. If the string contains no words, the function should return an empty list. The input string may contain multiple words separated by spaces, including multiple spaces between words. The function should ignore lea...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1401, "level": 1, "question": "Create a function that takes a string as input and returns a list of words. If the string contains no words, the function should return an empty list. The input string may contain multiple words separated by spaces, including multiple spaces between wo...
import math def digit_count(n): if n == 0: return 1 n = abs(n) return math.floor(math.log10(n)) + 1
simplelr_Data_Structure
[ { "content": "Question:\nYou are required to write a function `digit_count` that takes an integer and returns the number of its digits. Your solution should consider the edge cases effectively, ensuring the function is efficient and accurate. Your task is to write this function in Python.\n\n### Input\n* An int...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1402, "level": 1, "question": "You are required to write a function `digit_count` that takes an integer and returns the number of its digits. Your solution should consider the edge cases effectively, ensuring the function is efficient and accurate. Your task is to write this functio...
import math def is_prime(n): if not isinstance(n, int): raise ValueError("Input must be an integer.") if n <= 1: raise ValueError("Input must be greater than 1.") if n == 2: return True if n % 2 == 0: return False max_divisor = math.isqrt(n) for i in range(3, max...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to determine if an input number is prime. The function should also check if the input is an integer and greater than 1. If the input does not meet these conditions, the function should raise a ValueError.\nAnswer:\nLet's think step by step.\n", "role": "user"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1403, "level": 1, "question": "Write a Python function to determine if an input number is prime. The function should also check if the input is an integer and greater than 1. If the input does not meet these conditions, the function should raise a ValueError.", "split": "train" }
def are_rotations(s1, s2): if len(s1) != len(s2): return False return s2 in s1 + s1
simplelr_Prefill
[ { "content": "Question:\nWrite a function to check if two strings are rotations of each other. For example, if the strings are \"abcd\" and \"dabc\", it returns True because \"dabc\" is a rotation of \"abcd\". However, if the strings are \"abcd\" and \"dcba\", it should return False.\nAnswer:\nLet's think step ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1404, "level": 1, "question": "Write a function to check if two strings are rotations of each other. For example, if the strings are \"abcd\" and \"dabc\", it returns True because \"dabc\" is a rotation of \"abcd\". However, if the strings are \"abcd\" and \"dcba\", it should return...
import matplotlib.pyplot as plt from collections import Counter def plot_crime_type_frequency(file_path: str): with open(file_path, 'r') as f: lines = [line.strip() for line in f if line.strip()] crime_types = [line.split(',')[0] for line in lines] frequency = Counter(crime_types) sor...
simplelr_Package
[ { "content": "Question:\nYou are given a text file named `crime_data.txt` containing information about reported crimes in a city. Each line in the file provides details of a single crime incident formatted as \"CrimeType,Location,Date\". The objective is to analyze the frequency of each type of crime and determ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1405, "level": 1, "question": "You are given a text file named `crime_data.txt` containing information about reported crimes in a city. Each line in the file provides details of a single crime incident formatted as \"CrimeType,Location,Date\". The objective is to analyze the frequen...
def daily_temperatures(temperatures): stack = [] result = [0] * len(temperatures) for i in range(len(temperatures)): current_temp = temperatures[i] while stack and current_temp > stack[-1][0]: prev_temp, prev_i = stack.pop() result[prev_i] = i - prev_i stack.a...
simplelr_Apps
[ { "content": "Question:\n### Problem Description\n\nYou are given an array representing the daily temperature readings over a period of days. Write a function to calculate the number of days you would have to wait until a warmer temperature. If there is no future day with a warmer temperature, the answer for th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1406, "level": 1, "question": "### Problem Description\n\nYou are given an array representing the daily temperature readings over a period of days. Write a function to calculate the number of days you would have to wait until a warmer temperature. If there is no future day with a wa...
def max_non_adjacent_sum(arr): if not arr: return 0 n = len(arr) if n == 1: return arr[0] include = arr[0] exclude = 0 for i in range(1, n): new_include = exclude + arr[i] new_exclude = max(include, exclude) include, exclude = new_include, new_ex...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an array of integers and returns the maximum sum of non-adjacent elements. For example, if the array is `[2, 1, 4, 9]`, the maximum sum of non-adjacent elements is `10` (which are `2` and `9`).\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1407, "level": 1, "question": "Create a function that takes an array of integers and returns the maximum sum of non-adjacent elements. For example, if the array is `[2, 1, 4, 9]`, the maximum sum of non-adjacent elements is `10` (which are `2` and `9`).", "split": "train" }
def countSubstrings(s): if not s: return 0 total = 0 current_char = s[0] current_length = 1 for i in range(1, len(s)): if s[i] == current_char: current_length += 1 else: total += current_length * (current_length + 1) // 2 current_char = s[i...
simplelr_Taco
[ { "content": "Question:\nGiven a string S consisting of lowercase English letters, you need to complete the function countSubstrings() which returns the total number of substrings such that all the characters of the substring are same.\n\nFor example, given the string \"aaa\", the substrings are \"a\", \"a\", \...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1408, "level": 1, "question": "Given a string S consisting of lowercase English letters, you need to complete the function countSubstrings() which returns the total number of substrings such that all the characters of the substring are same.\n\nFor example, given the string \"aaa\",...
import numpy as np def longest_non_zero_block(arr): if not arr.size: return None max_length = 0 max_start = None max_stop = None current_start = None for i in range(len(arr)): if arr[i] != 0: if current_start is None: current_start = i ...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a NumPy array as input and returns the boundaries (start and stop indices) of the longest contiguous block that does not contain the value 0. If there are multiple blocks of the same maximum length, return the boundaries of the first one. If the array ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1409, "level": 1, "question": "Write a Python function that takes a NumPy array as input and returns the boundaries (start and stop indices) of the longest contiguous block that does not contain the value 0. If there are multiple blocks of the same maximum length, return the boundar...
from typing import List def all_pairs_shortest_path(adjacency_matrix: List[List[float]]) -> List[List[float]]: n = len(adjacency_matrix) dist = [row.copy() for row in adjacency_matrix] for k in range(n): for i in range(n): for j in range(n): if dist[i][k] + dist[k][...
simplelr_Data_Structure
[ { "content": "Question:\nYou are given an \\(n \\times n\\) grid representing the edge weights of a graph. Each cell \\((i, j)\\) in the grid represents the weight of the edge from node \\(i\\) to node \\(j\\). If there is no direct edge between node \\(i\\) and node \\(j\\), the weight will be a large value (y...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1410, "level": 1, "question": "You are given an \\(n \\times n\\) grid representing the edge weights of a graph. Each cell \\((i, j)\\) in the grid represents the weight of the edge from node \\(i\\) to node \\(j\\). If there is no direct edge between node \\(i\\) and node \\(j\\), ...
import torch def process_dlpack_tensor(dlpack_tensor) -> 'dlpack_tensor': # Convert the DLPack tensor to a PyTorch tensor pt_tensor = torch.utils.dlpack.from_dlpack(dlpack_tensor) # Normalize the tensor to [0, 1] range min_val = pt_tensor.min() max_val = pt_tensor.max() if max_val == min_v...
simplelr_Docs
[ { "content": "Question:\n**Question: Converting and Processing Tensors using DLPack and PyTorch**\n\nGiven a tensor in DLPack format, you are required to perform the following steps:\n\n1. Convert the DLPack tensor to a PyTorch tensor using `torch.utils.dlpack.from_dlpack`.\n2. Perform a series of operations on...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1411, "level": 1, "question": "**Question: Converting and Processing Tensors using DLPack and PyTorch**\n\nGiven a tensor in DLPack format, you are required to perform the following steps:\n\n1. Convert the DLPack tensor to a PyTorch tensor using `torch.utils.dlpack.from_dlpack`.\n2...
def two_sum(nums, target): seen = set() for num in nums: complement = target - num if complement in seen: return True seen.add(num) return False
simplelr_Filter
[ { "content": "Question:\nGiven an array of distinct integers, determine if any two numbers in the array sum to a given target value. Returns a boolean true if a pair is found, false otherwise.\n\nExample:\nInput: [2,7,11,15]\nTarget: 9\nOutput: true\nExplanation: 2 + 7 = 9\n\nHere is a sample implementation in ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1412, "level": 1, "question": "Given an array of distinct integers, determine if any two numbers in the array sum to a given target value. Returns a boolean true if a pair is found, false otherwise.\n\nExample:\nInput: [2,7,11,15]\nTarget: 9\nOutput: true\nExplanation: 2 + 7 = 9\n\n...
def second_highest(arr): if len(arr) < 2: return None maximum = max(arr) new_arr = [x for x in arr if x != maximum] if not new_arr: return maximum else: return max(new_arr)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that returns the second highest number in an array. If there is no such number, return the highest number. If the array has less than two elements, return None.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1413, "level": 1, "question": "Create a function that returns the second highest number in an array. If there is no such number, return the highest number. If the array has less than two elements, return None.", "split": "train" }
from typing import List def max_non_adjacent_sum(nums: List[int]) -> int: if not nums: return 0 include = nums[0] exclude = 0 for num in nums[1:]: new_include = exclude + num new_exclude = max(include, exclude) include, exclude = new_include, new_exclude return max(i...
simplelr_Code_Contests
[ { "content": "Question:\nGiven an integer array, you will need to find the maximum possible sum of its non-adjacent elements. You are not allowed to pick two adjacent elements from the array, and you must maximize the sum of the picked elements.\n\nThe function should be called `max_non_adjacent_sum` and it sho...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1414, "level": 1, "question": "Given an integer array, you will need to find the maximum possible sum of its non-adjacent elements. You are not allowed to pick two adjacent elements from the array, and you must maximize the sum of the picked elements.\n\nThe function should be calle...
from collections import defaultdict def longestSubstringWithTwoDistinct(s): char_counts = defaultdict(int) max_len = 0 left = 0 for right in range(len(s)): char = s[right] char_counts[char] += 1 while len(char_counts) > 2: left_char = s[left] char_counts[...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` containing only lowercase alphabetical characters. Your task is to determine the **length** of the longest substring that contains **no more than two distinct characters**. Write a function `longestSubstringWithTwoDistinct(s)` that takes the string `s` as inpu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1415, "level": 1, "question": "You are given a string `s` containing only lowercase alphabetical characters. Your task is to determine the **length** of the longest substring that contains **no more than two distinct characters**. Write a function `longestSubstringWithTwoDistinct(s)...
def min_operations_to_equalize_height(heights, m): if not heights: return 0 # Assuming 0 stones can be considered as same height with 0 operations. n = len(heights) sorted_h = sorted(heights) if n % 2 == 1: median = sorted_h[n // 2] else: # For even length, choose the lower ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of integers `height` representing the heights of stones in a row. In one operation, you can pick any stone and increase or decrease its height by 1. However, you can only perform this operation a maximum of `m` times across the entire list. The goal is to make all t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1416, "level": 1, "question": "You are given a list of integers `height` representing the heights of stones in a row. In one operation, you can pick any stone and increase or decrease its height by 1. However, you can only perform this operation a maximum of `m` times across the ent...
def string_to_int(s: str) -> int: stripped_s = s.strip() if not stripped_s: raise ValueError("No value passed to the function") sign = 1 if stripped_s[0] in '+-': sign = -1 if stripped_s[0] == '-' else 1 number_str = stripped_s[1:] else: number_str = stripped_s ...
simplelr_Algorithm
[ { "content": "Question:\n### Convert String to Integer (atoi) Function\n\n#### Background\nThe `atoi` (ASCII to integer) function is a common utility in various programming languages that converts a string representation of a number into its integer form. This function needs to handle optional leading/trailing ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1417, "level": 1, "question": "### Convert String to Integer (atoi) Function\n\n#### Background\nThe `atoi` (ASCII to integer) function is a common utility in various programming languages that converts a string representation of a number into its integer form. This function needs t...
from typing import List def can_return_books(borrowed: List[int], returned: List[int]) -> bool: return borrowed == returned
simplelr_Algorithm
[ { "content": "Question:\n### Scenario:\nYou are developing a software system for a library that helps in managing book loans and returns. One of the functionalities required is to track whether a series of books can be returned in the same order as they were borrowed. This helps the library staff ensure that bo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1418, "level": 1, "question": "### Scenario:\nYou are developing a software system for a library that helps in managing book loans and returns. One of the functionalities required is to track whether a series of books can be returned in the same order as they were borrowed. This hel...
def majority_element(arr): candidate = arr[0] count = 1 for i in range(1, len(arr)): if arr[i] == candidate: count += 1 else: count -= 1 if count == 0: candidate = arr[i] count = 1 return candidate
simplelr_Filter
[ { "content": "Question:\nDesign an algorithm to find the majority element in an array. The majority element is the element that appears more than ⌊n/2⌋ times, where n is the size of the array. You can assume that the array is non-empty and the majority element always exists in the array. Explain the algorithm a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1419, "level": 1, "question": "Design an algorithm to find the majority element in an array. The majority element is the element that appears more than ⌊n/2⌋ times, where n is the size of the array. You can assume that the array is non-empty and the majority element always exists in...
def longest_substring_same_char(s): if not s: return 0 max_len = 1 current = 1 for i in range(1, len(s)): if s[i] == s[i-1]: current += 1 else: current = 1 if current > max_len: max_len = current return max_len
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` consisting of lowercase English letters. Return the length of the longest substring with all characters the same. A substring is a contiguous sequence of characters within a string. \n\nFor example, given `s = \"aaabbccaa\"`, return `3` since the longest subst...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1420, "level": 1, "question": "You are given a string `s` consisting of lowercase English letters. Return the length of the longest substring with all characters the same. A substring is a contiguous sequence of characters within a string. \n\nFor example, given `s = \"aaabbccaa\"`,...
from typing import List, Tuple def compress_image(image: List[List[int]]) -> List[Tuple[int, int]]: compressed = [] for row in image: if not row: continue current = row[0] count = 1 for pixel in row[1:]: if pixel == current: count += 1 ...
simplelr_Algorithm
[ { "content": "Question:\n### Image Compression Algorithm\n\n#### Context\nImage compression is crucial for reducing the size of image data without significantly compromising quality. One basic method of image compression is Run-Length Encoding (RLE), which is particularly effective for images with large areas o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1421, "level": 1, "question": "### Image Compression Algorithm\n\n#### Context\nImage compression is crucial for reducing the size of image data without significantly compromising quality. One basic method of image compression is Run-Length Encoding (RLE), which is particularly effe...
def rabin_karp(text, pattern): base = 256 mod = 101 # You may want to use a larger prime like 1000000007 for better collision resistance pattern_len = len(pattern) text_len = len(text) if pattern_len == 0 or text_len == 0 or pattern_len > text_len: return -1 # Pattern not found ...
simplelr_Filter
[ { "content": "Question:\nI'm learning about the Rabin-Karp algorithm and its implementation. Could you provide a detailed explanation and some code examples to help me understand how it works?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1422, "level": 1, "question": "I'm learning about the Rabin-Karp algorithm and its implementation. Could you provide a detailed explanation and some code examples to help me understand how it works?", "split": "train" }
def merge_sorted_arrays(arr1: list, arr2: list) -> list: """ Merges two sorted lists into a single sorted list. :param arr1: A sorted list of comparable items. :param arr2: Another sorted list of comparable items. :return: A single sorted list containing all elements from arr1 and arr2. """...
simplelr_Algorithm
[ { "content": "Question:\n**Question 2: Merge Two Sorted Arrays**\n\nYou are required to implement a function that merges two sorted arrays into a single sorted array. The function should take advantage of the fact that both input arrays are individually sorted and combine them with optimal performance.\n\n### F...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1423, "level": 1, "question": "**Question 2: Merge Two Sorted Arrays**\n\nYou are required to implement a function that merges two sorted arrays into a single sorted array. The function should take advantage of the fact that both input arrays are individually sorted and combine them...
from typing import List def reformat_string(s: str) -> List[str]: # Step 1: Filter out non-alphanumeric characters and convert to lowercase cleaned = [] for c in s: if c.isalnum(): cleaned.append(c.lower()) cleaned_str = ''.join(cleaned) # Step 2: Split into chunks of 3, pa...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are given a string that may contain various characters, including letters, digits, and special characters. Your task is to implement a function that reformats this string in a specific manner: \n\n1. Remove all special characters (anything that is not a lett...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1424, "level": 1, "question": "### Problem Statement\n\nYou are given a string that may contain various characters, including letters, digits, and special characters. Your task is to implement a function that reformats this string in a specific manner: \n\n1. Remove all special char...
import json def convert_json_to_dict(json_str): """ Converts a JSON string into a Python dictionary. Args: json_str (str): The JSON string to be converted. Returns: dict: The Python dictionary representation of the JSON string. Returns None if an error occurs during conve...
simplelr_Filter
[ { "content": "Question:\nPlease provide a Python function that can convert a given JSON string into its corresponding Python object (dictionary) and handle any potential errors that might occur during the conversion process.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1425, "level": 1, "question": "Please provide a Python function that can convert a given JSON string into its corresponding Python object (dictionary) and handle any potential errors that might occur during the conversion process.", "split": "train" }
def rotate(arr, k): if not arr or k == 0: return arr n = len(arr) effective_k = k % n return arr[-effective_k:] + arr[:-effective_k]
simplelr_Apps
[ { "content": "Question:\nCreate a function that rotates the elements of an array to the right by a given number of steps.\n\nFor example, given array `[1, 2, 3, 4, 5]` and `k = 2`, the array should be rotated to `[4, 5, 1, 2, 3]`.\n\nYour function should handle edge cases where:\n- The array is empty.\n- The nu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1426, "level": 1, "question": "Create a function that rotates the elements of an array to the right by a given number of steps.\n\nFor example, given array `[1, 2, 3, 4, 5]` and `k = 2`, the array should be rotated to `[4, 5, 1, 2, 3]`.\n\nYour function should handle edge cases wher...
def compute_totient(n: int) -> int: if n == 0: return 0 res = n i = 2 while i * i <= n: if n % i == 0: res = res // i * (i - 1) while n % i == 0: n = n // i i += 1 if n > 1: res = res // n * (n - 1) return res
simplelr_Data_Structure
[ { "content": "Question:\n### Euler's Totient Function Challenge\n\n#### Objective:\nWrite a function `compute_totient` that computes Euler's Totient Function, ϕ(n), for a given integer \\( n \\).\n\n#### Function Signature:\n```python\ndef compute_totient(n: int) -> int:\n```\n\n#### Input:\n - `n`: A single i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1427, "level": 1, "question": "### Euler's Totient Function Challenge\n\n#### Objective:\nWrite a function `compute_totient` that computes Euler's Totient Function, ϕ(n), for a given integer \\( n \\).\n\n#### Function Signature:\n```python\ndef compute_totient(n: int) -> int:\n```\...
def sum_of_elements(array): total = 0 for number in array: total += number return total
simplelr_Filter
[ { "content": "Question:\n### Lesson 12: Write a Function to Calculate the Sum of All Elements in an Array\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1428, "level": 1, "question": "### Lesson 12: Write a Function to Calculate the Sum of All Elements in an Array", "split": "train" }
def find_unique_triplets(nums, target): nums.sort() triplets = set() n = len(nums) for i in range(n): for j in range(i + 1, n): for k in range(j + 1, n): if nums[i] + nums[j] + nums[k] == target: triplet = tuple(sorted((nums[i], nums[j], nums[k])))...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to find the number of unique triplets in a list of integers that sum up to a specific target. The function should be named `find_unique_triplets` and take two parameters: a list of integers and a target sum. The function should return the count of unique triplets...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1429, "level": 1, "question": "Write a Python function to find the number of unique triplets in a list of integers that sum up to a specific target. The function should be named `find_unique_triplets` and take two parameters: a list of integers and a target sum. The function should ...
def calculate_total_marks(student_name, marks): return sum(marks)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the total marks of a student in a school. The function should take a student name and the list of marks of all subjects as input and return the total marks.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1430, "level": 1, "question": "Write a function to calculate the total marks of a student in a school. The function should take a student name and the list of marks of all subjects as input and return the total marks.", "split": "train" }
def parse_commands(commands): """ Parse a list of commands for a smart stove. Args: commands (list): A list of strings, where each string is a command. Returns: list: A list of dictionaries, where each dictionary represents a parsed command. """ valid_modes = {"rapid boil", "lo...
simplelr_Filter
[ { "content": "Question:\nI have a voice-controlled smart stove. I can tell it to start cooking with one of several modes (e.g. \"start rapid boil\", \"start low simmer\", etc.) or I can tell it to change the cooking mode of a pot that is already cooking (e.g. \"switch to rapid boil\", \"switch to low simmer\", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1431, "level": 1, "question": "I have a voice-controlled smart stove. I can tell it to start cooking with one of several modes (e.g. \"start rapid boil\", \"start low simmer\", etc.) or I can tell it to change the cooking mode of a pot that is already cooking (e.g. \"switch to rapid...
def remove_duplicates(nums): seen = set() result = [] for num in nums: if num not in seen: seen.add(num) result.append(num) return result
simplelr_Apps
[ { "content": "Question:\nImplement a function that takes a list of integers and returns the list with duplicates removed, while preserving the order of the first occurrence of each element.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1432, "level": 1, "question": "Implement a function that takes a list of integers and returns the list with duplicates removed, while preserving the order of the first occurrence of each element.", "split": "train" }
def count_boats(total_boats, total_oars, total_pedals): pedal_boats = total_pedals // 2 rowing_boats = total_oars // 2 motorboats = total_boats - pedal_boats - rowing_boats return { "pedal_boats": pedal_boats, "rowing_boats": rowing_boats, "motorboats": motorboats }
simplelr_Apps
[ { "content": "Question:\nA park has a boating lake with several types of boats: pedal boats, rowing boats, and motorboats. The park’s manager needs to know how many of each type of boat there are. Unfortunately, the data collected only includes the total number of boats, the total number of oars, and the total ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1433, "level": 1, "question": "A park has a boating lake with several types of boats: pedal boats, rowing boats, and motorboats. The park’s manager needs to know how many of each type of boat there are. Unfortunately, the data collected only includes the total number of boats, the t...
import heapq from collections import deque def rearrange_string(s: str, k: int) -> str: if k == 0: return s # No constraints, just return the string as is # Calculate the frequency of each character freq = {} max_freq = 0 for c in s: freq[c] = freq.get(c, 0) + 1 if fre...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` containing only lowercase alphabetic characters, and an integer `k`. Your task is to rearrange the string such that the same characters are at least `k` indices apart. If it is not possible to rearrange the string to satisfy this condition, return an empty str...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1434, "level": 1, "question": "You are given a string `s` containing only lowercase alphabetic characters, and an integer `k`. Your task is to rearrange the string such that the same characters are at least `k` indices apart. If it is not possible to rearrange the string to satisfy ...
import pandas as pd def analyze_sales_data(file_path: str) -> pd.DataFrame: # Read the CSV file into a DataFrame df = pd.read_csv(file_path) # Add the 'Total Sales' column as Quantity multiplied by Price df['Total Sales'] = df['Quantity'] * df['Price'] # Group by Region and Product, then ...
simplelr_Docs
[ { "content": "Question:\n#### Objective:\nYou are required to implement a function using the pandas library that processes a given dataset and returns a specific output based on various operations including conditional filtering, aggregation, and pivoting.\n\n#### Problem Statement:\nImplement a function `analy...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1435, "level": 1, "question": "#### Objective:\nYou are required to implement a function using the pandas library that processes a given dataset and returns a specific output based on various operations including conditional filtering, aggregation, and pivoting.\n\n#### Problem Stat...
from collections import defaultdict import string def summarize_text(text): # Preprocess the text into words and their cleaned versions words = [] for word in text.split(): cleaned_word = word.strip(string.punctuation).lower() if cleaned_word: words.append((word, cleaned_word)) ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to perform a simple text summarization using a naive implementation of the compression method. This function should take a single string input and return a string that is a summary of the input text. The summary should be created by repeatedly replacing the most ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1436, "level": 1, "question": "Write a python function to perform a simple text summarization using a naive implementation of the compression method. This function should take a single string input and return a string that is a summary of the input text. The summary should be create...
def hailstone_properties(n: int) -> (int, int): current = n max_elem = current length = 1 # Start with the initial element while current != 1: if current % 2 == 0: next_num = current // 2 else: next_num = 3 * current + 1 length += 1 if next_num > ...
simplelr_Data_Structure
[ { "content": "Question:\n### Hailstone Sequence Length and Maximum Element\n\n**Objective**: Write a Python function to compute the length of the hailstone sequence and the maximum element encountered in the sequence for any given positive integer `n`.\n\n**Function Signature**:\n```python\ndef hailstone_proper...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1437, "level": 1, "question": "### Hailstone Sequence Length and Maximum Element\n\n**Objective**: Write a Python function to compute the length of the hailstone sequence and the maximum element encountered in the sequence for any given positive integer `n`.\n\n**Function Signature*...
from collections import deque def shortest_path(graph, start, end): if start not in graph or end not in graph: return [] if start == end: return [start] visited = set() parent = {} queue = deque() queue.append(start) visited.add(start) parent[start] = None # P...
simplelr_Algorithm
[ { "content": "Question:\n### Data Structure & Algorithms: Graph Traversal\n\nYou are developing a navigation system for a city. The city is represented as a graph where intersections are nodes, and roads are edges. You need to find the shortest path from a starting intersection to a destination intersection.\n\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1438, "level": 1, "question": "### Data Structure & Algorithms: Graph Traversal\n\nYou are developing a navigation system for a city. The city is represented as a graph where intersections are nodes, and roads are edges. You need to find the shortest path from a starting intersectio...
from collections import defaultdict def valid_path(edges, source, destination): if source == destination: return True adj = defaultdict(list) for u, v in edges: adj[u].append(v) stack = [(source, {source})] while stack: current, visited = stack.pop() i...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a directed graph represented by a list of edges `edges`, where each element in `edges` is a pair of integers `[u, v]` representing a directed edge from node `u` to node `v`. You are also given two nodes `source` and `destination`. Write a function to determine if there is ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1439, "level": 1, "question": "You are given a directed graph represented by a list of edges `edges`, where each element in `edges` is a pair of integers `[u, v]` representing a directed edge from node `u` to node `v`. You are also given two nodes `source` and `destination`. Write a...
from collections import Counter def sort_array(nums): count = Counter(nums) sorted_nums = sorted(nums, key=lambda x: (count[x], x)) return sorted_nums # Example usage: # nums = [2, 4, 1, 4, 3, 3, 3] # print(sort_array(nums)) # Output: [1, 2, 4, 4, 3, 3, 3]
simplelr_Filter
[ { "content": "Question:\nHere is the text of the input:\n7\n2 4 1 4 3 3 3\n\nGiven the array of integers, write a code that sorts the array by the number of occurrences of each integer in ascending order. If two or more integers have the same number of occurrences, sort them in ascending order.\n\nThis code sho...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1440, "level": 1, "question": "Here is the text of the input:\n7\n2 4 1 4 3 3 3\n\nGiven the array of integers, write a code that sorts the array by the number of occurrences of each integer in ascending order. If two or more integers have the same number of occurrences, sort them i...
def remove_duplicate_characters(s): seen = set() result = [] for char in s: if char not in seen: result.append(char) seen.add(char) return ''.join(result)
simplelr_Filter
[ { "content": "Question:\nWe need to implement a function called `remove_duplicate_characters` that takes a string as input and returns a new string with all duplicate characters removed while preserving the order of the first occurrence of each unique character.\nAnswer:\nLet's think step by step.\n", "role...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1441, "level": 1, "question": "We need to implement a function called `remove_duplicate_characters` that takes a string as input and returns a new string with all duplicate characters removed while preserving the order of the first occurrence of each unique character.", "split": "...
def reverse_list(lst): return lst[::-1]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that reverses the order of a list of integers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1442, "level": 1, "question": "Create a function that reverses the order of a list of integers.", "split": "train" }
from typing import List def sum_nested_list(nested_list: List) -> int: total = 0 for element in nested_list: if isinstance(element, list): total += sum_nested_list(element) else: total += element return total
simplelr_Algorithm
[ { "content": "Question:\n### Sum of Nested List Node Values\n\n**Context:**\nYou're working with a nested list data structure that is used to store hierarchical information. Each element in the list can either be a single integer or another nested list. Your task is to implement a function that computes the sum...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1443, "level": 1, "question": "### Sum of Nested List Node Values\n\n**Context:**\nYou're working with a nested list data structure that is used to store hierarchical information. Each element in the list can either be a single integer or another nested list. Your task is to impleme...
def group_words_by_length(words): if not words: return {} temp_dict = {} for word in words: length = len(word) if length in temp_dict: temp_dict[length].append(word) else: temp_dict[length] = [word] sorted_lengths = sorted(temp_dict.keys(...
simplelr_Evol
[ { "content": "Question:\nImplement a function that takes a list of words and returns a dictionary where the keys are the lengths of the words and the values are lists containing words of that length. The words should be grouped in the list according to their lengths in ascending order. If the word list is empty...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1444, "level": 1, "question": "Implement a function that takes a list of words and returns a dictionary where the keys are the lengths of the words and the values are lists containing words of that length. The words should be grouped in the list according to their lengths in ascendi...
def maximize_tickets(tickets, budget): dp = [0] * (budget + 1) for ticket in tickets: for j in range(budget, ticket - 1, -1): dp[j] = max(dp[j], dp[j - ticket] + ticket) return dp[budget]
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nIn an amusement park, there is a popular tickets booth that offers a collection of tickets with different values. A customer wants to buy a combination of tickets that maximize the total value, but they are constrained by a budget limit. Write a function that de...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1445, "level": 1, "question": "### Problem Statement\n\nIn an amusement park, there is a popular tickets booth that offers a collection of tickets with different values. A customer wants to buy a combination of tickets that maximize the total value, but they are constrained by a bud...
import unicodedata def process_unicode_string(s: str) -> dict: normalized = unicodedata.normalize('NFD', s) casefolded = normalized.casefold() encoded = casefolded.encode('utf-8', errors='replace') decoded = encoded.decode('utf-8', errors='replace') char_properties = [] for char in decoded...
simplelr_Docs
[ { "content": "Question:\n#### Title: Unicode String Manipulation and Encoding\n\n#### Objective:\nTo assess the student's understanding of handling Unicode strings, encoding and decoding, and employing Unicode properties in Python.\n\n#### Description:\nYou are required to implement a function `process_unicode_...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1446, "level": 1, "question": "#### Title: Unicode String Manipulation and Encoding\n\n#### Objective:\nTo assess the student's understanding of handling Unicode strings, encoding and decoding, and employing Unicode properties in Python.\n\n#### Description:\nYou are required to imp...
def num_decodings(s): n = len(s) if n == 0: return 0 dp = [0] * (n + 1) dp[0] = 1 # Base case: empty string has one way to decode for i in range(1, n + 1): # Check single digit if s[i-1] != '0': dp[i] += dp[i-1] # Check two digits if i >= 2: ...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` representing an encoded message where each letter is represented by a number corresponding to its position in the alphabet (`'A' = 1, 'B' = 2, ..., 'Z' = 26`), return the total number of ways to decode it. A single digit can be decoded if it is between 1 and 9, and a ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1447, "level": 1, "question": "Given a string `s` representing an encoded message where each letter is represented by a number corresponding to its position in the alphabet (`'A' = 1, 'B' = 2, ..., 'Z' = 26`), return the total number of ways to decode it. A single digit can be decod...
def optimized_combination(n: int, r: int) -> int: if n < 0 or r < 0: return 0 if r > n: return 0 if r == 0 or r == n: return 1 r = min(r, n - r) result = 1 for i in range(1, r + 1): result = result * (n - r + i) // i return result
simplelr_Data_Structure
[ { "content": "Question:\n### Combination Calculation with Edge-Case Handling and Optimization\n\n#### Context\n\nYou're developing a program for a lottery system where users select different combinations of numbers. You need to calculate the number of possible combinations efficiently. Your task is to implement...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1448, "level": 1, "question": "### Combination Calculation with Edge-Case Handling and Optimization\n\n#### Context\n\nYou're developing a program for a lottery system where users select different combinations of numbers. You need to calculate the number of possible combinations eff...
def hamming_weight(n: int) -> int: count = 0 while n: count += 1 n &= n - 1 return count
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario:\nYou are working on optimizing a system that requires frequent evaluation of the number of '1' bits in binary representations of numbers. This is crucial for tasks such as cryptographic compute units and error-checking routines. To test your understanding of Brian Kernigha...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1449, "level": 1, "question": "### Scenario:\nYou are working on optimizing a system that requires frequent evaluation of the number of '1' bits in binary representations of numbers. This is crucial for tasks such as cryptographic compute units and error-checking routines. To test y...
def max_sum(grid): if not grid: return 0 max_sum = 0 rows = len(grid) cols = len(grid[0]) if rows else 0 # Calculate maximum row sum for row in grid: row_sum = sum(row) if row_sum > max_sum: max_sum = row_sum # Calculate maximum column sum for col in...
simplelr_Leetcode
[ { "content": "Question:\nWrite a function that takes a 2D list `grid` representing a grid of integers and returns the maximum sum of elements in any single row or column. The function should make use of efficient traversals to ensure a minimal runtime. The grid can have different numbers of rows and columns, bu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1450, "level": 1, "question": "Write a function that takes a 2D list `grid` representing a grid of integers and returns the maximum sum of elements in any single row or column. The function should make use of efficient traversals to ensure a minimal runtime. The grid can have differ...
def find_peak_elements(arr): if not arr: return [] peaks = [] n = len(arr) if n == 1: return arr.copy() for i in range(1, n): current = arr[i] previous = arr[i-1] if i == 1: if previous >= current: peaks.append(previous) els...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to retrieve peak elements in an array. A peak element is defined as an element that is not smaller than its neighbors. For array elements at the ends, we need to consider only one neighbor. You can traverse the array only once and return all peak elements.\nAnswer:\nLet...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1451, "level": 1, "question": "Write a function to retrieve peak elements in an array. A peak element is defined as an element that is not smaller than its neighbors. For array elements at the ends, we need to consider only one neighbor. You can traverse the array only once and retu...
def modify_string(s): if not s: return s result = [s[0]] for i in range(1, len(s)): current = s[i] prev = result[-1] if current == prev: if prev == 'a': new_char = 'b' else: new_char = 'a' result.append(new_c...
simplelr_Code_Contests
[ { "content": "Question:\nYou are given a string s of length n (1 ≤ n ≤ 100) consisting of lowercase English letters only. Your task is to modify the string so that no two adjacent characters are the same by replacing some (possibly none) characters with any lowercase English letter.\n\nWrite a function called `...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1452, "level": 1, "question": "You are given a string s of length n (1 ≤ n ≤ 100) consisting of lowercase English letters only. Your task is to modify the string so that no two adjacent characters are the same by replacing some (possibly none) characters with any lowercase English l...
from datetime import datetime, timedelta def expected_delivery_dates(orders): result = [] for order in orders: order_date_str, days = order order_date = datetime.strptime(order_date_str, "%Y-%m-%d").date() delivery_date = order_date + timedelta(days=days) result.append(delivery_...
simplelr_Codeforces
[ { "content": "Question:\nYou are a software engineer at an e-commerce company. Your team is working on improving the delivery estimates for orders. Each order has a shipping duration which varies based on the location of the recipient. To provide more accurate delivery dates, your task is to implement a functio...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1453, "level": 1, "question": "You are a software engineer at an e-commerce company. Your team is working on improving the delivery estimates for orders. Each order has a shipping duration which varies based on the location of the recipient. To provide more accurate delivery dates, ...
def second_smallest(nums): if len(nums) < 2: return -1 min_val = min(nums) new_list = [x for x in nums if x != min_val] if not new_list: return -1 return min(new_list)
simplelr_Filter
[ { "content": "Question:\nWrite a Python code snippet to find the second smallest number in a given list of integers. If the list does not have distinct second smallest, return -1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1454, "level": 1, "question": "Write a Python code snippet to find the second smallest number in a given list of integers. If the list does not have distinct second smallest, return -1.", "split": "train" }
def canRepairBridge(planks, K): current_consecutive = 0 for plank in planks: if plank == 1: current_consecutive += 1 if current_consecutive > K: return False else: current_consecutive = 0 return True
simplelr_Taco
[ { "content": "Question:\nGeek wants to repair a broken bridge in his village. The bridge can be described as a series of planks where each plank either needs to be repaired or replaced. The planks are represented in an array where a `1` indicates a plank that needs to be replaced, and a `0` indicates a plank th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1455, "level": 1, "question": "Geek wants to repair a broken bridge in his village. The bridge can be described as a series of planks where each plank either needs to be repaired or replaced. The planks are represented in an array where a `1` indicates a plank that needs to be repla...
def string_length(s): count = 0 for char in s: count += 1 return count
simplelr_Filter
[ { "content": "Question:\nCreate a program in Python to find the length of a string without using the built-in `len()` function.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1456, "level": 1, "question": "Create a program in Python to find the length of a string without using the built-in `len()` function.", "split": "train" }
import ipaddress def is_valid_ip(ip): try: ipaddress.IPv4Address(ip) return True except ValueError: pass try: ipaddress.IPv6Address(ip) return True except ValueError: return False
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to check if a given IP address is valid IPv4 or IPv6. The function should return a boolean value where `True` indicates a valid IP address and `False` indicates an invalid IP address. The function should handle both IPv4 and IPv6 addresses.\nAnswer:\nLet's think ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1457, "level": 1, "question": "Write a Python function to check if a given IP address is valid IPv4 or IPv6. The function should return a boolean value where `True` indicates a valid IP address and `False` indicates an invalid IP address. The function should handle both IPv4 and IPv...
import sunau def modify_sunau_file(input_file: str, output_file: str, new_sample_rate: int) -> None: with sunau.open(input_file, 'r') as au_read: channels = au_read.getnchannels() samp_width = au_read.getsampwidth() n_frames = au_read.getnframes() audio_data = au_read.readframes(n_f...
simplelr_Docs
[ { "content": "Question:\n#### Objective\nYou will implement a function that reads a Sun AU audio file, extracts its metadata, and then writes a new AU file with modified metadata and the same audio content.\n\n#### Task Description\n1. Implement a function `modify_sunau_file(input_file: str, output_file: str, n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1458, "level": 1, "question": "#### Objective\nYou will implement a function that reads a Sun AU audio file, extracts its metadata, and then writes a new AU file with modified metadata and the same audio content.\n\n#### Task Description\n1. Implement a function `modify_sunau_file(i...
def square_and_filter(numbers): return [x**2 for x in numbers if x**2 <= 100]
simplelr_Filter
[ { "content": "Question:\nGiven a list of numbers, write a Python function to return a new list where each element is the square of the corresponding element in the input list. Use list comprehension for this task. Additionally, modify the function to filter out any squared numbers that are greater than 100. For...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1459, "level": 1, "question": "Given a list of numbers, write a Python function to return a new list where each element is the square of the corresponding element in the input list. Use list comprehension for this task. Additionally, modify the function to filter out any squared num...
def most_copies(inventory): max_copies = inventory[0]['copies'] best_title = inventory[0]['title'] for book in inventory[1:]: copies = book['copies'] title = book['title'] if copies > max_copies: max_copies = copies best_title = title eli...
simplelr_Apps
[ { "content": "Question:\nYou are managing a bookstore, and you track the inventory of your books using a simple list of dictionaries. Each dictionary contains the `title` of the book, the `author`, and the number of `copies` in stock. Here's an example list:\n\n```python\ninventory = [\n {'title': 'Book A', ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1460, "level": 1, "question": "You are managing a bookstore, and you track the inventory of your books using a simple list of dictionaries. Each dictionary contains the `title` of the book, the `author`, and the number of `copies` in stock. Here's an example list:\n\n```python\ninve...
def count_pairs(N: int) -> int: MOD = 10**9 + 7 return ((N - 1) // 2) % MOD
simplelr_Taco
[ { "content": "Question:\nYou are given an integer N. Your task is to count the number of distinct pairs of positive integers (a, b) such that their sum equals N. Return the count of such pairs. Since the output can be huge, return it modulo 10^9 + 7.\n\nExample 1:\nInput:\nN = 5\nOutput:\n2\nExplanation:\nThe p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1461, "level": 1, "question": "You are given an integer N. Your task is to count the number of distinct pairs of positive integers (a, b) such that their sum equals N. Return the count of such pairs. Since the output can be huge, return it modulo 10^9 + 7.\n\nExample 1:\nInput:\nN =...
def count_flips_to_convert(a: int, b: int) -> int: xor = a ^ b return bin(xor).count('1')
simplelr_Data_Structure
[ { "content": "Question:\nGiven two non-negative integers `a` and `b`, write a function `count_flips_to_convert(a: int, b: int) -> int` that determines the minimal number of bits you need to flip to convert integer `a` to integer `b`. \n\n### Input/Output Formats\n\n* **Input**:\n * `a`: A non-negative integer,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1462, "level": 1, "question": "Given two non-negative integers `a` and `b`, write a function `count_flips_to_convert(a: int, b: int) -> int` that determines the minimal number of bits you need to flip to convert integer `a` to integer `b`. \n\n### Input/Output Formats\n\n* **Input**...
def find_first_equal(nums, target): for num in nums: if num == target: return num return -1
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in two parameters: a list of integers and a target integer. The function should return the first integer in the list that is equal to the target integer. If no such integer is found, the function should return -1.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1463, "level": 1, "question": "Create a function that takes in two parameters: a list of integers and a target integer. The function should return the first integer in the list that is equal to the target integer. If no such integer is found, the function should return -1.", "spli...
import math def is_sum_perfect_square(numbers): total = sum(numbers) if total < 0: return False sqrt_total = math.isqrt(total) return sqrt_total * sqrt_total == total
simplelr_Prefill
[ { "content": "Question:\nCreate a function that determines whether the sum of a list of numbers is a perfect square. If the sum is a perfect square, return `True`. If not, return `False`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1464, "level": 1, "question": "Create a function that determines whether the sum of a list of numbers is a perfect square. If the sum is a perfect square, return `True`. If not, return `False`.", "split": "train" }
def execute_python_code(code: str, input_type: str) -> any: try: if input_type in ('file', 'interactive'): namespace = {} exec(code, namespace, namespace) return None elif input_type == 'expression': globals_dict = {'__builtins__': __builtins__} ...
simplelr_Docs
[ { "content": "Question:\n#### Objective\n\nImplement a function `execute_python_code(code: str, input_type: str) -> Any` that takes a string of Python code and the type of input (either \"file\", \"interactive\", or \"expression\") and executes the code accordingly. The function should return the result of the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1465, "level": 1, "question": "#### Objective\n\nImplement a function `execute_python_code(code: str, input_type: str) -> Any` that takes a string of Python code and the type of input (either \"file\", \"interactive\", or \"expression\") and executes the code accordingly. The functi...
import seaborn as sns import matplotlib.pyplot as plt def create_custom_jointgrid(): penguins = sns.load_dataset('penguins') g = sns.JointGrid( x='bill_length_mm', y='bill_depth_mm', data=penguins, height=5, ratio=3, space=0.1 ) # Customize join...
simplelr_Docs
[ { "content": "Question:\nCustomizing a JointGrid in Seaborn\n\n**Objective**: This exercise will evaluate your understanding of how to use the `seaborn.JointGrid` class to create customized plots with seaborn functions.\n\n**Problem Statement**:\n\nYou are provided with the \"penguins\" dataset from the seaborn...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1466, "level": 1, "question": "Customizing a JointGrid in Seaborn\n\n**Objective**: This exercise will evaluate your understanding of how to use the `seaborn.JointGrid` class to create customized plots with seaborn functions.\n\n**Problem Statement**:\n\nYou are provided with the \"...
def find_min_max(numbers): if not numbers: return None return (min(numbers), max(numbers))
simplelr_Filter
[ { "content": "Question:\nCreate a Python function to find the largest and the smallest numbers in a list. The function should return a tuple with the smallest number first and the largest number second. If the list is empty, the function should return `None`.\nAnswer:\nLet's think step by step.\n", "role": ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1467, "level": 1, "question": "Create a Python function to find the largest and the smallest numbers in a list. The function should return a tuple with the smallest number first and the largest number second. If the list is empty, the function should return `None`.", "split": "tra...
import re from collections import Counter def sort_names_by_frequency(names, text): # Extract words from the text using regular expression words_in_text = re.findall(r'\b\w+\b', text) # Convert each word to lowercase for case-insensitive counting lower_words = [word.lower() for word in words_in_text] ...
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python code to sort a list of names based on the frequency of each name in a given text? The names should be sorted in descending order of their frequency. If two names have the same frequency, they should be sorted alphabetically.\nAnswer:\nLet's think step by step.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1468, "level": 1, "question": "Can you provide a Python code to sort a list of names based on the frequency of each name in a given text? The names should be sorted in descending order of their frequency. If two names have the same frequency, they should be sorted alphabetically.", ...
def group_by_length(strings): length_groups = {} for s in strings: length = len(s) length_groups.setdefault(length, []).append(s) return length_groups
simplelr_Filter
[ { "content": "Question:\nGiven a list of strings, write a Python function that groups these strings by their lengths. The output should be a dictionary where the keys are the string lengths and the values are lists of strings with the corresponding length.\nAnswer:\nLet's think step by step.\n", "role": "us...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1469, "level": 1, "question": "Given a list of strings, write a Python function that groups these strings by their lengths. The output should be a dictionary where the keys are the string lengths and the values are lists of strings with the corresponding length.", "split": "train"...
def total_cost(items): return sum(item['price'] * item['quantity'] for item in items)
simplelr_Filter
[ { "content": "Question:\nYou have been tasked with implementing a function to calculate the total cost of a list of items, where each item has a price and a quantity. The function should take a list of dictionaries as input, where each dictionary represents an item and contains the keys 'name', 'price', and 'qu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1470, "level": 1, "question": "You have been tasked with implementing a function to calculate the total cost of a list of items, where each item has a price and a quantity. The function should take a list of dictionaries as input, where each dictionary represents an item and contain...
def generate_fibonacci_like_sequence(start1, start2, length): sequence = [] if length == 0: return sequence sequence.append(start1) if length == 1: return sequence sequence.append(start2) if length == 2: return sequence for i in range(2, length): next_value = ...
simplelr_Package
[ { "content": "Question:\nGenerate a Fibonacci-like sequence using custom starting values and specific sequence length. The function should accept two starting values, a sequence length, and compute the sequence based on the summation of the two prior elements, similar to traditional Fibonacci sequence logic. Re...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1471, "level": 1, "question": "Generate a Fibonacci-like sequence using custom starting values and specific sequence length. The function should accept two starting values, a sequence length, and compute the sequence based on the summation of the two prior elements, similar to tradi...
def optimized_bubble_sort(arr): n = len(arr) while True: swapped = False for i in range(n - 1): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] swapped = True if not swapped: break n -= 1 return arr
simplelr_Algorithm
[ { "content": "Question:\n### Question: Implement an Optimized Bubble Sort with Early Termination\n\n#### Context:\nYou are tasked with improving the efficiency of sorting algorithms used in a legacy system. One approach you're exploring is optimizing the Bubble Sort algorithm by incorporating an early terminati...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1472, "level": 1, "question": "### Question: Implement an Optimized Bubble Sort with Early Termination\n\n#### Context:\nYou are tasked with improving the efficiency of sorting algorithms used in a legacy system. One approach you're exploring is optimizing the Bubble Sort algorithm ...
def maxProfit(prices): if len(prices) < 2: return 0 buy1 = buy2 = float('-inf') sell1 = 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 = max(sell2, buy2 + price) ...
simplelr_Leetcode
[ { "content": "Question:\nCreate a function that takes a list of `n` integers representing daily stock prices and returns the maximum profit that can be achieved by buying and selling the stock at most twice. You need to buy before you can sell, and you cannot engage in multiple transactions simultaneously (i.e....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1473, "level": 1, "question": "Create a function that takes a list of `n` integers representing daily stock prices and returns the maximum profit that can be achieved by buying and selling the stock at most twice. You need to buy before you can sell, and you cannot engage in multipl...
def roman_to_integer(s): roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} total = 0 for i in range(len(s)): current = roman_dict[s[i]] if i < len(s) - 1 and current < roman_dict[s[i + 1]]: total -= current else: total += current ...
simplelr_Filter
[ { "content": "Question:\nWrite a Python program that converts a Roman numeral to an integer. The input will be a string representing a valid Roman numeral up to 3999.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1474, "level": 1, "question": "Write a Python program that converts a Roman numeral to an integer. The input will be a string representing a valid Roman numeral up to 3999.", "split": "train" }
def has_unique_characters(s): seen = set() for char in s: if char in seen: return False seen.add(char) return True
simplelr_Filter
[ { "content": "Question:\nGiven a string, create a function to check if the string contains only unique characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1475, "level": 1, "question": "Given a string, create a function to check if the string contains only unique characters.", "split": "train" }
from typing import List def max_consecutive_ones(binary_list: List[str]) -> int: global_max = 0 for s in binary_list: current = 0 max_in_s = 0 for c in s: if c == '1': current += 1 if current > max_in_s: max_in_s = current ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are given a list of strings where each string represents a binary number (consisting of 0s and 1s). Write a function `max_consecutive_ones` which finds the maximum number of consecutive 1s in any binary number in the list. \n\n### Specifications\n* **Function ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1476, "level": 1, "question": "### Problem Statement\nYou are given a list of strings where each string represents a binary number (consisting of 0s and 1s). Write a function `max_consecutive_ones` which finds the maximum number of consecutive 1s in any binary number in the list. \n...
from functools import reduce def sum_integers(numbers): return reduce(lambda x, y: x + y, numbers, 0)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers and uses the `reduce` function to sum all the integers in the list. If no integers are present, the function should return 0. How can you implement this in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1477, "level": 1, "question": "Create a function that takes a list of integers and uses the `reduce` function to sum all the integers in the list. If no integers are present, the function should return 0. How can you implement this in Python?", "split": "train" }
from typing import List, Tuple, Dict def track_stamps(transactions: List[Tuple[str, str]]) -> Dict[str, Dict[str, int]]: customer_data = {} for transaction in transactions: name, action = transaction if action == 'buy': if name not in customer_data: customer_data[nam...
simplelr_Taco
[ { "content": "Question:\n# Story\n\nA famous music store offers a special discount policy for loyal customers. Each time a customer buys an album, they receive a loyalty card stamp. Once they have collected 10 stamps, they can get a free album. You need to design an application that helps the store track the nu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1478, "level": 1, "question": "# Story\n\nA famous music store offers a special discount policy for loyal customers. Each time a customer buys an album, they receive a loyalty card stamp. Once they have collected 10 stamps, they can get a free album. You need to design an applicatio...
def even_fibonacci(n): """Return the sum of the even-valued Fibonacci numbers less than n.""" a = 1 b = 2 sum = 0 while b < n: if b % 2 == 0: sum += b a, b = b, a + b return sum
simplelr_Filter
[ { "content": "Question:\nThe following is my current code: \n```python\ndef even_fibonacci(n):\n \"\"\"Return the sum of the even-valued Fibonacci numbers less than n.\"\"\"\n a = 1\n b = 2\n sum = 0\n while b < n:\n if b % 2 == 0:\n sum += b\n a, b = b, a + b\n return sum\nAnswer:\nLet's think...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1479, "level": 1, "question": "The following is my current code: \n```python\ndef even_fibonacci(n):\n \"\"\"Return the sum of the even-valued Fibonacci numbers less than n.\"\"\"\n a = 1\n b = 2\n sum = 0\n while b < n:\n if b % 2 == 0:\n sum += b\n a, b = b, a + b\...
import heapq def min_cost_to_combine_stones(stones): if len(stones) < 2: return 0 heapq.heapify(stones) total = 0 while len(stones) > 1: a = heapq.heappop(stones) b = heapq.heappop(stones) s = a + b total += s heapq.heappush(stones, s) return total
simplelr_Leetcode
[ { "content": "Question:\nYou are given an integer array `stones` where `stones[i]` represents the weight of the `i`th stone. We are to combine these stones into one stone by performing the following operation until only one stone is left:\n\n1. Choose two stones with the smallest weights (let's call them `a` an...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1480, "level": 1, "question": "You are given an integer array `stones` where `stones[i]` represents the weight of the `i`th stone. We are to combine these stones into one stone by performing the following operation until only one stone is left:\n\n1. Choose two stones with the small...
def enhanced_split(path: str, delimiter: str = '/') -> tuple: """ Splits the input path into two parts using the last occurrence of the specified delimiter. Args: path (str): The input file path. delimiter (str): The delimiter to split the path. Default is '/'. Returns: tuple: A tu...
simplelr_Data_Structure
[ { "content": "Question:\nYou are given a function `split` which takes a path as input and splits it into two parts using the last occurrence of the '/' delimiter. Your task is to extend this function to handle a broader range of file path manipulations while preserving its original purpose and efficiency. Addit...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1481, "level": 1, "question": "You are given a function `split` which takes a path as input and splits it into two parts using the last occurrence of the '/' delimiter. Your task is to extend this function to handle a broader range of file path manipulations while preserving its ori...
import math def power_using_math_pow(base, exponent): result = math.pow(base, exponent) if result == int(result): return int(result) else: return result
simplelr_Filter
[ { "content": "Question:\nIn Python, how can I implement a function that calculates the power of a number using the `math.pow` function, ensuring that the result is returned as an integer when possible?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1482, "level": 1, "question": "In Python, how can I implement a function that calculates the power of a number using the `math.pow` function, ensuring that the result is returned as an integer when possible?", "split": "train" }
import numpy as np def create_array_from_range(range_str): parts = range_str.split(':') if len(parts) < 2: raise ValueError("Invalid range string. Must have at least start and end.") start = int(parts[0]) end = int(parts[1]) if len(parts) == 3: step = int(parts[2]) else: ...
simplelr_Filter
[ { "content": "Question:\nHey, I need some help writing a Python function that can create an array from a range. The function should be able to take any range in the form of a string like \"1:10\", \"30:50\", or \"5:-5\" and convert it into a NumPy array with a starting number, end number, and step value. Could ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1483, "level": 1, "question": "Hey, I need some help writing a Python function that can create an array from a range. The function should be able to take any range in the form of a string like \"1:10\", \"30:50\", or \"5:-5\" and convert it into a NumPy array with a starting number,...
def grade_text(score): if not (0 <= score <= 100): raise ValueError("Score must be between 0 and 100") if score >= 90: return 'A' elif score >= 80: return 'B' elif score >= 70: return 'C' elif score >= 60: return 'D' else: return 'F'
simplelr_Apps
[ { "content": "Question:\nYou are tasked with creating a simple text-based grading system. The grading system converts numerical scores into letter grades according to the following scale:\n\n- 90 and above: A\n- 80 to 89: B\n- 70 to 79: C\n- 60 to 69: D\n- Below 60: F\n\nCreate a function called `grade_text(sco...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1484, "level": 1, "question": "You are tasked with creating a simple text-based grading system. The grading system converts numerical scores into letter grades according to the following scale:\n\n- 90 and above: A\n- 80 to 89: B\n- 70 to 79: C\n- 60 to 69: D\n- Below 60: F\n\nCreat...
import csv def read_and_print_first_five_rows(filename): """ Reads a CSV file and prints the first five rows. Args: filename (str): The name of the CSV file to read. Raises: FileNotFoundError: If the specified file does not exist. """ try: with open(filename, '...
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python function that reads a CSV file and prints the first five rows?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1485, "level": 1, "question": "Can you provide a Python function that reads a CSV file and prints the first five rows?", "split": "train" }
def decimal_to_binary(n): if n == 0: return '0' is_negative = False if n < 0: is_negative = True n = -n # Work with the absolute value binary_digits = [] while n > 0: remainder = n % 2 binary_digits.append(str(remainder)) n = n // 2 # Reverse to g...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that converts a given decimal number into its binary representation as a string, without using in-built conversion functions. The function should handle both positive and negative integers, and return the string representation of its binary equivalent. Additionally, th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1486, "level": 1, "question": "Create a function that converts a given decimal number into its binary representation as a string, without using in-built conversion functions. The function should handle both positive and negative integers, and return the string representation of its ...
def most_frequent_number(arr): if not arr: return -1 freq = {} for num in arr: if num in freq: freq[num] += 1 else: freq[num] = 1 max_freq = max(freq.values()) candidates = [k for k, v in freq.items() if v == max_freq] return min(candidates)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a fixed-length array of integers as input and returns the integer that appears most frequently in the array. If there is a tie, return the smallest number. If the array is empty, return -1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1487, "level": 1, "question": "Create a function that takes a fixed-length array of integers as input and returns the integer that appears most frequently in the array. If there is a tie, return the smallest number. If the array is empty, return -1.", "split": "train" }
def caesar_cipher(text, shift): result = [] for char in text: if char.islower(): base = ord('a') elif char.isupper(): base = ord('A') else: result.append(char) continue shifted = (ord(char) - base + shift) % 26 result.append...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to implement the Caesar cipher.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1488, "level": 1, "question": "Write a function to implement the Caesar cipher.", "split": "train" }
def find_missing_number(lst): n = len(lst) + 1 expected_sum = n * (n + 1) // 2 actual_sum = sum(lst) return expected_sum - actual_sum
simplelr_Taco
[ { "content": "Question:\n*** Find the Missing Number ***\n\nYou will be given an array containing `n-1` unique integers from the range `1` to `n`. The array does not contain duplicates, and one integer is missing from the series. Your task is to find the missing integer.\n\nYou must solve this without using any...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1489, "level": 1, "question": "*** Find the Missing Number ***\n\nYou will be given an array containing `n-1` unique integers from the range `1` to `n`. The array does not contain duplicates, and one integer is missing from the series. Your task is to find the missing integer.\n\nYo...
def remove_occurrences(arr, x): return [num for num in arr if num != x]
simplelr_Filter
[ { "content": "Question:\nGiven an array `arr` of integers and an element `x`, how can I remove all occurrences of `x` from `arr` and return the resulting array?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1490, "level": 1, "question": "Given an array `arr` of integers and an element `x`, how can I remove all occurrences of `x` from `arr` and return the resulting array?", "split": "train" }
def can_partition(nums): total = sum(nums) if total % 2 != 0: return False target = total // 2 possible_sums = {0} for num in nums: for s in list(possible_sums): new_sum = s + num if new_sum == target: return True elif new_sum < tar...
simplelr_Apps
[ { "content": "Question:\nGiven an array of integers, determine whether the array can be partitioned into two subsets such that the sum of the elements in both subsets is equal.\n\nWrite a function that accepts an array of integers and returns `true` if the array can be partitioned into two subsets with equal su...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1491, "level": 1, "question": "Given an array of integers, determine whether the array can be partitioned into two subsets such that the sum of the elements in both subsets is equal.\n\nWrite a function that accepts an array of integers and returns `true` if the array can be partiti...
import math def count_paths(n: int, m: int) -> int: return math.comb(n + m - 2, n - 1)
simplelr_Algorithm
[ { "content": "Question:\n### Matrix Path Counting\n\n#### Problem Statement\nYou are given an `n x m` grid, and you start at the top-left corner of the grid (position (0, 0)). You can only move right or down at any point in time. The goal is to reach the bottom-right corner of the grid (position (n-1, m-1)).\n\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1492, "level": 1, "question": "### Matrix Path Counting\n\n#### Problem Statement\nYou are given an `n x m` grid, and you start at the top-left corner of the grid (position (0, 0)). You can only move right or down at any point in time. The goal is to reach the bottom-right corner of...
import numpy as np from typing import List, Tuple def reshape_matrix(nums: List[int], shape: Tuple[int, int]) -> np.ndarray: rows, cols = shape total = rows * cols filled_nums = nums[:total] if len(filled_nums) < total: filled_nums += [None] * (total - len(filled_nums)) return np.array(fill...
simplelr_Package
[ { "content": "Question:\nYou need to write a function that reshapes a given list of integers into a specified matrix shape. The function should take a list of integers and a tuple specifying the desired matrix shape (rows, columns). The matrix should be filled with the integers from the list row-wise. If there ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1493, "level": 1, "question": "You need to write a function that reshapes a given list of integers into a specified matrix shape. The function should take a list of integers and a tuple specifying the desired matrix shape (rows, columns). The matrix should be filled with the integer...
def find_minimum(lst): if not lst: return None return min(lst)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the minimum value in a list of numbers. If the list is empty, the function should return None. The function should have a time complexity of O(n).\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1494, "level": 1, "question": "Write a python function to find the minimum value in a list of numbers. If the list is empty, the function should return None. The function should have a time complexity of O(n).", "split": "train" }
def longest_consecutive_sequence(arr): unique_sorted = sorted(set(arr)) if not unique_sorted: return 0 max_length = 1 current_length = 1 for i in range(1, len(unique_sorted)): if unique_sorted[i] == unique_sorted[i-1] + 1: current_length += 1 else: cur...
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `arr`, return the **length of the longest** consecutive elements sequence. A consecutive elements sequence is a sequence of numbers, each either one less than or one more than its predecessor. The sequence doesn't have to be sorted within the array; only the conse...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1495, "level": 1, "question": "Given an integer array `arr`, return the **length of the longest** consecutive elements sequence. A consecutive elements sequence is a sequence of numbers, each either one less than or one more than its predecessor. The sequence doesn't have to be sort...
def second_smallest(lst): unique = list(set(lst)) if len(unique) < 2: return None unique.sort() return unique[1]
simplelr_Apps
[ { "content": "Question:\nCreate a function that takes a list of integers and returns the second smallest number. If the list is empty or contains less than two unique elements, return None.\n\nExample:\n\n```python\nsecond_smallest([3, 1, 4, 1, 5, 9]) --> 3\nsecond_smallest([10, 20, 30, 20, 40, 10]) --> 20\nsec...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1496, "level": 1, "question": "Create a function that takes a list of integers and returns the second smallest number. If the list is empty or contains less than two unique elements, return None.\n\nExample:\n\n```python\nsecond_smallest([3, 1, 4, 1, 5, 9]) --> 3\nsecond_smallest([1...
from typing import List, Tuple def bitwise_array_manipulator(arr: List[int], ops: List[Tuple[str, int, int, int]]) -> List[bool]: result = [] for op in ops: command, idx, bidx, val = op current = arr[idx] if command == 'get': mask = 1 << bidx res = (current & mas...
simplelr_Data_Structure
[ { "content": "Question:\nImplement a Bitwise Array Manipulator\n\n#### Context\nYou are tasked with manipulating an array of integers at the bit level to optimize memory usage for a performance-critical application. Specifically, you need to perform various operations on the bits of these integers in the array ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1497, "level": 1, "question": "Implement a Bitwise Array Manipulator\n\n#### Context\nYou are tasked with manipulating an array of integers at the bit level to optimize memory usage for a performance-critical application. Specifically, you need to perform various operations on the b...
def jump(nums): n = len(nums) if n <= 1: return 0 jumps = 0 current_end = 0 farthest = 0 for i in range(n): if i > current_end: return -1 farthest = max(farthest, i + nums[i]) if i == current_end: if farthest == current_end: ...
simplelr_Taco
[ { "content": "Question:\nYou are given an array of integers where each element represents the maximum number of steps you can jump forward from that position. Write a function to determine the minimum number of jumps you need to reach the last position of the array. If it's not possible to reach the end of the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1498, "level": 1, "question": "You are given an array of integers where each element represents the maximum number of steps you can jump forward from that position. Write a function to determine the minimum number of jumps you need to reach the last position of the array. If it's no...
from typing import List def canArrangeBalloons(n: int, balloons: List[str]) -> str: max_len = max(len(s) for s in balloons) for j in range(max_len): colors = [] for s in balloons: if j < len(s): colors.append(s[j]) freq = {} max_freq = 0 ...
simplelr_Codeforces
[ { "content": "Question:\nAlice is hosting a themed party and she wants to decorate the venue with balloons. She has `n` balloons of different colors. Each balloon is represented as a string `s` of length `m` where each character in the string represents a color segment of that balloon. For instance, the balloon...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 1499, "level": 1, "question": "Alice is hosting a themed party and she wants to decorate the venue with balloons. She has `n` balloons of different colors. Each balloon is represented as a string `s` of length `m` where each character in the string represents a color segment of that...