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 math def sieve_of_eratosthenes(n): if n < 2: return set() is_prime = [True] * (n + 1) is_prime[0], is_prime[1] = False, False for p in range(2, int(math.sqrt(n)) + 1): if is_prime[p]: for multiple in range(p * p, n + 1, p): is_prime[multiple] = False ...
simplelr_Filter
[ { "content": "Question:\nCan you help me find a Python method to create a set of all prime numbers up to a given number n?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8300, "level": 1, "question": "Can you help me find a Python method to create a set of all prime numbers up to a given number n?", "split": "train" }
def transform_string_to_ascii(s): ascii_values = [] for char in s: ascii_values.append(str(ord(char))) return ''.join(ascii_values)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that transforms a given string by replacing each character with its ASCII value and then concatenating them together. For example, the string \"hello\" should be transformed to \"104101108108111\".\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8301, "level": 1, "question": "Create a function that transforms a given string by replacing each character with its ASCII value and then concatenating them together. For example, the string \"hello\" should be transformed to \"104101108108111\".", "split": "train" }
def process_transactions(users, transactions): # Convert users list into a dictionary for easier access by name user_balances = {user['name']: user['balance'] for user in users} for transaction in transactions: parts = transaction.split() if not parts: continue # Skip empty...
simplelr_Taco
[ { "content": "Question:\n**Bank Account Transaction Processor**\n\nA bank maintains a system to manage and process various types of transactions in user accounts. Each user has an account with a balance and can perform transactions which include deposits, withdrawals, and transfers. The bank needs to support ba...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8302, "level": 1, "question": "**Bank Account Transaction Processor**\n\nA bank maintains a system to manage and process various types of transactions in user accounts. Each user has an account with a balance and can perform transactions which include deposits, withdrawals, and tran...
def count_k_complement_pairs(arr, k): freq = {} for num in arr: if num in freq: freq[num] += 1 else: freq[num] = 1 unique = sorted(freq.keys()) count = 0 for x in unique: y = k - x if y in freq: if y == x: if fr...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of integers `arr` and an integer `k`. Define a **k-complement** of an integer `x` as the number `y` such that `x + y = k`. Write a function to find the number of unique pairs `(x, y)` in the array that satisfy the k-complement requirement. Each pair should be coun...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8303, "level": 1, "question": "You are given an array of integers `arr` and an integer `k`. Define a **k-complement** of an integer `x` as the number `y` such that `x + y = k`. Write a function to find the number of unique pairs `(x, y)` in the array that satisfy the k-complement re...
def find_first_greater(arr, num): for index, value in enumerate(arr): if value > num: return index return -1
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the first occurrence of an element in an array that is greater than a given number. If no such element exists, return -1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8304, "level": 1, "question": "Write a function to find the first occurrence of an element in an array that is greater than a given number. If no such element exists, return -1.", "split": "train" }
def swap_case(s): return ''.join([c.lower() if c.isupper() else c.upper() for c in s])
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as an argument and returns a new string with each character's case swapped.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8305, "level": 1, "question": "Create a function that takes a string as an argument and returns a new string with each character's case swapped.", "split": "train" }
def longest_same_subarray(nums): if not nums: return 0 max_length = 1 current_length = 1 for i in range(1, len(nums)): if nums[i] == nums[i-1]: current_length += 1 else: if current_length > max_length: max_length = current_length ...
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes an array of integers and returns the length of the longest contiguous subarray where all elements have the same value. For example, given the array [1, 2, 2, 3, 3, 3, 1], the function should return 3, corresponding to the subarray [3, 3, 3].\n\nMore examples ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8306, "level": 1, "question": "Write a function that takes an array of integers and returns the length of the longest contiguous subarray where all elements have the same value. For example, given the array [1, 2, 2, 3, 3, 3, 1], the function should return 3, corresponding to the su...
def enhanced_exchange_sort(arr, comparator): n = len(arr) for i in range(n - 1): for j in range(n - i - 1): if comparator(arr[j], arr[j + 1]) == 1: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr
simplelr_Data_Structure
[ { "content": "Question:\nEnhanced Exchange Sort with Custom Comparer\n\nYou are given an implementation of the Exchange Sort algorithm. The algorithm has O(n^2) complexity and is used for small datasets due to its simplicity. Your task is to enhance the given Exchange Sort function to allow for custom sorting o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8307, "level": 1, "question": "Enhanced Exchange Sort with Custom Comparer\n\nYou are given an implementation of the Exchange Sort algorithm. The algorithm has O(n^2) complexity and is used for small datasets due to its simplicity. Your task is to enhance the given Exchange Sort fun...
def cyclic_shifted_string(s1, s2): if len(s1) != len(s2): return False return s2 in s1 + s1
simplelr_Evol
[ { "content": "Question:\nWrite a function called `cyclic_shifted_string(s1, s2)` that checks whether one string is a cyclic shift of another. A cyclic shift shifts all characters of the string to the right and the characters that fall off are moved to the beginning of the string. \n\nFor example, \"abcde\" cycl...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8308, "level": 1, "question": "Write a function called `cyclic_shifted_string(s1, s2)` that checks whether one string is a cyclic shift of another. A cyclic shift shifts all characters of the string to the right and the characters that fall off are moved to the beginning of the stri...
def int_to_roman(num): roman_numerals = [ (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I') ] res = '' for value, numeral in roman_numerals: while num >= value: ...
simplelr_Taco
[ { "content": "Question:\nCreate a Roman Numeral Converter\n\nYou will need to convert a given integer to its equivalent Roman numeral representation. The Roman numeral system uses the following symbols:\n\n- I - 1\n- V - 5\n- X - 10\n- L - 50\n- C - 100\n- D - 500\n- M - 1000\n\nFor example:\n\n```python\nint_t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8309, "level": 1, "question": "Create a Roman Numeral Converter\n\nYou will need to convert a given integer to its equivalent Roman numeral representation. The Roman numeral system uses the following symbols:\n\n- I - 1\n- V - 5\n- X - 10\n- L - 50\n- C - 100\n- D - 500\n- M - 1000\...
def strings_by_unique_characters(strings): char_dict = {} for s in strings: reversed_s = s[::-1] unique_chars = set(reversed_s) for char in unique_chars: if char not in char_dict: char_dict[char] = [] char_dict[char].append(s) return char_dict
simplelr_Filter
[ { "content": "Question:\nGiven a list of strings, you need to create a function that returns a dictionary where each key is a unique character from the strings and the corresponding value is a list of strings that contain that character. Reverse each string in the input list before processing. This problem requ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8310, "level": 1, "question": "Given a list of strings, you need to create a function that returns a dictionary where each key is a unique character from the strings and the corresponding value is a list of strings that contain that character. Reverse each string in the input list b...
from typing import List, Tuple def process_list(nums: List[int], operations: List[Tuple[str, int]]) -> List[int]: result = nums.copy() for op in operations: action, value = op if action in ("insert", "append"): result.append(value) elif action == "delete": if val...
simplelr_Package
[ { "content": "Question:\nIn the field of data structures, efficient manipulation and management of collections of elements is paramount. This problem involves implementing a function to perform a specific series of operations on a list of integers.\n\nYou are required to implement the function `process_list(num...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8311, "level": 1, "question": "In the field of data structures, efficient manipulation and management of collections of elements is paramount. This problem involves implementing a function to perform a specific series of operations on a list of integers.\n\nYou are required to imple...
import math def check_perfect_square(num): if num < 0: return -1 s = math.isqrt(num) if s * s == num: return s else: return -1
simplelr_Prefill
[ { "content": "Question:\nCreate a function that checks if a given number is a perfect square. If it is, return the square root of the number. If it is not, return -1. This function should work for both positive and negative integers. For negative numbers, the function should simply return -1.\nAnswer:\nLet's th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8312, "level": 1, "question": "Create a function that checks if a given number is a perfect square. If it is, return the square root of the number. If it is not, return -1. This function should work for both positive and negative integers. For negative numbers, the function should s...
from PIL import Image import numpy as np def resize_image(file_path, height, width, n=None): img = Image.open(file_path) if n is not None: if n == 1: img = img.convert('L') elif n == 3: img = img.convert('RGB') else: raise ValueError("n must be e...
simplelr_Filter
[ { "content": "Question:\n### Pinging a colored or grayscale\nAn image for a web page can be represented by a 3D numpy array of size (height, width, n), where n = 3 for a color image or n = 1\nfor a grayscale image. Write a function that can take a file path to an image and return a resized image of the\nspecifi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8313, "level": 1, "question": "### Pinging a colored or grayscale\nAn image for a web page can be represented by a 3D numpy array of size (height, width, n), where n = 3 for a color image or n = 1\nfor a grayscale image. Write a function that can take a file path to an image and ret...
from typing import List def max_profit(prices: List[int]) -> int: if len(prices) < 2: return 0 min_price = prices[0] max_profit = 0 for price in prices[1:]: if price < min_price: min_price = price else: current_profit = price - min_price if cu...
simplelr_Taco
[ { "content": "Question:\nGiven an integer list representing stock prices over `n` days, determine the maximum profit that could be achieved by buying and selling the stock exactly once. Note that you must buy before you can sell, and there is no possibility to short sell.\n\nWrite a function `max_profit(prices:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8314, "level": 1, "question": "Given an integer list representing stock prices over `n` days, determine the maximum profit that could be achieved by buying and selling the stock exactly once. Note that you must buy before you can sell, and there is no possibility to short sell.\n\nW...
from collections import deque from typing import Dict, List def shortest_path(graph: Dict[int, List[int]], start: int, end: int) -> List[int]: if start == end: return [start] queue = deque() queue.append((start, [start])) visited = set() visited.add(start) while queue: ...
simplelr_Code_Contests
[ { "content": "Question:\nEmily just started learning about graphs in her computer science class. She learned about how graphs can be used to represent connections between various points, called nodes. The connections between these nodes are referred to as edges. \n\nTo further her understanding, she wants to wr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8315, "level": 1, "question": "Emily just started learning about graphs in her computer science class. She learned about how graphs can be used to represent connections between various points, called nodes. The connections between these nodes are referred to as edges. \n\nTo further...
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm def plot_kmeans_clusters(X, centroids, labels, filename): plt.figure(figsize=(10, 8)) k = centroids.shape[0] colors = cm.rainbow(np.linspace(0, 1, k)) for i in range(k): cluster_points = X[labels == i] ...
simplelr_Package
[ { "content": "Question:\nYou are required to write a function `plot_kmeans_clusters(X, centroids, labels, filename)` that visualizes the results of the k-means clustering algorithm. The function should generate a plot with the following features:\n\n1. **Cluster Scatter Plot**: Display the data points color-cod...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8316, "level": 1, "question": "You are required to write a function `plot_kmeans_clusters(X, centroids, labels, filename)` that visualizes the results of the k-means clustering algorithm. The function should generate a plot with the following features:\n\n1. **Cluster Scatter Plot**...
def remove_duplicates_optimized(array: list) -> list: seen = set() result = [] for element in array: if element not in seen: seen.add(element) result.append(element) return result
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario\nYou are given a list of elements which may contain duplicates. The goal is to write a function that removes the duplicates while maintaining the order of their first occurrence. However, the current implementation provided has a performance bottleneck due to its time compl...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8317, "level": 1, "question": "### Scenario\nYou are given a list of elements which may contain duplicates. The goal is to write a function that removes the duplicates while maintaining the order of their first occurrence. However, the current implementation provided has a performan...
def trap_water_capacity(heights, v): n = len(heights) if n < 3: return 0 # Can't trap water with less than 3 buildings left_max = [0] * n right_max = [0] * n # Compute left_max array left_max[0] = heights[0] for i in range(1, n): left_max[i] = max(left_max[i-1], he...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an integer array `heights` representing the heights of buildings in a row, and an integer `v` representing the maximum volume of water that can be trapped between the buildings after it rains. For each building, water can only be trapped between buildings that are taller t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8318, "level": 1, "question": "You are given an integer array `heights` representing the heights of buildings in a row, and an integer `v` representing the maximum volume of water that can be trapped between the buildings after it rains. For each building, water can only be trapped ...
def find_smallest_of_four(a, b, c, d): return min(a, b, c, d)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes as its input 4 numbers and outputs the smallest of the four.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8319, "level": 1, "question": "Create a function that takes as its input 4 numbers and outputs the smallest of the four.", "split": "train" }
def group_integers(lst): result = { 'positive': [], 'negative': [], 'even-and-divisible-by-three': [] } for num in lst: if num > 0: result['positive'].append(num) elif num < 0: result['negative'].append(num) else: if num % 2...
simplelr_Evol
[ { "content": "Question:\nGiven a list of integers, your task is to group these integers based on their properties into one of three categories: \"positive\", \"negative\", or \"even-and-divisible-by-three\". The categorization should follow these rules:\n\n1. Positive: The integer is greater than 0.\n2. Negativ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8320, "level": 1, "question": "Given a list of integers, your task is to group these integers based on their properties into one of three categories: \"positive\", \"negative\", or \"even-and-divisible-by-three\". The categorization should follow these rules:\n\n1. Positive: The int...
def longest_common_subsequence(s1: str, s2: str) -> int: len_s1 = len(s1) len_s2 = len(s2) # Create a table with (len_s1+1) rows and (len_s2+1) columns dp = [[0] * (len_s2 + 1) for _ in range(len_s1 + 1)] for i in range(1, len_s1 + 1): for j in range(1, len_s2 + 1): # I...
simplelr_Algorithm
[ { "content": "Question:\n### Longest Common Subsequence\n\n**Problem Statement**:\nYou are given two strings, `s1` and `s2`. Your task is to find and return the length of their longest common subsequence. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements witho...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8321, "level": 1, "question": "### Longest Common Subsequence\n\n**Problem Statement**:\nYou are given two strings, `s1` and `s2`. Your task is to find and return the length of their longest common subsequence. A subsequence is a sequence that can be derived from another sequence by...
def modify_list(lst, operation): operations = { "add": lambda x: x + 1, "subtract": lambda x: x - 1, "none": lambda x: x } if operation not in operations: raise ValueError("Invalid operation") return [operations[operation](x) for x in lst]
simplelr_Filter
[ { "content": "Question:\nI have a function that currently adds 1 to all values in a list. I want to modify it to also add the option to subtract 1 from all values in the list, or to do nothing to the list. \n\nHere's a way I could do it:\n```python\ndef modify_list(lst, operation):\n if operation == \"add\":...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8322, "level": 1, "question": "I have a function that currently adds 1 to all values in a list. I want to modify it to also add the option to subtract 1 from all values in the list, or to do nothing to the list. \n\nHere's a way I could do it:\n```python\ndef modify_list(lst, operat...
def perimeter_of_square(side_length): return side_length * 4
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the perimeter of a square given its side length. The function should be able to handle both integer and floating-point side lengths.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8323, "level": 1, "question": "Write a function to find the perimeter of a square given its side length. The function should be able to handle both integer and floating-point side lengths.", "split": "train" }
import linecache def get_lines(files_lines_dict: dict) -> dict: result = {} for filename, line_nums in files_lines_dict.items(): linecache.checkcache(filename) lines = [] for num in line_nums: line = linecache.getline(filename, num) lines.append(line) res...
simplelr_Docs
[ { "content": "Question:\n### **Problem Statement: Efficient Line Retrieval and Cache Management**\n\nYou are tasked with implementing a small script that uses the `linecache` module to efficiently manage and retrieve specific lines from a set of text files. You will implement a function `get_lines(files_lines_d...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8324, "level": 1, "question": "### **Problem Statement: Efficient Line Retrieval and Cache Management**\n\nYou are tasked with implementing a small script that uses the `linecache` module to efficiently manage and retrieve specific lines from a set of text files. You will implement ...
def max_skyline_area(heights): stack = [] max_area = 0 n = len(heights) for i in range(n): while stack and heights[i] < heights[stack[-1]]: h = heights[stack.pop()] if stack: w = i - stack[-1] - 1 else: w = i max_are...
simplelr_Apps
[ { "content": "Question:\nGiven a list of integers representing the heights of buildings in a skyline, your task is to find the maximum area of a rectangle that can be formed between the buildings, where the width of each building is 1 unit.\n\nWrite a function `max_skyline_area` that takes a list of integers as...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8325, "level": 1, "question": "Given a list of integers representing the heights of buildings in a skyline, your task is to find the maximum area of a rectangle that can be formed between the buildings, where the width of each building is 1 unit.\n\nWrite a function `max_skyline_are...
def find_smallest_sequence(s: str, k: int) -> str: stack = [] for num in s: while k > 0 and stack and stack[-1] > num: stack.pop() k -= 1 stack.append(num) # If there are remaining k, remove from the end if k > 0: stack = stack[:-k] # Convert to string...
simplelr_Code_Contests
[ { "content": "Question:\nA group of archaeologists has discovered an ancient number puzzle engraved on a stone tablet. The puzzle consists of a number sequence represented in a peculiar way. \n\nThe tablet contains a sequence of digits, and the puzzle is to find the smallest possible numeric sequence of a given...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8326, "level": 1, "question": "A group of archaeologists has discovered an ancient number puzzle engraved on a stone tablet. The puzzle consists of a number sequence represented in a peculiar way. \n\nThe tablet contains a sequence of digits, and the puzzle is to find the smallest p...
def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[-1] less = [x for x in arr[:-1] if x < pivot] equal = [x for x in arr if x == pivot] greater = [x for x in arr[:-1] if x > pivot] return quicksort(less) + equal + quicksort(greater)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to sort an array in ascending order using the quicksort algorithm. I am looking for a Python implementation.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8327, "level": 1, "question": "Write a function to sort an array in ascending order using the quicksort algorithm. I am looking for a Python implementation.", "split": "train" }
def reverse_words(sentence): return ' '.join(sentence.split()[::-1])
simplelr_Prefill
[ { "content": "Question:\nWrite a function to reverse the order of words in a given sentence. The function should return the reversed sentence as a string. For example, if the input sentence is \"Hello World from Alibaba\", the output should be \"Alibaba from World Hello\".\nAnswer:\nLet's think step by step.\n"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8328, "level": 1, "question": "Write a function to reverse the order of words in a given sentence. The function should return the reversed sentence as a string. For example, if the input sentence is \"Hello World from Alibaba\", the output should be \"Alibaba from World Hello\".", ...
def invert_dict(d): return {v: k for k, v in d.items()}
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a dictionary as an input and returns a new dictionary with the keys and values switched.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8329, "level": 1, "question": "Create a function that takes a dictionary as an input and returns a new dictionary with the keys and values switched.", "split": "train" }
def reverse_string(s): return s[::-1]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as input and returns a reversed version of the string. Can you walk me through the steps to create this function?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8330, "level": 1, "question": "Create a function that takes a string as input and returns a reversed version of the string. Can you walk me through the steps to create this function?", "split": "train" }
def length_of_longest_substring(s): char_index = {} start = 0 max_len = 0 for end in range(len(s)): if s[end] in char_index: # Move start to one position after the last occurrence of s[end] start = max(start, char_index[s[end]] + 1) char_index[s[end]] = end ...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s`, return the length of the longest substring that contains no repeated characters. The substring must be contiguous but does not need to be a dictionary word. Your solution should achieve this in linear time complexity, considering the optimal approach to efficiently d...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8331, "level": 1, "question": "Given a string `s`, return the length of the longest substring that contains no repeated characters. The substring must be contiguous but does not need to be a dictionary word. Your solution should achieve this in linear time complexity, considering th...
from collections import defaultdict import heapq def shortest_path_with_constraints(roads, source, destination, blocked): # Process blocked roads into a set of frozensets for quick lookup blocked_edges = set() for u, v in blocked: blocked_edges.add(frozenset({u, v})) # Collect all nodes fr...
simplelr_Algorithm
[ { "content": "Question:\n### Road Network Optimization - Shortest Path with Constraints\n\n#### Background\nYou are given a road network represented as a graph where nodes represent cities and edges represent the roads connecting these cities. Each road has a corresponding travel time. However, due to road main...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8332, "level": 1, "question": "### Road Network Optimization - Shortest Path with Constraints\n\n#### Background\nYou are given a road network represented as a graph where nodes represent cities and edges represent the roads connecting these cities. Each road has a corresponding tra...
def sum_of_squares(lst): total = 0 for num in lst: total += num ** 2 return total
simplelr_Prefill
[ { "content": "Question:\nCreate a function that returns the sum of the squares of the numbers in a list using Python. You are not allowed to use any built-in functions or libraries. Please implement the function from scratch.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8333, "level": 1, "question": "Create a function that returns the sum of the squares of the numbers in a list using Python. You are not allowed to use any built-in functions or libraries. Please implement the function from scratch.", "split": "train" }
import csv def char_frequency(input_str): frequency = {} for char in input_str: if char in frequency: frequency[char] += 1 else: frequency[char] = 1 with open("char_frequency.csv", "w", newline='') as csvfile: fieldnames = ['Character', 'Count'] writ...
simplelr_Evol
[ { "content": "Question:\nWrite a Python function that takes a string as input, counts the frequency of each character in the string, and returns a dictionary with characters as keys and their respective counts as values. Additionally, create a CSV file that contains two columns: 'Character' and 'Count', listing...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8334, "level": 1, "question": "Write a Python function that takes a string as input, counts the frequency of each character in the string, and returns a dictionary with characters as keys and their respective counts as values. Additionally, create a CSV file that contains two column...
from collections import deque def shortest_path(grid: list[list[int]], start: tuple[int, int], end: tuple[int, int]) -> int: if start == end: return 0 rows = len(grid) cols = len(grid[0]) if rows > 0 else 0 visited = [[False for _ in range(cols)] for _ in range(rows)] queue = deque() ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are working on a project for a logistics company that involves optimizing their delivery routes. One key feature of the application is to find the shortest path between two delivery points in a city represented as a grid, where some cells are impassable due ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8335, "level": 1, "question": "### Problem Statement\n\nYou are working on a project for a logistics company that involves optimizing their delivery routes. One key feature of the application is to find the shortest path between two delivery points in a city represented as a grid, w...
import seaborn as so import matplotlib.pyplot as plt def advanced_seaborn_plot(): # Load the dataset data = so.load_dataset('anscombe') # Set the custom theme so.set_theme( style="whitegrid", rc={ 'axes.facecolor': 'white', 'axes.edgecolor': 'slategray', ...
simplelr_Docs
[ { "content": "Question:\n### Advanced Data Visualization with Seaborn\n\n**Objective:** \nDemonstrate your understanding of advanced plotting and customization using the Seaborn `objects` interface.\n\n**Task:**\n\nUsing the `anscombe` dataset from Seaborn, perform the following tasks:\n\n1. **Load the Data:** ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8336, "level": 1, "question": "### Advanced Data Visualization with Seaborn\n\n**Objective:** \nDemonstrate your understanding of advanced plotting and customization using the Seaborn `objects` interface.\n\n**Task:**\n\nUsing the `anscombe` dataset from Seaborn, perform the followi...
def word_frequency_sort(words: list) -> list: if not words: return [] frequency = {} for word in words: if word in frequency: frequency[word] += 1 else: frequency[word] = 1 freq_list = list(frequency.items()) sorted_list = sorted(freq_list, k...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are given a list of strings where each string is a word. Implement a function that performs a word frequency analysis on the list and then sorts the results by the frequency of the words in descending order. If two words have the same frequency, they should ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8337, "level": 1, "question": "### Problem Statement\n\nYou are given a list of strings where each string is a word. Implement a function that performs a word frequency analysis on the list and then sorts the results by the frequency of the words in descending order. If two words ha...
def longest_consecutive_sequence(nums): if not nums: return [] num_set = set(nums) max_length = 0 result = [] for num in nums: current_num = num current_sequence = [current_num] next_num = current_num + 1 while next_num in num_set: current_sequence...
simplelr_Taco
[ { "content": "Question:\nGiven a list of integers, find and return the longest consecutive sequence of integers within the list. The sequence does not need to be contiguous in the input list but must appear in ascending order. If there are multiple sequences of the same maximum length, return the sequence which...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8338, "level": 1, "question": "Given a list of integers, find and return the longest consecutive sequence of integers within the list. The sequence does not need to be contiguous in the input list but must appear in ascending order. If there are multiple sequences of the same maximu...
def rotate_array(arr, k): n = len(arr) if n == 0 or k == 0: return list(arr) effective_k = k % n if effective_k == 0: return list(arr) return arr[-effective_k:] + arr[:-effective_k]
simplelr_Prefill
[ { "content": "Question:\nWrite a function to rotate an array to the right by k positions. The function should return the rotated array. If k is greater than the length of the array, the function should handle this by considering the effective rotations which is the remainder of k divided by the array length.\nA...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8339, "level": 1, "question": "Write a function to rotate an array to the right by k positions. The function should return the rotated array. If k is greater than the length of the array, the function should handle this by considering the effective rotations which is the remainder o...
def calculate_discounted_prices(original_prices: list, discount_percentages: list) -> list: discounted_prices = [] for price, discount in zip(original_prices, discount_percentages): discounted_price = price * (1 - discount / 100) discounted_prices.append(discounted_price) return discounted_p...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nAn e-commerce platform needs to automate the calculation of discount prices for products during a flash sale. The platform provides a list of original prices for the products and a corresponding list of discount percentages. The task is t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8340, "level": 1, "question": "### Coding Assessment Question\n\n#### Scenario\nAn e-commerce platform needs to automate the calculation of discount prices for products during a flash sale. The platform provides a list of original prices for the products and a corresponding list of ...
from typing import List def most_frequent_element(elements: List[int]) -> int: if not elements: return None frequency = {} max_count = 0 result = None for num in elements: if num in frequency: frequency[num] += 1 else: frequency[num] = 1 ...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Question: Most Frequent Element\n\n#### Scenario\nYou are developing an e-commerce application where you need to analyze customer behaviors based on their activity logs. One of the tasks involves identifying the most frequently visited product on the website.\n\n#### Problem\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8341, "level": 1, "question": "### Coding Question: Most Frequent Element\n\n#### Scenario\nYou are developing an e-commerce application where you need to analyze customer behaviors based on their activity logs. One of the tasks involves identifying the most frequently visited produ...
def largest_rectangle_area(heights): n = len(heights) if n == 0: return 0 left = [-1] * n stack = [] for i in range(n): while stack and heights[stack[-1]] >= heights[i]: stack.pop() if stack: left[i] = stack[-1] else: left[i] =...
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers where each element represents the height of a histogram bar, write a function to compute the largest rectangular area possible in the histogram.\n\nFor example, given the histogram represented by the array [2, 1, 5, 6, 2, 3], the function should return 10. The...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8342, "level": 1, "question": "Given an array of integers where each element represents the height of a histogram bar, write a function to compute the largest rectangular area possible in the histogram.\n\nFor example, given the histogram represented by the array [2, 1, 5, 6, 2, 3],...
def minimum_deletions_palindrome(s): n = len(s) # Create a 2D table with all elements initialized to 0 dp = [[0] * n for _ in range(n)] # All substrings of length 1 are palindromes of length 1 for i in range(n): dp[i][i] = 1 # Fill the table for substrings of length 2 to n ...
simplelr_Code_Contests
[ { "content": "Question:\nWrite a function **minimum_deletions_palindrome(s)** that returns the minimum number of character deletions required to make a given string a palindrome.\n\nA palindrome is a string that reads the same backward as forward. For instance, \"racecar\" is a palindrome, but \"race\" is not.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8343, "level": 1, "question": "Write a function **minimum_deletions_palindrome(s)** that returns the minimum number of character deletions required to make a given string a palindrome.\n\nA palindrome is a string that reads the same backward as forward. For instance, \"racecar\" is ...
def find_needle_in_haystack(haystack: str, needle: str) -> int: m = len(needle) n = len(haystack) if m == 0: return 0 if m > n: return -1 # Compute the Longest Prefix Suffix (LPS) array for the needle lps = [0] * m length = 0 # length of the previous longest prefix...
simplelr_Data_Structure
[ { "content": "Question:\nYou are tasked with implementing a more efficient substrings search algorithm that makes use of preprocessing to reduce the number of comparisons. Implement the Knuth-Morris-Pratt (KMP) algorithm to perform substring search.\n\n#### Objective:\nWrite a function `find_needle_in_haystack(...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8344, "level": 1, "question": "You are tasked with implementing a more efficient substrings search algorithm that makes use of preprocessing to reduce the number of comparisons. Implement the Knuth-Morris-Pratt (KMP) algorithm to perform substring search.\n\n#### Objective:\nWrite a...
def main(): from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score # Step 1: Load the data mice = fetch_ope...
simplelr_Docs
[ { "content": "Question:\n**Objective**: Demonstrate your understanding of loading datasets from openml.org, preprocessing the data, and using it for a simple classification task.\n\n**Question**:\n\nYou are required to perform the following tasks using scikit-learn and its datasets module:\n\n1. **Load the Data...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8345, "level": 1, "question": "**Objective**: Demonstrate your understanding of loading datasets from openml.org, preprocessing the data, and using it for a simple classification task.\n\n**Question**:\n\nYou are required to perform the following tasks using scikit-learn and its dat...
import sys def TemperatureStatistics(temperatures: list, k: int) -> list: if k <= 0: sys.exit("Invalid window size. Window size must be a positive integer.") if len(temperatures) < k: sys.exit('The length of temperatures list is less than the window size.') result = [] n = len(temp...
simplelr_Package
[ { "content": "Question:\nWrite a function named `TemperatureStatistics` that takes a list of integers representing daily temperatures and an integer `k`, representing a specific window size. The function should return a list of tuples, where each tuple contains three values: the minimum temperature, maximum tem...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8346, "level": 1, "question": "Write a function named `TemperatureStatistics` that takes a list of integers representing daily temperatures and an integer `k`, representing a specific window size. The function should return a list of tuples, where each tuple contains three values: t...
def combine_dicts(dict1, dict2): result = {} keys = set(dict1.keys()).union(set(dict2.keys())) for key in keys: val1 = dict1.get(key, 0) val2 = dict2.get(key, 0) result[key] = val1 + val2 return result
simplelr_Apps
[ { "content": "Question:\nWrite a function combine_dicts(dict1, dict2) that takes two dictionaries as input and returns a new dictionary that contains all the keys from both dictionaries. If a key is present in both dictionaries, the value in the new dictionary should be the sum of the values from the input dict...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8347, "level": 1, "question": "Write a function combine_dicts(dict1, dict2) that takes two dictionaries as input and returns a new dictionary that contains all the keys from both dictionaries. If a key is present in both dictionaries, the value in the new dictionary should be the su...
def sum_of_string_numbers(lst): return sum(int(s) for s in lst)
simplelr_Filter
[ { "content": "Question:\nGiven a list of strings that represent numbers, write a Python function to convert each string into an integer and calculate the sum of all the numbers. The function should return the sum.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8348, "level": 1, "question": "Given a list of strings that represent numbers, write a Python function to convert each string into an integer and calculate the sum of all the numbers. The function should return the sum.", "split": "train" }
def int_to_roman(num: int) -> str: units_roman = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'] tens_roman = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'] hundreds_roman = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'] thousands = num // 1000 remainder...
simplelr_Data_Structure
[ { "content": "Question:\nRoman Numeral Conversion\n\nYou are to write a function that converts a given integer into its corresponding Roman numeral representation. \n\n**Function Signature**:\n```python\ndef int_to_roman(num: int) -> str:\n```\n**Constraints**:\n- The input integer will be in the range from 1 t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8349, "level": 1, "question": "Roman Numeral Conversion\n\nYou are to write a function that converts a given integer into its corresponding Roman numeral representation. \n\n**Function Signature**:\n```python\ndef int_to_roman(num: int) -> str:\n```\n**Constraints**:\n- The input in...
def convert_time(minutes): hours = minutes // 60 mins = minutes % 60 return f"{hours} hour(s) and {mins} minute(s)"
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a positive integer representing the number of minutes and returns the equivalent time in hours and minutes in the format \"X hour(s) and Y minute(s)\".\n\nFor example:\n\n```python\nconvert_time(130) == \"2 hour(s) and 10 minute(s)\"\nconvert_time(45) == \"0 ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8350, "level": 1, "question": "Write a function that takes a positive integer representing the number of minutes and returns the equivalent time in hours and minutes in the format \"X hour(s) and Y minute(s)\".\n\nFor example:\n\n```python\nconvert_time(130) == \"2 hour(s) and 10 mi...
def extract_divisible_by_3_and_5(lst): return list(map(str, filter(lambda x: isinstance(x, int) and x % 15 == 0, lst)))
simplelr_Filter
[ { "content": "Question:\nWrite a function using python map and lambda to extract elements divisible by 3 and 5 from a given list, but the function also must handle input lists that may contain non-integer data types by ignoring them. Function should return a list of integers divisible by 3 and 5, where each int...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8351, "level": 1, "question": "Write a function using python map and lambda to extract elements divisible by 3 and 5 from a given list, but the function also must handle input lists that may contain non-integer data types by ignoring them. Function should return a list of integers d...
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:\nWrite a Python function `count_letters` that takes a string as input and returns a dictionary with the count of each letter in the string. The function should ignore case, treating uppercase and lowercase letters as the same. Additionally, the function should ignore any non-letter chara...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8352, "level": 1, "question": "Write a Python function `count_letters` that takes a string as input and returns a dictionary with the count of each letter in the string. The function should ignore case, treating uppercase and lowercase letters as the same. Additionally, the function...
def find_largest(lst): if len(lst) == 1: return lst[0] else: return max(lst[0], find_largest(lst[1:])) # Example usage numbers = [5, 3, 8, 2, 9] print("Largest number in the list:", find_largest(numbers))
simplelr_Filter
[ { "content": "Question:\nWrite a Python program to find the largest number in a list of numbers using a recursive function.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8353, "level": 1, "question": "Write a Python program to find the largest number in a list of numbers using a recursive function.", "split": "train" }
def count_unique_balanced_substrings(s): count_map = {0: 1} current_sum = 0 result = 0 for c in s: current_sum += 1 if c == '1' else -1 result += count_map.get(current_sum, 0) count_map[current_sum] = count_map.get(current_sum, 0) + 1 return result
simplelr_Leetcode
[ { "content": "Question:\nConsider a string `s` consisting of only the characters '0' and '1'. A substring of `s` is called a \"balanced substring\" if it contains an equal number of '0's and '1's. Your task is to count the number of unique balanced substrings of `s`. Return the total count of such unique balanc...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8354, "level": 1, "question": "Consider a string `s` consisting of only the characters '0' and '1'. A substring of `s` is called a \"balanced substring\" if it contains an equal number of '0's and '1's. Your task is to count the number of unique balanced substrings of `s`. Return th...
import sunau def double_sample_rate(input_filename: str, output_filename: str) -> None: with sunau.open(input_filename, 'r') as input_file: num_channels = input_file.getnchannels() sampwidth = input_file.getsampwidth() framerate = input_file.getframerate() num_frames = input_file.ge...
simplelr_Docs
[ { "content": "Question:\n**Question:**\n\nYou are given an audio file in Sun AU format. Your task is to write a Python function that reads this audio file, doubles its sample rate, and saves the modified audio to a new Sun AU file.\n\n### Requirements:\n1. **Function Signature:**\n ```python\n def double_...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8355, "level": 1, "question": "**Question:**\n\nYou are given an audio file in Sun AU format. Your task is to write a Python function that reads this audio file, doubles its sample rate, and saves the modified audio to a new Sun AU file.\n\n### Requirements:\n1. **Function Signature...
import datetime def manipulate_datetime(datetime_params, time_params): # Create a datetime object using the provided datetime parameters dt = datetime.datetime(*datetime_params) # Extract components from the datetime object datetime_tuple = ( dt.year, dt.month, dt.day, ...
simplelr_Docs
[ { "content": "Question:\n### Python Datetime C API Implementation\n\nYou are required to implement a Python function that utilizes the C API macros provided by Python's datetime module to manipulate datetime objects. Your task is to:\n\n1. **Create** a new datetime object with a specified date and time.\n2. **E...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8356, "level": 1, "question": "### Python Datetime C API Implementation\n\nYou are required to implement a Python function that utilizes the C API macros provided by Python's datetime module to manipulate datetime objects. Your task is to:\n\n1. **Create** a new datetime object with...
import heapq from collections import Counter def rearrangeString(s, k): if k == 0: return s freq = Counter(s) max_count = max(freq.values()) if (max_count - 1) * k + 1 > len(s): return "" heap = [(-v, char) for char, v in freq.items()] heapq.heapify(heap) waiting = [] re...
simplelr_Apps
[ { "content": "Question:\nGiven a string `s` and an integer `k`, write a function `rearrangeString(s, k)` that rearranges the characters of `s` such that the same characters are at least `k` distance apart. If it is not possible to rearrange the string, return an empty string `\"\"`.\n\n### Input:\n- `s`: a stri...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8357, "level": 1, "question": "Given a string `s` and an integer `k`, write a function `rearrangeString(s, k)` that rearranges the characters of `s` such that the same characters are at least `k` distance apart. If it is not possible to rearrange the string, return an empty string `...
def min_distance(word1: str, word2: str) -> int: m = len(word1) n = len(word2) dp = [[0 for _ in range(n+1)] for __ in range(m+1)] for i in range(m+1): for j in range(n+1): if i == 0: dp[i][j] = j elif j == 0: dp[i][j] = i ...
simplelr_Taco
[ { "content": "Question:\nBuild an application that will determine the minimum number of modifications required to transform one string into another string using the following operations: insertion, deletion, or substitution of a single character. \n\n### Function Signature\n```python\ndef min_distance(word1: st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8358, "level": 1, "question": "Build an application that will determine the minimum number of modifications required to transform one string into another string using the following operations: insertion, deletion, or substitution of a single character. \n\n### Function Signature\n``...
def custom_shell_sort(arr): '''Sorts an array using Shell Sort with a custom gap sequence [9, 5, 3, 1].''' arr = arr.copy() gaps = [9, 5, 3, 1] for gap in gaps: for i in range(gap, len(arr)): j = i while j >= gap and arr[j] < arr[j - gap]: arr[j], arr[j - ...
simplelr_Data_Structure
[ { "content": "Question:\nShell Sort with Custom Gap Sequence\n\nYou are required to implement the Shell Sort algorithm with a custom gap sequence. This task will assess your understanding of adaptive sorting algorithms and how variations in implementation can affect performance.\n\n### Question\n\n**Objective**...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8359, "level": 1, "question": "Shell Sort with Custom Gap Sequence\n\nYou are required to implement the Shell Sort algorithm with a custom gap sequence. This task will assess your understanding of adaptive sorting algorithms and how variations in implementation can affect performanc...
import math def sum_of_multiples(n): if n < 1: return 0 k = int(math.floor(n)) m3 = k // 3 sum3 = 3 * m3 * (m3 + 1) // 2 m5 = k // 5 sum5 = 5 * m5 * (m5 + 1) // 2 m15 = k // 15 sum15 = 15 * m15 * (m15 + 1) // 2 total = sum3 + sum5 - sum15 return total
simplelr_Prefill
[ { "content": "Question:\nWrite a function to return the sum of numbers from 1 to a given number n, but only include numbers that are multiples of either 3 or 5. If the number n is less than 1, the function should return 0.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8360, "level": 1, "question": "Write a function to return the sum of numbers from 1 to a given number n, but only include numbers that are multiples of either 3 or 5. If the number n is less than 1, the function should return 0.", "split": "train" }
import math def count_digits(n: int) -> int: if n == 0: return 1 n_abs = abs(n) return math.floor(math.log10(n_abs)) + 1
simplelr_Data_Structure
[ { "content": "Question:\n#### Context:\nAs part of a number processing system, you need to accurately determine the number of digits in various integers. Your task is to implement a function that computes the number of digits in an integer with efficient time and space complexity.\n\n#### Problem Statement:\nIm...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8361, "level": 1, "question": "#### Context:\nAs part of a number processing system, you need to accurately determine the number of digits in various integers. Your task is to implement a function that computes the number of digits in an integer with efficient time and space complex...
def remove_consecutive_duplicates(lst): if not lst: return [] result = [lst[0]] for num in lst[1:]: if num != result[-1]: result.append(num) return result
simplelr_Apps
[ { "content": "Question:\nYour task is to write a function that takes a list of integers and returns a list of the same integers but without any consecutive duplicates. The function should preserve the original order of elements.\n\nExample\n-----\n\n`input: [1, 2, 2, 3, 3, 3, 4, 4, 5]`\n\n`output: [1, 2, 3, 4, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8362, "level": 1, "question": "Your task is to write a function that takes a list of integers and returns a list of the same integers but without any consecutive duplicates. The function should preserve the original order of elements.\n\nExample\n-----\n\n`input: [1, 2, 2, 3, 3, 3, ...
def reverse_string(s): if not isinstance(s, str): return None reversed_s = '' for c in s: reversed_s = c + reversed_s return reversed_s
simplelr_Prefill
[ { "content": "Question:\nWrite a function to reverse a string in Python without using any built-in functions or slicing methods. Additionally, ensure that the function handles exceptions by returning `None` if the input is not a string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8363, "level": 1, "question": "Write a function to reverse a string in Python without using any built-in functions or slicing methods. Additionally, ensure that the function handles exceptions by returning `None` if the input is not a string.", "split": "train" }
def min_jumps(arr): n = len(arr) if n == 1: return 0 current_end = 0 next_end = 0 jumps = 0 for i in range(n): if i > current_end: return -1 next_end = max(next_end, i + arr[i]) if i == current_end: jumps += 1 current_...
simplelr_Code_Contests
[ { "content": "Question:\nGiven a list of `N` integers, where each integer represents the maximum number of steps you can jump forward from that position. Your goal is to determine the minimum number of jumps required to reach the end of the list from the start. You are initially positioned at the first index (p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8364, "level": 1, "question": "Given a list of `N` integers, where each integer represents the maximum number of steps you can jump forward from that position. Your goal is to determine the minimum number of jumps required to reach the end of the list from the start. You are initial...
def convert_temperature(value: float, from_unit: str, to_unit: str) -> float: if from_unit == to_unit: return round(value, 2) elif from_unit == 'F': if to_unit == 'C': converted_value = (value - 32) * 5 / 9 else: # to Kelvin converted_value = (value - 32) * 5 / 9...
simplelr_Apps
[ { "content": "Question:\nYou are working on a temperature conversion application that allows users to convert temperatures between Fahrenheit, Celsius, and Kelvin. Your task is to complete the `convert_temperature` function which should take three arguments: the original temperature value, the original temperat...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8365, "level": 1, "question": "You are working on a temperature conversion application that allows users to convert temperatures between Fahrenheit, Celsius, and Kelvin. Your task is to complete the `convert_temperature` function which should take three arguments: the original tempe...
def find_first_occurrence(matrix, target): for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] == target: return (i, j) return None # Example usage: matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 1], [3, 1, 1, 5] ] print(find_first...
simplelr_Filter
[ { "content": "Question:\nI have a Matrix with multiple rows and columns, and I need to find the first occurrence of a specific value in that matrix.\nThe matrix looks like this:\n```python\nmatrix = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 0, 0, 1],\n [3, 1, 1, 5]\n]\n```\nLet's say I want to find th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8366, "level": 1, "question": "I have a Matrix with multiple rows and columns, and I need to find the first occurrence of a specific value in that matrix.\nThe matrix looks like this:\n```python\nmatrix = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 0, 0, 1],\n [3, 1, 1, 5]\n...
def find_first_duplicate(nums): seen = set() for num in nums: if num in seen: return num seen.add(num) return None # Test cases assert find_first_duplicate([2, 1, 3, 5, 3, 2]) == 3, "Test case 1 failed" assert find_first_duplicate([1, 2, 3, 4]) is None, "Test case 2 failed" asse...
simplelr_Filter
[ { "content": "Question:\nI'll provide you with a problem, and I want you to create a Python function to solve it. The problem is:\n\nGiven a list of integers as input, find the first duplicate in the list. A duplicate is an element that appears more than once in the list.\n\nFor example, given the list [2, 1, 3...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8367, "level": 1, "question": "I'll provide you with a problem, and I want you to create a Python function to solve it. The problem is:\n\nGiven a list of integers as input, find the first duplicate in the list. A duplicate is an element that appears more than once in the list.\n\nF...
import collections def findOrder(numCourses, prerequisites): adj = [[] for _ in range(numCourses)] in_degree = [0] * numCourses for course, prereq in prerequisites: adj[prereq].append(course) in_degree[course] += 1 queue = collections.deque() for i in range(numCourses): if i...
simplelr_Leetcode
[ { "content": "Question:\nIn a university, students participate in various courses, and each course has a set of prerequisites. Given the number of courses `numCourses` and a list of prerequisites where `prerequisites[i] = [ai, bi]` indicates that to enroll in course `ai`, a student must have completed course `b...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8368, "level": 1, "question": "In a university, students participate in various courses, and each course has a set of prerequisites. Given the number of courses `numCourses` and a list of prerequisites where `prerequisites[i] = [ai, bi]` indicates that to enroll in course `ai`, a st...
import json def read_json_file(file_path): with open(file_path, 'r') as file: data = json.load(file) return data
simplelr_Filter
[ { "content": "Question:\nCan you generate a Python function that can read a JSON file and return its content as a dictionary? Also, can you add a small example of how to use this function?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8369, "level": 1, "question": "Can you generate a Python function that can read a JSON file and return its content as a dictionary? Also, can you add a small example of how to use this function?", "split": "train" }
def move_every_5th_to_end(lst): new_list = [] move_list = [] for index, item in enumerate(lst): if (index + 1) % 5 == 0: move_list.append(item) else: new_list.append(item) return new_list + move_list
simplelr_Filter
[ { "content": "Question:\nI have a long list of items, and I need to move every 5th item to the end of the list, and I want to preserve the order of the other items. Is there a way to do this with Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8370, "level": 1, "question": "I have a long list of items, and I need to move every 5th item to the end of the list, and I want to preserve the order of the other items. Is there a way to do this with Python?", "split": "train" }
def longest_unique_substring(s): char_index = {} max_length = 0 left = 0 for right in range(len(s)): char = s[right] if char in char_index and char_index[char] >= left: left = char_index[char] + 1 char_index[char] = right current_length = right - left + 1 ...
simplelr_Evol
[ { "content": "Question:\nDevelop a function that computes the longest sequence of unique characters in a given string. The function should return the length of this sequence. Use a sliding window approach to optimize the function's performance. \n\ndef longest_unique_substring(s):\n \"\"\"\n Calculate the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8371, "level": 1, "question": "Develop a function that computes the longest sequence of unique characters in a given string. The function should return the length of this sequence. Use a sliding window approach to optimize the function's performance. \n\ndef longest_unique_substring...
def robot_return_to_origin(s): x, y = 0, 0 for c in s: if c == 'U': y += 1 elif c == 'D': y -= 1 elif c == 'L': x -= 1 elif c == 'R': x += 1 return x == 0 and y == 0
simplelr_Code_Contests
[ { "content": "Question:\nA robot is situated in a 2D grid at position (0, 0). The robot can receive a sequence of commands where each command instructs the robot to move one unit step in a specific direction: 'U' for up, 'D' for down, 'L' for left, and 'R' for right. \n\nYour task is to determine whether the ro...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8372, "level": 1, "question": "A robot is situated in a 2D grid at position (0, 0). The robot can receive a sequence of commands where each command instructs the robot to move one unit step in a specific direction: 'U' for up, 'D' for down, 'L' for left, and 'R' for right. \n\nYour ...
from typing import List def find_missing_number(nums: List[int]) -> int: n = len(nums) sum_nums = sum(nums) expected_sum = n * (n + 1) // 2 return expected_sum - sum_nums
simplelr_Data_Structure
[ { "content": "Question:\n### Missing Number Finder\n\n#### Problem Description:\nYou are tasked with writing a function that determines the missing number in a list of unique integers within the range `[0..n]`. The list contains `n` unique integers, and you need to identify the single missing number.\n\n#### In...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8373, "level": 1, "question": "### Missing Number Finder\n\n#### Problem Description:\nYou are tasked with writing a function that determines the missing number in a list of unique integers within the range `[0..n]`. The list contains `n` unique integers, and you need to identify th...
def are_synonyms(synonym_pairs, word1, word2): """ Determines if two words are synonyms based on given synonym pairs. :param synonym_pairs: List of tuples, where each tuple contains two words that are synonyms. :param word1: A string representing the first word. :param word2: A string representing t...
simplelr_Package
[ { "content": "Question:\nGiven a dataset of unique word pairs representing synonyms, your task is to write a function that checks if two given words are synonyms of each other, directly or indirectly. Two words are considered synonymous if:\n1. They are directly listed as pairs in the dataset.\n2. They share a ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8374, "level": 1, "question": "Given a dataset of unique word pairs representing synonyms, your task is to write a function that checks if two given words are synonyms of each other, directly or indirectly. Two words are considered synonymous if:\n1. They are directly listed as pair...
def nextGreaterElement(nums1, nums2): stack = [] next_greater = {} for num in reversed(nums2): while stack and stack[-1] < num: stack.pop() if stack: next_greater[num] = stack[-1] else: next_greater[num] = -1 stack.append(num) result = ...
simplelr_Leetcode
[ { "content": "Question:\nWrite a function `nextGreaterElement(nums1, nums2)` where `nums1` and `nums2` are arrays without duplicates, and `nums1` is a subset of `nums2`. The function finds all the next greater numbers for `nums1`'s elements in the corresponding places of `nums2`.\n\nThe next greater number of a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8375, "level": 1, "question": "Write a function `nextGreaterElement(nums1, nums2)` where `nums1` and `nums2` are arrays without duplicates, and `nums1` is a subset of `nums2`. The function finds all the next greater numbers for `nums1`'s elements in the corresponding places of `nums...
def sortStudents(heights): students = list(enumerate(heights)) # Create tuples of (index, height) students.sort(key=lambda x: (x[1], x[0])) # Sort by height, then by original index return [h for idx, h in students]
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `heights` representing the heights of students in a line, sort the students by their heights in non-decreasing order. However, there is a special requirement: each student maintains their relative order from the initial list even if their heights are the same. Imp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8376, "level": 1, "question": "Given an integer array `heights` representing the heights of students in a line, sort the students by their heights in non-decreasing order. However, there is a special requirement: each student maintains their relative order from the initial list even...
def max_candies(grid: list[list[int]]) -> int: n = len(grid) dp = [[0 for _ in range(n)] for _ in range(n)] dp[0][0] = grid[0][0] # Fill the first row for j in range(1, n): dp[0][j] = dp[0][j-1] + grid[0][j] # Fill the first column for i in range(1, n): dp[i][0...
simplelr_Code_Contests
[ { "content": "Question:\nYou are given a grid of size NxN with each cell containing a positive integer representing the number of candies at that position. You start from the top-left cell (1, 1) and you want to reach the bottom-right cell (N, N). From any cell, you can only move to the cell directly right or d...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8377, "level": 1, "question": "You are given a grid of size NxN with each cell containing a positive integer representing the number of candies at that position. You start from the top-left cell (1, 1) and you want to reach the bottom-right cell (N, N). From any cell, you can only m...
def modulo(a, b): if b == 0: raise ZeroDivisionError("division by zero") return a - (a // b) * b
simplelr_Filter
[ { "content": "Question:\nHow can we implement a function to perform modulo between two numbers in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8378, "level": 1, "question": "How can we implement a function to perform modulo between two numbers in Python?", "split": "train" }
import struct def transform_binary_data(binary_data: bytes, format: str, encode_index: int) -> bytes: unpacked = struct.unpack(format, binary_data) component = unpacked[encode_index] # Decode the bytes to a string assuming it's UTF-8 encoded decoded_str = component.decode('utf-8') # Encode the stri...
simplelr_Docs
[ { "content": "Question:\n### Question: Handling and Transforming Binary Data\n\nGiven your knowledge of Python’s `struct` and `codecs` modules as described in the documentation, write a Python function that:\n\n1. Takes a binary string representing multiple fields packed in a specific structure.\n2. Unpacks the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8379, "level": 1, "question": "### Question: Handling and Transforming Binary Data\n\nGiven your knowledge of Python’s `struct` and `codecs` modules as described in the documentation, write a Python function that:\n\n1. Takes a binary string representing multiple fields packed in a ...
def calculate_run_length_encoding(input_string: str) -> str: if not input_string: return "" result = [] current_char = input_string[0] count = 1 for char in input_string[1:]: if char == current_char: count += 1 else: result.append(f"{current_...
simplelr_Taco
[ { "content": "Question:\nYour task is to write a Python function called `calculate_run_length_encoding` that takes a string as input and returns a compressed representation of the string using run-length encoding.\n\nRun-length encoding is a basic form of data compression where consecutive occurrences of the sa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8380, "level": 1, "question": "Your task is to write a Python function called `calculate_run_length_encoding` that takes a string as input and returns a compressed representation of the string using run-length encoding.\n\nRun-length encoding is a basic form of data compression wher...
def sum_of_odds(n): total = 0 for i in range(1, n + 1): if i % 2 != 0: total += i return total
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a number as an argument and returns the sum of all odd numbers from 1 to that number using a loop.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8381, "level": 1, "question": "Create a function that takes a number as an argument and returns the sum of all odd numbers from 1 to that number using a loop.", "split": "train" }
from collections import Counter def find_most_frequent(lst): freq = Counter(lst) max_freq = None most_freq_num = None for num, count in freq.items(): if max_freq is None: max_freq = count most_freq_num = num else: if count > max_freq: ...
simplelr_Apps
[ { "content": "Question:\nWrite a function `find_most_frequent` that takes a list of integers and returns the integer that appears most frequently in the list. If there are multiple numbers with the same highest frequency, return the smallest number among them. Assume that the input list is non-empty and contain...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8382, "level": 1, "question": "Write a function `find_most_frequent` that takes a list of integers and returns the integer that appears most frequently in the list. If there are multiple numbers with the same highest frequency, return the smallest number among them. Assume that the ...
def cosine_similarity(vec1: list, vec2: list) -> float: if len(vec1) != len(vec2): raise ValueError("Vectors must be of the same length.") dot_product = sum(x * y for x, y in zip(vec1, vec2)) mag1 = sum(x ** 2 for x in vec1) ** 0.5 mag2 = sum(x ** 2 for x in vec2) ** 0.5 denom...
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario\n\nIn machine learning, especially in text analysis or recommendation systems, one often needs to determine the similarity between entities represented as vectors. One of the most commonly used similarity measures is **cosine similarity**.\n\n### Problem Statement\n\nGiven ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8383, "level": 1, "question": "### Scenario\n\nIn machine learning, especially in text analysis or recommendation systems, one often needs to determine the similarity between entities represented as vectors. One of the most commonly used similarity measures is **cosine similarity**....
def sort_sentence_by_word_length(sentence): return ' '.join(sorted(sentence.split(), key=lambda x: len(x)))
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `sentence` which consists of words separated by single spaces, with no leading or trailing spaces. Each word in the `sentence` has a unique length. Return the words of the `sentence` sorted in ascending order of their lengths. If two words have the same length, th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8384, "level": 1, "question": "You are given a string `sentence` which consists of words separated by single spaces, with no leading or trailing spaces. Each word in the `sentence` has a unique length. Return the words of the `sentence` sorted in ascending order of their lengths. If...
from typing import List def next_greater_elements(nums: List[int]) -> List[int]: stack = [] res = [] for num in reversed(nums): while stack and stack[-1] <= num: stack.pop() if not stack: res.append(-1) else: res.append(stack[-1]) stack.ap...
simplelr_Algorithm
[ { "content": "Question:\n### Question: Find the Next Greater Element\n\nGiven an array of integers, write a function to find the next greater element for each element in the array. The next greater element for an element x is the first greater element to the right of x in the array. If no such element exists, r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8385, "level": 1, "question": "### Question: Find the Next Greater Element\n\nGiven an array of integers, write a function to find the next greater element for each element in the array. The next greater element for an element x is the first greater element to the right of x in the ...
import numpy as np def euclidean_distance(X, Y): return np.linalg.norm(X - Y, axis=1)
simplelr_Filter
[ { "content": "Question:\nDesign a Python function to calculate the Euclidean distance between points in two 2D arrays, `X` and `Y`. Each array contains `n` points, with `X` being of shape (n, p) and `Y` also of shape (n, p), where each row represents a point in a p-dimensional space. The function should return ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8386, "level": 1, "question": "Design a Python function to calculate the Euclidean distance between points in two 2D arrays, `X` and `Y`. Each array contains `n` points, with `X` being of shape (n, p) and `Y` also of shape (n, p), where each row represents a point in a p-dimensional...
from collections import Counter import heapq def top_k_frequent(nums, k): count = Counter(nums) return heapq.nlargest(k, count, key=lambda x: count[x])
simplelr_Filter
[ { "content": "Question:\nThe following problem was presented to me during a coding interview. Unfortunately, I struggled to solve it and the interviewer moved on without providing feedback.\n\n**Problem:**\n\nGiven an array of integers `nums` and an integer `k`, return the `k` most frequent elements. You may re...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8387, "level": 1, "question": "The following problem was presented to me during a coding interview. Unfortunately, I struggled to solve it and the interviewer moved on without providing feedback.\n\n**Problem:**\n\nGiven an array of integers `nums` and an integer `k`, return the `k`...
def reverse(x): sign = 1 if x < 0: sign = -1 x = -x max_int = 2**31 - 1 reversed_num = 0 while x > 0: digit = x % 10 x = x // 10 if reversed_num > (max_int - digit) // 10: return 0 reversed_num = reversed_num * 10 + digit if sign == -1:...
simplelr_Leetcode
[ { "content": "Question:\nGiven a signed 32-bit integer `x`, return `x` with its digits reversed. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-2^31, 2^31 - 1]`, then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).\n\nFor exa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8388, "level": 1, "question": "Given a signed 32-bit integer `x`, return `x` with its digits reversed. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-2^31, 2^31 - 1]`, then return 0. Assume the environment does not allow you to store 64-bit intege...
def advanced_two_sum(numbers, target): left = 0 right = len(numbers) - 1 while left < right: # Skip non-integer elements on the left while left < right and not (isinstance(numbers[left], int) or (isinstance(numbers[left], float) and numbers[left].is_integer())): left += 1 ...
simplelr_Data_Structure
[ { "content": "Question:\n### Question: Advanced Two Sum - Special Cases Handling\n\nGiven an array of integers sorted in ascending order, find two indices of numbers such that they add up to a specific target number. The function `advanced_two_sum` should ensure that no element is used more than once, and it sh...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8389, "level": 1, "question": "### Question: Advanced Two Sum - Special Cases Handling\n\nGiven an array of integers sorted in ascending order, find two indices of numbers such that they add up to a specific target number. The function `advanced_two_sum` should ensure that no elemen...
def largest_rectangle_area(heights: list[int]) -> int: stack = [-1] max_area = 0 for i in range(len(heights)): while stack[-1] != -1 and heights[i] < heights[stack[-1]]: popped = stack.pop() width = i - stack[-1] - 1 area = heights[popped] * width if a...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Challenge\n\n**Scenario**: You are given an array of integers, which represents the heights of buildings in a city, arranged in a row. Each element in the array is the height of a building. Your task is to find the area of the largest rectangle that can be formed by choosing ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8390, "level": 1, "question": "### Coding Challenge\n\n**Scenario**: You are given an array of integers, which represents the heights of buildings in a city, arranged in a row. Each element in the array is the height of a building. Your task is to find the area of the largest rectan...
def find_min(nums): left = 0 right = len(nums) - 1 while left < right: mid = (left + right) // 2 if nums[mid] > nums[right]: left = mid + 1 else: right = mid return nums[left]
simplelr_Evol
[ { "content": "Question:\nRotated Array Minimum\nDescription: Given an array `nums` that has been rotated at an unknown pivot (a rotation involves taking the elements from the front of the array and moving them to the back), find the minimum element in the array. The array was originally sorted in ascending orde...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8391, "level": 1, "question": "Rotated Array Minimum\nDescription: Given an array `nums` that has been rotated at an unknown pivot (a rotation involves taking the elements from the front of the array and moving them to the back), find the minimum element in the array. The array was ...
def trap(height): if not height: return 0 left = 0 right = len(height) - 1 max_left = 0 max_right = 0 result = 0 while left < right: if height[left] <= height[right]: if height[left] >= max_left: max_left = height[left] else: ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of non-negative integers representing the amount of rainwater trapped on top of walls of varying heights, where the width of each wall segment is 1. Calculate _the maximum amount of rainwater that can be trapped_ between the walls. The list represents an elevation m...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8392, "level": 1, "question": "You are given a list of non-negative integers representing the amount of rainwater trapped on top of walls of varying heights, where the width of each wall segment is 1. Calculate _the maximum amount of rainwater that can be trapped_ between the walls....
def sanitize_cart(prices): seen = set() result = [] for p in prices: if p >= 0 and p not in seen: result.append(p) seen.add(p) return result
simplelr_Code_Contests
[ { "content": "Question:\nAn e-commerce company hosts a shopping site where users can add items to their shopping cart. You are given a list of price tags (in cents) of items a user added to their cart. Unfortunately, due to a software bug, the prices of the items may be listed multiple times or even be negative...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8393, "level": 1, "question": "An e-commerce company hosts a shopping site where users can add items to their shopping cart. You are given a list of price tags (in cents) of items a user added to their cart. Unfortunately, due to a software bug, the prices of the items may be listed...
def find_max_subarray_sum(arr, k): current_sum = sum(arr[:k]) max_sum = current_sum for i in range(k, len(arr)): current_sum = current_sum - arr[i - k] + arr[i] if current_sum > max_sum: max_sum = current_sum return max_sum
simplelr_Package
[ { "content": "Question:\nWrite a function `find_max_subarray_sum(arr, k)` that finds the maximum sum of any subarray of length `k` in the given array `arr`. A subarray is defined as a contiguous sequence of elements within an array.\n\n**Function Specification:**\n\n- **Input:**\n - `arr`: A list of integers r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8394, "level": 1, "question": "Write a function `find_max_subarray_sum(arr, k)` that finds the maximum sum of any subarray of length `k` in the given array `arr`. A subarray is defined as a contiguous sequence of elements within an array.\n\n**Function Specification:**\n\n- **Input:...
def productExceptSelf(nums): n = len(nums) prefix = [1] * n for i in range(1, n): prefix[i] = prefix[i-1] * nums[i-1] suffix = [1] * n for i in range(n-2, -1, -1): suffix[i] = suffix[i+1] * nums[i+1] result = [prefix[i] * suffix[i] for i in range(n)] return result
simplelr_Taco
[ { "content": "Question:\nGiven a list of integers, return a new list such that each element at index i of the new list is the product of all the numbers in the original list except the one at i.\n\nExample 1:\nInput: nums = [1, 2, 3, 4]\nOutput: [24, 12, 8, 6]\nExplanation: Output at index 0 is 2 * 3 * 4 = 24, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8395, "level": 1, "question": "Given a list of integers, return a new list such that each element at index i of the new list is the product of all the numbers in the original list except the one at i.\n\nExample 1:\nInput: nums = [1, 2, 3, 4]\nOutput: [24, 12, 8, 6]\nExplanation: Ou...
def max_boxes_that_fit(arr, boxes): arr.sort() boxes.sort() i = j = count = 0 while i < len(arr) and j < len(boxes): if arr[i] >= boxes[j]: count += 1 i += 1 j += 1 else: i += 1 return count
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of integers `arr` representing the capacity of storage units in a warehouse. Additionally, you are provided an array `boxes`, where each element represents the size of a box that needs to be stored. You are required to place each box into a storage unit such that ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8396, "level": 1, "question": "You are given an array of integers `arr` representing the capacity of storage units in a warehouse. Additionally, you are provided an array `boxes`, where each element represents the size of a box that needs to be stored. You are required to place each...
def all_multiples_of(lst, number): if number == 0: return all(x == 0 for x in lst) return all(x % number == 0 for x in lst)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that checks if all the elements in a given list are multiples of a specific number.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8397, "level": 1, "question": "Create a function that checks if all the elements in a given list are multiples of a specific number.", "split": "train" }
def filter_and_sort_products(products, category): # Filter products by the given category filtered_products = [product for product in products if product['category'] == category] # Sort the filtered products by price in ascending order sorted_products = sorted(filtered_products, key=lambda x: x['price']...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of dictionaries, where each dictionary represents a product with keys like 'id', 'name', 'price', and 'category'. The function should filter products based on a given category and return a list of dictionaries containing only the products from t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8398, "level": 1, "question": "Write a Python function that takes a list of dictionaries, where each dictionary represents a product with keys like 'id', 'name', 'price', and 'category'. The function should filter products based on a given category and return a list of dictionaries ...
def bulls_and_cows(secret, guess): bulls = 0 for s, g in zip(secret, guess): if s == g: bulls += 1 secret_remaining = [] guess_remaining = [] for s, g in zip(secret, guess): if s != g: secret_remaining.append(s) guess_remaining.append(g) from...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to solve a simple version of the \"Bulls and Cows\" game. In this simplified version, the game is played with two-digit numbers. The function should take two strings as input: the secret number and the guess. It should return a tuple (Bulls, Cows) where Bulls rep...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8399, "level": 1, "question": "Write a python function to solve a simple version of the \"Bulls and Cows\" game. In this simplified version, the game is played with two-digit numbers. The function should take two strings as input: the secret number and the guess. It should return a ...