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 largest_sum_of_two_elements(nums): if len(nums) < 2: return -1 first_max = second_max = -1 for num in nums: if num > first_max: second_max = first_max first_max = num elif num > second_max: second_max = num return first_max + second_max
simplelr_Code_Contests
[ { "content": "Question:\nYou are given a list of non-negative integers. Write a function that returns the largest sum obtainable by summing exactly two distinct elements from the list. If there's fewer than two elements in the input list, return -1.\n\nExample\n\nInput\n[3, 5, 1, 9, 2]\n\nOutput\n14\n\nInput\n[...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6400, "level": 1, "question": "You are given a list of non-negative integers. Write a function that returns the largest sum obtainable by summing exactly two distinct elements from the list. If there's fewer than two elements in the input list, return -1.\n\nExample\n\nInput\n[3, 5,...
def concatenate_strings(string_list): return ''.join(string_list)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes as input a list of strings, concatenates all the strings, and returns the result. The function should handle cases where the list could be empty, and should return an empty string in such cases.\nAnswer:\nLet's think step by step.\n", "role": "user" } ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6401, "level": 1, "question": "Create a function that takes as input a list of strings, concatenates all the strings, and returns the result. The function should handle cases where the list could be empty, and should return an empty string in such cases.", "split": "train" }
def sum_of_odds(numbers: str) -> int: total = 0 for num_str in numbers.split(','): num = int(num_str) if num % 2 != 0: total += num return total
simplelr_Apps
[ { "content": "Question:\n# Kata Task\n\nYou are given a string representing a list of integers separated by commas, e.g., \"1,2,3,4\".\n\nWrite a function that finds the sum of the odd numbers in the list.\n\n**Function Signature**\n\nThe function should be named `sum_of_odds` and have the following signature:\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6402, "level": 1, "question": "# Kata Task\n\nYou are given a string representing a list of integers separated by commas, e.g., \"1,2,3,4\".\n\nWrite a function that finds the sum of the odd numbers in the list.\n\n**Function Signature**\n\nThe function should be named `sum_of_odds`...
def custom_sort(s): return ''.join(sorted(s, key=lambda c: (0, c) if c.isalpha() else (1, int(c)))) print(custom_sort("2a1b3c")) # Outputs: abc123
simplelr_Filter
[ { "content": "Question:\nConsider a string that contains a mix of alphabetic characters and numbers. Write a program to sort this string in a way that all the alphabetic characters come first in alphabetical order, followed by numbers in ascending order.\n\nHere is a sample string: \"2a1b3c\"\n\nThe sorted str...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6403, "level": 1, "question": "Consider a string that contains a mix of alphabetic characters and numbers. Write a program to sort this string in a way that all the alphabetic characters come first in alphabetical order, followed by numbers in ascending order.\n\nHere is a sample s...
def find_identical_adjacent_sequences(s): if len(s) < 2: return [] sequences = [] start = 0 for i in range(1, len(s)): if s[i] != s[i - 1]: if i - start >= 2: sequences.append((start, i - 1, s[start:i])) start = i if len(s) - start >= 2: ...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that identifies the positions of sequences of identical adjacent digits in a given string. The function should return a list of tuples, where each tuple contains the starting index, the ending index, and the sequence itself. If the string does not contain any seq...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6404, "level": 1, "question": "Write a Python function that identifies the positions of sequences of identical adjacent digits in a given string. The function should return a list of tuples, where each tuple contains the starting index, the ending index, and the sequence itself. If ...
def is_valid_ride(cars: str) -> bool: for i in range(len(cars) - 1): if cars[i] == cars[i + 1]: return False return True
simplelr_Code_Contests
[ { "content": "Question:\nA new amusement park ride features a line of cars connected in a straight line, resembling a train. Each car can either be facing forward or backward. The ride has a strict requirement that a ride cannot start if there are any adjacent cars facing the same direction, as they can only co...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6405, "level": 1, "question": "A new amusement park ride features a line of cars connected in a straight line, resembling a train. Each car can either be facing forward or backward. The ride has a strict requirement that a ride cannot start if there are any adjacent cars facing the ...
def has_alternating_bits(s): if len(s) <= 1: return True for i in range(len(s) - 1): if s[i] == s[i + 1]: return False return True
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check whether a binary string has alternating bits or not. A binary string has alternating bits if no two consecutive characters are the same.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6406, "level": 1, "question": "Write a python function to check whether a binary string has alternating bits or not. A binary string has alternating bits if no two consecutive characters are the same.", "split": "train" }
def longest_unique_substring(s): if not s: return 0 max_length = 1 current_length = 1 for i in range(1, len(s)): if s[i] == s[i-1]: current_length += 1 else: current_length = 1 if current_length > max_length: max_length = current_length...
simplelr_Taco
[ { "content": "Question:\nGiven a string `s` consisting of only 'a', 'b', and 'c', determine the length of the longest substring that contains no more than one unique character. For example:\n\n```python\nlongest_unique_substring('aaabbc') # Should return 3\nlongest_unique_substring('abaccc') # Should return 3\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6407, "level": 1, "question": "Given a string `s` consisting of only 'a', 'b', and 'c', determine the length of the longest substring that contains no more than one unique character. For example:\n\n```python\nlongest_unique_substring('aaabbc') # Should return 3\nlongest_unique_subs...
import json def parse_json_with_a_keys(json_str): # Parse the JSON string into a dictionary data = json.loads(json_str) # Filter the dictionary to include only keys starting with 'a' filtered_data = {key: value for key, value in data.items() if key.startswith('a')} return filtered_data #...
simplelr_Filter
[ { "content": "Question:\nWrite a python code to parse the given JSON into a dictionary, but only include the keys that start with the letter 'a'.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6408, "level": 1, "question": "Write a python code to parse the given JSON into a dictionary, but only include the keys that start with the letter 'a'.", "split": "train" }
def count_valleys(log): elevation = 0 valley_count = 0 for c in log: prev_elev = elevation if c == 'U': elevation += 1 elif c == 'D': elevation -= 1 # Check if this step ended a valley if elevation == 0 and prev_elev < 0: valley_cou...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `log` consisting of characters 'U' (uphill), 'D' (downhill), and '_' (flat terrain), representing a path in a mountain hiking trail. Determine the number of valleys encountered during the hike. A valley is defined as any sequence of consecutive steps below sea level, star...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6409, "level": 1, "question": "Given a string `log` consisting of characters 'U' (uphill), 'D' (downhill), and '_' (flat terrain), representing a path in a mountain hiking trail. Determine the number of valleys encountered during the hike. A valley is defined as any sequence of cons...
def all_unique(lst): return len(lst) == len(set(lst)) # Test cases print(all_unique([1, 2, 3, 4])) # Expected output: True print(all_unique([1, 2, 2, 3])) # Expected output: False
simplelr_Filter
[ { "content": "Question:\nCan you write a piece of Python code that checks if all elements in a given list are unique? If all elements are unique, the function should return True; if there are duplicates, it should return False. Please also include a simple test case to verify your solution.\nAnswer:\nLet's thin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6410, "level": 1, "question": "Can you write a piece of Python code that checks if all elements in a given list are unique? If all elements are unique, the function should return True; if there are duplicates, it should return False. Please also include a simple test case to verify ...
def generate_ascending_sequence(start, end, step=1): if start >= end: return [] if step <= 0: return [] sequence = [] current = start while current < end: sequence.append(current) current += step return sequence
simplelr_Filter
[ { "content": "Question:\nWrite a Python function `generate_ascending_sequence` that accepts three parameters: `start`, `end`, and `step`. This function should return a list of numbers starting from `start` up to but not including `end`, incrementing by `step`. If `step` is not provided, it should default to 1. ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6411, "level": 1, "question": "Write a Python function `generate_ascending_sequence` that accepts three parameters: `start`, `end`, and `step`. This function should return a list of numbers starting from `start` up to but not including `end`, incrementing by `step`. If `step` is not...
def process_data(data): processed = [] for s in data: words = s.split() reversed_words_order = words[::-1] reversed_chars = [word[::-1] for word in reversed_words_order] new_string = ' '.join(reversed_chars) processed.append(new_string) return processed
simplelr_Docs
[ { "content": "Question:\n### Question: String and List Manipulation in Python\n\n**Objective:** Write a function `process_data` that processes a given list of strings according to the requirements outlined below.\n\n**Requirements:**\n\n1. The function should accept a single argument: a list of strings `data`, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6412, "level": 1, "question": "### Question: String and List Manipulation in Python\n\n**Objective:** Write a function `process_data` that processes a given list of strings according to the requirements outlined below.\n\n**Requirements:**\n\n1. The function should accept a single a...
def rotate_array(arr, n): if not arr or n == 0: return list(arr) m = len(arr) k = n % m if k == 0: return list(arr) return arr[-k:] + arr[:-k]
simplelr_Algorithm
[ { "content": "Question:\n### Array Rotation\n\n#### Problem Statement:\nWrite a function `rotate_array` that rotates the elements of an array to the right by `n` positions. \n\nElements that are shifted beyond the length of the array are wrapped around to the beginning.\n\n#### Input:\n\n- A list of integers, `...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6413, "level": 1, "question": "### Array Rotation\n\n#### Problem Statement:\nWrite a function `rotate_array` that rotates the elements of an array to the right by `n` positions. \n\nElements that are shifted beyond the length of the array are wrapped around to the beginning.\n\n###...
def rank_elements_by_threshold(lst, threshold): above = sorted([x for x in lst if x >= threshold], reverse=True) below = sorted([x for x in lst if x < threshold]) return above + below
simplelr_Filter
[ { "content": "Question:\nDesign a Python function that ranks and groups elements of a list based on a threshold condition. The function should accept a list of numerical values and a threshold value. It should output a list where each element's position is determined by the descending order of its value within ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6414, "level": 1, "question": "Design a Python function that ranks and groups elements of a list based on a threshold condition. The function should accept a list of numerical values and a threshold value. It should output a list where each element's position is determined by the de...
def longest_substring_k_distinct(s: str, k: int) -> int: char_count = {} left = 0 max_length = 0 for right in range(len(s)): current_char = s[right] char_count[current_char] = char_count.get(current_char, 0) + 1 # If the number of distinct characters exceeds k, adjust th...
simplelr_Code_Contests
[ { "content": "Question:\nCreate a function that takes a string `s` and an integer `k` as input. The function should return the length of the longest substring of `s` that contains at most `k` distinct characters.\n\n**Function Signature:**\n```python\ndef longest_substring_k_distinct(s: str, k: int) -> int:\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6415, "level": 1, "question": "Create a function that takes a string `s` and an integer `k` as input. The function should return the length of the longest substring of `s` that contains at most `k` distinct characters.\n\n**Function Signature:**\n```python\ndef longest_substring_k_d...
from typing import List def count_paths(grid: List[List[str]]) -> int: m = len(grid) if m == 0: return 0 n = len(grid[0]) if n == 0: return 0 if grid[0][0] == '#' or grid[m-1][n-1] == '#': return 0 dp = [[0 for _ in range(n)] for _ in range(m)] dp[0][0] = 1...
simplelr_Apps
[ { "content": "Question:\nPaths in a Grid\n\nGiven an MxN grid, where each cell can either be empty ('.') or blocked ('#'), write a function to calculate the number of unique paths from the top-left corner to the bottom-right corner. You can only move right or down at each step.\n\n### Examples\n\n**Example 1:**...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6416, "level": 1, "question": "Paths in a Grid\n\nGiven an MxN grid, where each cell can either be empty ('.') or blocked ('#'), write a function to calculate the number of unique paths from the top-left corner to the bottom-right corner. You can only move right or down at each step...
def sum_numeric_values(mixed_list): total = 0 for item in mixed_list: if isinstance(item, (int, float)) and not isinstance(item, bool): total += item return total # Example usage: mixed_list = [1, 2, 'a', 3.5, True, False, 'b'] result = sum_numeric_values(mixed_list) print(result) # Ou...
simplelr_Filter
[ { "content": "Question:\nI have a list of mixed elements in a Python list, including numbers and strings. I want to sum up the numeric values while safely ignoring the strings. How can I modify the given code to handle this situation, ensuring that non-numeric entries do not disrupt the computation?\nAnswer:\nL...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6417, "level": 1, "question": "I have a list of mixed elements in a Python list, including numbers and strings. I want to sum up the numeric values while safely ignoring the strings. How can I modify the given code to handle this situation, ensuring that non-numeric entries do not d...
import math def find_gcd(array): if not array: return 0 if len(array) == 1: return abs(array[0]) current_gcd = array[0] for num in array[1:]: current_gcd = math.gcd(current_gcd, num) if current_gcd == 1: break return current_gcd
simplelr_Package
[ { "content": "Question:\nYou are required to write a function in Python that computes the greatest common divisor (GCD) of an array of integers. The function should be named `find_gcd` and should accept one parameter:\n- `array`: A list of integers for which the GCD needs to be calculated.\n\nThe function shoul...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6418, "level": 1, "question": "You are required to write a function in Python that computes the greatest common divisor (GCD) of an array of integers. The function should be named `find_gcd` and should accept one parameter:\n- `array`: A list of integers for which the GCD needs to b...
def longest_substring_without_repeating_characters(s: str) -> str: i = 0 longest_substring = "" seen = set() n = len(s) for j in range(n): while s[j] in seen: seen.remove(s[i]) i += 1 seen.add(s[j]) current_substring = s[i:j+1] if len(current_s...
simplelr_Filter
[ { "content": "Question:\nYou are given a string of lowercase letters.\n\nYou want to find the longest substring without repeating characters.\n\nExample:\n\nInput: \"abcabcbb\"\nOutput: \"abc\"\n\nInput: \"bbbbb\"\nOutput: \"b\"\n\nInput: \"pwwkew\"\nOutput: \"wke\"\n\nApproach:\n\nSliding Window Technique\n\nT...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6419, "level": 1, "question": "You are given a string of lowercase letters.\n\nYou want to find the longest substring without repeating characters.\n\nExample:\n\nInput: \"abcabcbb\"\nOutput: \"abc\"\n\nInput: \"bbbbb\"\nOutput: \"b\"\n\nInput: \"pwwkew\"\nOutput: \"wke\"\n\nApproac...
from array import array def sum_of_evens(arr: array) -> int: sum_even = 0 for num in arr: if num % 2 == 0: sum_even += num return sum_even # Example usage: # arr1 = array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # print(sum_of_evens(arr1)) # Output: 30 # arr2 = array('i', [-10, 0, 5, 12...
simplelr_Docs
[ { "content": "Question:\n**Objective:**\nYou are required to implement a function `sum_of_evens` that takes an array of signed integers and returns the sum of all even numbers in the array. Make full use of the `array` module and ensure the solution is efficient in terms of both time and space.\n\n**Function Si...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6420, "level": 1, "question": "**Objective:**\nYou are required to implement a function `sum_of_evens` that takes an array of signed integers and returns the sum of all even numbers in the array. Make full use of the `array` module and ensure the solution is efficient in terms of bo...
from collections import Counter def find_max_occurrence(numbers: list) -> int: if not numbers: return None count = Counter(numbers) max_count = max(count.values()) candidates = [num for num, cnt in count.items() if cnt == max_count] return min(candidates)
simplelr_Package
[ { "content": "Question:\nYou have been approached to create a function called `find_max_occurrence` in Python, which will accept a list of integers and determine the integer that occurs the most frequently. The function should meet the following requirements:\n\n1. If there is a tie (i.e., multiple integers occ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6421, "level": 1, "question": "You have been approached to create a function called `find_max_occurrence` in Python, which will accept a list of integers and determine the integer that occurs the most frequently. The function should meet the following requirements:\n\n1. If there is...
from collections import Counter from typing import List def countUniqueElements(ar: List[int]) -> int: counts = Counter(ar) return sum(1 for count in counts.values() if count == 1)
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers, determine the number of elements in the array that are unique (appear only once).\n\nFor example, if the array `ar = [1, 2, 2, 3, 4, 4, 5]`, the unique elements are `[1, 3, 5]`, so the function should return `3`.\n\n#### Function Description\n\nComplete the `...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6422, "level": 1, "question": "Given an array of integers, determine the number of elements in the array that are unique (appear only once).\n\nFor example, if the array `ar = [1, 2, 2, 3, 4, 4, 5]`, the unique elements are `[1, 3, 5]`, so the function should return `3`.\n\n#### Fun...
from collections import deque def bfs_level(n, edges, s): # Create the adjacency list adj = [[] for _ in range(n)] for u, v in edges: adj[u].append(v) adj[v].append(u) # Initialize level array with -1 level = [-1] * n queue = deque([s]) level[s] = 0 while queue...
simplelr_Code_Contests
[ { "content": "Question:\nValera is working on a problem involving a connected, unweighted, undirected graph with n vertices and m edges. Valera wants to perform a breadth-first search (BFS) starting from a given source vertex s. After performing the BFS, he is interested in knowing the level of each vertex from...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6423, "level": 1, "question": "Valera is working on a problem involving a connected, unweighted, undirected graph with n vertices and m edges. Valera wants to perform a breadth-first search (BFS) starting from a given source vertex s. After performing the BFS, he is interested in kn...
def find_max_min(nested_list): flat_list = [num for sublist in nested_list for num in sublist] return max(flat_list), min(flat_list) nested_list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] nested_list2 = [[10, 20], [30, 40], [50, 60], [70, 80]] nested_list3 = [[100, 200, 300], [400, 500, 600], [700, 800, 900]] nested...
simplelr_Filter
[ { "content": "Question:\nHere are 5 nested lists in Python:\n```python\nnested_list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nnested_list2 = [[10, 20], [30, 40], [50, 60], [70, 80]]\nnested_list3 = [[100, 200, 300], [400, 500, 600], [700, 800, 900]]\nnested_list4 = [[1000, 2000], [3000, 4000], [5000, 6000], [7000, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6424, "level": 1, "question": "Here are 5 nested lists in Python:\n```python\nnested_list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nnested_list2 = [[10, 20], [30, 40], [50, 60], [70, 80]]\nnested_list3 = [[100, 200, 300], [400, 500, 600], [700, 800, 900]]\nnested_list4 = [[1000, 2000], ...
from typing import List def increment_digits(digits: List[int]) -> List[int]: if not digits: digits.append(1) return digits carry = 1 for i in range(len(digits)-1, -1, -1): digits[i] += carry if digits[i] > 9: carry = 1 digits[i] -= 10 el...
simplelr_Data_Structure
[ { "content": "Question:\nYou are given a non-negative number represented as an array of digits, where each digit is in the range 0–9 and the most significant digit is at the head of the list. Write a function that increments this number by one.\n\nYour task is to provide an implementation of this function that ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6425, "level": 1, "question": "You are given a non-negative number represented as an array of digits, where each digit is in the range 0–9 and the most significant digit is at the head of the list. Write a function that increments this number by one.\n\nYour task is to provide an im...
def has_repeating_chars(s): seen = set() for char in s: if char in seen: return True seen.add(char) return False
simplelr_Prefill
[ { "content": "Question:\nWrite a function to detect if a string contains any repeating characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6426, "level": 1, "question": "Write a function to detect if a string contains any repeating characters.", "split": "train" }
def find_first_occurrence(nums, target): for index, num in enumerate(nums): if num == target: return index 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 earliest occurrence of the target integer in the list, if it exists. If the target integer is not found, the function should return -1.\nAnswer:\nLet's think step by s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6427, "level": 1, "question": "Create a function that takes in two parameters: a list of integers and a target integer. The function should return the earliest occurrence of the target integer in the list, if it exists. If the target integer is not found, the function should return ...
def set_intersection(set_A, set_B): """ This function returns the intersection of two sets. The intersection consists of elements common to both sets. Parameters: set_A (set): The first set. set_B (set): The second set. Returns: set: A new set containing elements present in bot...
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python implementation of a set intersection algorithm that uses the built-in set data structure?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6428, "level": 1, "question": "Can you provide a Python implementation of a set intersection algorithm that uses the built-in set data structure?", "split": "train" }
def calculate_differences(numbers): return [numbers[i+1] - numbers[i] for i in range(len(numbers) - 1)]
simplelr_Filter
[ { "content": "Question:\nHere's a description of a technical problem. I want you to write the code to solve it.\n\nI have a list of numbers, and I want to write a function to calculate the difference between each pair of adjacent numbers. The result should be a new list that contains these differences.\n\nFor e...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6429, "level": 1, "question": "Here's a description of a technical problem. I want you to write the code to solve it.\n\nI have a list of numbers, and I want to write a function to calculate the difference between each pair of adjacent numbers. The result should be a new list that c...
def merge_intervals(intervals): if not intervals: return [] # Sort intervals based on the start time sorted_intervals = sorted(intervals, key=lambda x: x[0]) result = [] current_start, current_end = sorted_intervals[0][0], sorted_intervals[0][1] for interval in sorted_inte...
simplelr_Filter
[ { "content": "Question:\nHere's an interesting problem I came across: \n\nGiven a list of intervals, merge all overlapping intervals and return the merged list of non-overlapping intervals.\n\nHere's my attempt at a solution:\n```\ndef merge_intervals(intervals):\n if len(intervals) <= 1:\n return int...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6430, "level": 1, "question": "Here's an interesting problem I came across: \n\nGiven a list of intervals, merge all overlapping intervals and return the merged list of non-overlapping intervals.\n\nHere's my attempt at a solution:\n```\ndef merge_intervals(intervals):\n if len(i...
def max_binary_diff(binaries: list[str]) -> tuple[str, str]: """ Finds the two binary numbers in the list that have the maximum difference when converted to decimal. Parameters: binaries (list[str]): The list of binary strings. Returns: tuple[str, str]: A tuple containing the two binar...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are given a list of strings, each representing a binary number. Your task is to find the two binary numbers within the list that, when converted to decimal, have the maximum difference. Return these two numbers as strings in their original binary form.\n\n##...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6431, "level": 1, "question": "### Problem Statement\n\nYou are given a list of strings, each representing a binary number. Your task is to find the two binary numbers within the list that, when converted to decimal, have the maximum difference. Return these two numbers as strings i...
def find_pattern(string, pattern): return pattern in string
simplelr_Filter
[ { "content": "Question:\nHere's a problem: \nYou are given a string of characters and a pattern to find in the string. The string and the pattern are both non-empty and consist of lowercase English letters only. Write a function that checks if the given pattern appears in the string.\n\nExample 1:\nString: \"he...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6432, "level": 1, "question": "Here's a problem: \nYou are given a string of characters and a pattern to find in the string. The string and the pattern are both non-empty and consist of lowercase English letters only. Write a function that checks if the given pattern appears in the ...
def longest_unique_substr(s): char_index = {} start = 0 max_length = 0 for i, char in enumerate(s): if char in char_index and char_index[char] >= start: start = char_index[char] + 1 char_index[char] = i current_length = i - start + 1 if current_length > max_le...
simplelr_Package
[ { "content": "Question:\nYou are given a string of lowercase English letters, and you need to find the longest substring without repeating characters. A substring is defined as a contiguous sequence of characters within a string.\n\nWrite a function `longest_unique_substr(s)` that:\n- Takes a single argument `s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6433, "level": 1, "question": "You are given a string of lowercase English letters, and you need to find the longest substring without repeating characters. A substring is defined as a contiguous sequence of characters within a string.\n\nWrite a function `longest_unique_substr(s)` ...
def performShifts(S: str, shift: list[int]) -> str: res = [] for i in range(len(S)): c = S[i] s = shift[i] effective = s % 26 new_ord = (ord(c) - ord('a') + effective) % 26 new_char = chr(new_ord + ord('a')) res.append(new_char) return ''.join(res)
simplelr_Taco
[ { "content": "Question:\nYou are given a string S consisting of lowercase letters and an array of integers shift where shift[i] indicates the number of positions to shift the character at position i in the string forward. Shifting a character forward means moving it to the right in the alphabet, with 'a' follow...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6434, "level": 1, "question": "You are given a string S consisting of lowercase letters and an array of integers shift where shift[i] indicates the number of positions to shift the character at position i in the string forward. Shifting a character forward means moving it to the rig...
def add(a, b): return a + b
simplelr_Filter
[ { "content": "Question:\nGiven a Python code that defines a function for adding two numbers, how can we modify this function to also accept and handle complex numbers, ensuring it returns the correct sum in all cases?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6435, "level": 1, "question": "Given a Python code that defines a function for adding two numbers, how can we modify this function to also accept and handle complex numbers, ensuring it returns the correct sum in all cases?", "split": "train" }
def find_longest_alphabetical_subarray(seq): if not seq: return (0, 0) # Assuming the problem expects (0,0) for an empty list n = len(seq) max_len = 1 max_start = 0 current_start = 0 for i in range(1, n): if seq[i] >= seq[i-1]: continue else: ...
simplelr_Filter
[ { "content": "Question:\nGiven a string of lowercase alphabets in a python list variable named *seq*, write a python function to find the longest subarray which has all the characters in alphabetical order. The function should return the indices of the first and last character in the subarray. If multiple subar...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6436, "level": 1, "question": "Given a string of lowercase alphabets in a python list variable named *seq*, write a python function to find the longest subarray which has all the characters in alphabetical order. The function should return the indices of the first and last character...
def shell_sort(arr): n = len(arr) gap = n // 2 while gap > 0: for i in range(gap, n): temp = arr[i] j = i while j >= gap and arr[j - gap] > temp: arr[j] = arr[j - gap] j -= gap arr[j] = temp gap = gap // 2 re...
simplelr_Data_Structure
[ { "content": "Question:\nGiven an array of integers, implement the Shell Sort algorithm to sort the array in ascending order. The function should be named `shell_sort` and take a single argument, which is the list of integers. Return the sorted list as the output.\n\n#### Input\nA single list of integers `arr`:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6437, "level": 1, "question": "Given an array of integers, implement the Shell Sort algorithm to sort the array in ascending order. The function should be named `shell_sort` and take a single argument, which is the list of integers. Return the sorted list as the output.\n\n#### Inpu...
def evaluate_revpol(expression): tokens = expression.split() stack = [] operators = {'+', '-', '*', '/', '^'} for token in tokens: if token in operators: if len(stack) < 2: return None op1 = stack.pop() op2 = stack.pop() if tok...
simplelr_Apps
[ { "content": "Question:\nCreate a function that evaluates mathematical expressions written in a custom notation called **RevPol**.\n\n## The Notation\n\nRevPol is a Reverse Polish Notation (RPN) where every operator follows all of its operands. It is a mathematical notation in which every operator immediately f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6438, "level": 1, "question": "Create a function that evaluates mathematical expressions written in a custom notation called **RevPol**.\n\n## The Notation\n\nRevPol is a Reverse Polish Notation (RPN) where every operator follows all of its operands. It is a mathematical notation in...
import heapq def min_meeting_rooms(projects): if not projects: return 0 heap = [] max_rooms = 0 for start, end in projects: if heap and start >= heap[0]: heapq.heappop(heap) heapq.heappush(heap, end) max_rooms = max(max_rooms, len(heap)) re...
simplelr_Leetcode
[ { "content": "Question:\nA company has multiple departments, each offering a variety of projects. Each project has a start time and an end time. You are tasked with determining the minimum number of meeting rooms required for the projects in all departments combined. \n\nGiven a list of `projects`, where each p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6439, "level": 1, "question": "A company has multiple departments, each offering a variety of projects. Each project has a start time and an end time. You are tasked with determining the minimum number of meeting rooms required for the projects in all departments combined. \n\nGiven...
def sort_with_pigeonhole(input_list): if not input_list: return [] min_val = min(input_list) max_val = max(input_list) range_size = max_val - min_val + 1 pigeonholes = [0] * range_size for num in input_list: index = num - min_val pigeonholes[index] += 1 ...
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario\nYou are developing a data processing application that needs to sort lists of integers that have small ranges of values. Given the constraints of the application, you decide to implement Pigeonhole Sort because it is efficient for sorting lists where the number of elements ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6440, "level": 1, "question": "### Scenario\nYou are developing a data processing application that needs to sort lists of integers that have small ranges of values. Given the constraints of the application, you decide to implement Pigeonhole Sort because it is efficient for sorting ...
def batch_rename_files(filenames: list, prefix: str) -> list: # Validate the prefix if not prefix or ' ' in prefix: raise ValueError("Prefix must be a non-empty string with no spaces") # Validate each filename for filename in filenames: if not filename or ' ' in filename: ...
simplelr_Algorithm
[ { "content": "Question:\nBatch File Renaming\n\n### Problem Statement\n\nYou have a collection of files in a directory, each with a unique name. You need to implement a function `batch_rename_files` that takes a list of filenames and a common prefix. Your function should return a new list of filenames where eac...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6441, "level": 1, "question": "Batch File Renaming\n\n### Problem Statement\n\nYou have a collection of files in a directory, each with a unique name. You need to implement a function `batch_rename_files` that takes a list of filenames and a common prefix. Your function should retur...
def maxTasks(tasks): # Sort the tasks by their deadlines in ascending order tasks.sort() current_time = 0 count = 0 for deadline, duration in tasks: if current_time + duration <= deadline: count += 1 current_time += duration return count
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of tasks, where each task `i` is represented by a pair of integers `[deadline, duration]`. You can only work on one task at a time, and you must complete each task by its deadline in order to receive credit for that task. Return the maximum number of tasks you can c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6442, "level": 1, "question": "You are given a list of tasks, where each task `i` is represented by a pair of integers `[deadline, duration]`. You can only work on one task at a time, and you must complete each task by its deadline in order to receive credit for that task. Return th...
def largestRectangleArea(height): stack = [-1] # Initialize stack with sentinel max_area = 0 n = len(height) for i in range(n): while stack[-1] != -1 and height[i] < height[stack[-1]]: h = height[stack.pop()] left = stack[-1] width = i - left - 1 ...
simplelr_Apps
[ { "content": "Question:\nYou are given an array representing the heights of bars in a histogram. Each bar has a width of 1. Your task is to find the area of the largest rectangle that can be formed within the bounds of the histogram.\n\nThe histogram is such that it is surrounded by the imaginary ground of y = ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6443, "level": 1, "question": "You are given an array representing the heights of bars in a histogram. Each bar has a width of 1. Your task is to find the area of the largest rectangle that can be formed within the bounds of the histogram.\n\nThe histogram is such that it is surroun...
def is_palindrome(s): # Convert the string to lowercase and remove non-alphanumeric characters cleaned_s = ''.join(c.lower() for c in s if c.isalnum()) # Check if the cleaned string is equal to its reverse return cleaned_s == cleaned_s[::-1] # Check function with provided data points print(is_palindrom...
simplelr_Filter
[ { "content": "Question:\nWrite a function to check if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). \\n\\nExample 1: \\nInput: \"A man, a plan, a canal: Panama\"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6444, "level": 1, "question": "Write a function to check if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). \\n\\nExample 1: \\nInput:...
import os def setup_project_structure(root_path: str, project_name: str, readme_content: str) -> None: """ Sets up the directory structure for a new project and manages file permissions. Parameters: - root_path (str): The root path where the project directory will be created. - project_name (str):...
simplelr_Docs
[ { "content": "Question:\n#### Objective\nDesign and implement a Python function that interacts with the file system using the `os` module. The task will focus on creating directories, handling files and paths, and managing file permissions and attributes.\n\n#### Problem Statement\nYou are tasked with developin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6445, "level": 1, "question": "#### Objective\nDesign and implement a Python function that interacts with the file system using the `os` module. The task will focus on creating directories, handling files and paths, and managing file permissions and attributes.\n\n#### Problem State...
from typing import List def largest_subarray_sum(arr: List[int], k: int) -> int: n = len(arr) current_sum = sum(arr[:k]) max_sum = current_sum for i in range(1, n - k + 1): current_sum = current_sum - arr[i - 1] + arr[i + k - 1] if current_sum > max_sum: max_sum = current_su...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are asked to write a function `largest_subarray_sum(arr: List[int], k: int) -> int` that finds the largest sum of any contiguous subarray of length `k` from the given list `arr`.\n\n### Input\n- A list `arr` of integers. (-1000 ≤ arr[i] ≤ 1000)\n- An integer...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6446, "level": 1, "question": "### Problem Statement\n\nYou are asked to write a function `largest_subarray_sum(arr: List[int], k: int) -> int` that finds the largest sum of any contiguous subarray of length `k` from the given list `arr`.\n\n### Input\n- A list `arr` of integers. (-...
from collections import defaultdict def price_analyzer(start_date, end_date, price_data): product_data = defaultdict(list) for date_str, product, price in price_data: if start_date <= date_str <= end_date: product_data[product].append(price) result = {} for product, prices in produc...
simplelr_Evol
[ { "content": "Question:\nWrite a function `price_analyzer` that analyzes the prices of products over time. You will be given a list of tuples representing the daily prices of various products (e.g., [(date, product_name, price), ...]). The dates will be in the format 'YYYY-MM-DD.' Your task is to implement the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6447, "level": 1, "question": "Write a function `price_analyzer` that analyzes the prices of products over time. You will be given a list of tuples representing the daily prices of various products (e.g., [(date, product_name, price), ...]). The dates will be in the format 'YYYY-MM-...
def can_reach_end(jump_list: list[int]) -> bool: max_reach = 0 for i in range(len(jump_list)): if i > max_reach: return False max_reach = max(max_reach, i + jump_list[i]) return True
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nWrite a function `can_reach_end` to determine if it is possible to reach the last index of a list of non-negative integers, where each integer represents the maximum jump length at that position.\n\nEach jump can be at most the value of the integer at that posit...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6448, "level": 1, "question": "### Problem Statement\n\nWrite a function `can_reach_end` to determine if it is possible to reach the last index of a list of non-negative integers, where each integer represents the maximum jump length at that position.\n\nEach jump can be at most the...
import pandas as pd def student_performance_analysis(scores_df, subject, operation): if operation == "average": return scores_df[subject].mean() elif operation == "top": max_index = scores_df[subject].idxmax() return scores_df.loc[max_index, 'Name'] elif operation == "bottom": ...
simplelr_Package
[ { "content": "Question:\nYou need to create a function called `student_performance_analysis` that will analyze the performance of students based on their scores in three subjects (Math, Science, and English). The data is given in a pandas DataFrame, and your function should perform various analyses based on inp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6449, "level": 1, "question": "You need to create a function called `student_performance_analysis` that will analyze the performance of students based on their scores in three subjects (Math, Science, and English). The data is given in a pandas DataFrame, and your function should pe...
def can_be_sum_of_three_even_numbers(n): return n % 2 == 0 and n >= 6
simplelr_Prefill
[ { "content": "Question:\nWrite a function to determine if a given positive integer `n` can be expressed as the sum of exactly three positive even integers. Your function should return `true` if `n` can be expressed as such a sum, and `false` otherwise.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6450, "level": 1, "question": "Write a function to determine if a given positive integer `n` can be expressed as the sum of exactly three positive even integers. Your function should return `true` if `n` can be expressed as such a sum, and `false` otherwise.", "split": "train" }
def findXthNumber(X): return X * (X + 1) * (X + 2) // 6
simplelr_Taco
[ { "content": "Question:\nGiven a series of numbers 1, 4, 10, 20, 35..., where each number is generated by a specific pattern, determine the X'th number in the series. You need to recognize the pattern and implement a function to compute the X'th number for any given X.\n\nExample 1:\nInput:\nX = 3\nOutput:\n10\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6451, "level": 1, "question": "Given a series of numbers 1, 4, 10, 20, 35..., where each number is generated by a specific pattern, determine the X'th number in the series. You need to recognize the pattern and implement a function to compute the X'th number for any given X.\n\nExam...
def custom_binary_transform(num): binary_str = bin(num)[2:] # Convert to binary and remove the '0b' prefix translation_table = str.maketrans('01', 'BA') # Create translation table transformed = binary_str.translate(translation_table) return transformed
simplelr_Filter
[ { "content": "Question:\nCan you help me create a Python function that converts a given number into its binary representation and then applies a custom transformation? The custom transformation involves replacing all '1's with 'A' and all '0's with 'B'. The function should return the transformed string.\nAnswer...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6452, "level": 1, "question": "Can you help me create a Python function that converts a given number into its binary representation and then applies a custom transformation? The custom transformation involves replacing all '1's with 'A' and all '0's with 'B'. The function should ret...
import numpy as np import matplotlib.pyplot as plt def plot_linear_regression(x, y, line_color='red', data_color='blue'): """ Plots a 2D dataset and its linear regression line. Parameters: x (ndarray): A NumPy array of shape (n,) representing the x-coordinates of the data points. y (ndarray): A Nu...
simplelr_Package
[ { "content": "Question:\nCreate a function to perform linear regression on a 2D dataset and plot the results using `matplotlib`. This function should fit a linear model to the provided data points and visualize both the data and the fitted regression line.\n\n**Function Signature:**\n```python\ndef plot_linear_...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6453, "level": 1, "question": "Create a function to perform linear regression on a 2D dataset and plot the results using `matplotlib`. This function should fit a linear model to the provided data points and visualize both the data and the fitted regression line.\n\n**Function Signat...
def process_string(s): stack = [] for c in s: if c != '#': stack.append(c) else: if stack: stack.pop() return ''.join(stack)
simplelr_Filter
[ { "content": "Question:\nYou are given a string `str` consisting of lowercase letters and '#' characters. The '#' character represents a backspace. \n\nYour task is to process the string by deleting characters to the left of the '#' character.\n\nExample:\n```\nInput: str = \"ab#c\"\nOutput: \"c\"\n\nInput: str...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6454, "level": 1, "question": "You are given a string `str` consisting of lowercase letters and '#' characters. The '#' character represents a backspace. \n\nYour task is to process the string by deleting characters to the left of the '#' character.\n\nExample:\n```\nInput: str = \"...
from datetime import datetime def largest_file_within_last_year(sizes, dates, current_date): current = datetime.strptime(current_date, "%Y-%m-%d").date() max_size = -1 for size, date_str in zip(sizes, dates): file_date = datetime.strptime(date_str, "%Y-%m-%d").date() delta_days = (current -...
simplelr_Leetcode
[ { "content": "Question:\nYou have a collection of `n` computer files. You are given an array `sizes` where `sizes[i]` represents the size of the ith file in megabytes (MB). Additionally, there is an array `dates` where `dates[i]` is a string representing the date when the ith file was last modified, in the form...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6455, "level": 1, "question": "You have a collection of `n` computer files. You are given an array `sizes` where `sizes[i]` represents the size of the ith file in megabytes (MB). Additionally, there is an array `dates` where `dates[i]` is a string representing the date when the ith ...
def shortest_path_with_constraints(graph, source, destination, max_edges): if source == destination: return 0 if max_edges >= 0 else -1 n = len(graph) INF = float('inf') dist = [[INF] * (max_edges + 1) for _ in range(n)] dist[source][0] = 0 import heapq heap = [] heapq.heappush...
simplelr_Algorithm
[ { "content": "Question:\n### Shortest Path with Constraints\n\nYou are given a directed graph where each edge has a weight and there is a specific constraint on the maximum number of edges that can be used in the path. Your task is to find the shortest path from the source node to the destination node such that...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6456, "level": 1, "question": "### Shortest Path with Constraints\n\nYou are given a directed graph where each edge has a weight and there is a specific constraint on the maximum number of edges that can be used in the path. Your task is to find the shortest path from the source nod...
from typing import List import heapq def multi_merge_sort(arrays: List[List[int]]) -> List[int]: result = [] heap = [] # Push the first element of each array into the heap for i in range(len(arrays)): if arrays[i]: # Check if the array is not empty val = arrays[i][0] ...
simplelr_Algorithm
[ { "content": "Question:\n**Context**: Sorting algorithms are a fundamental part of computer science, with applications ranging from database indexing to search engines and beyond. One notable family of sorting algorithms is the merge sort, which follows a divide-and-conquer approach. However, variations of merg...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6457, "level": 1, "question": "**Context**: Sorting algorithms are a fundamental part of computer science, with applications ranging from database indexing to search engines and beyond. One notable family of sorting algorithms is the merge sort, which follows a divide-and-conquer ap...
def factorial(n): if type(n) is not int or n < 0: return "invalid input" result = 1 for i in range(1, n + 1): result *= i return result
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes an integer input and returns the factorial of the number.\n\nThe factorial of a non-negative integer `n` is the product of all positive integers less than or equal to `n`. The factorial of `0` is `1`.\n\nYour function will accept one argument:\n- The argument...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6458, "level": 1, "question": "Write a function that takes an integer input and returns the factorial of the number.\n\nThe factorial of a non-negative integer `n` is the product of all positive integers less than or equal to `n`. The factorial of `0` is `1`.\n\nYour function will a...
def sum_even_fibonacci(n, k): a, b = 1, 1 sum_even = 0 while a <= n: if a % 2 == 0: sum_even += a next_fib = a + b a, b = b, next_fib return sum_even
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes two arguments, `n` and `k`, and returns the sum of all even Fibonacci numbers not exceeding `n`. The Fibonacci sequence starts with `F(1) = 1` and `F(2) = 1`, and for `F(n) > 2`, `F(n) = F(n-1) + F(n-2)`. Ensure `n` is a positive integer.\nAnswer:\nLet's thi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6459, "level": 1, "question": "Create a function that takes two arguments, `n` and `k`, and returns the sum of all even Fibonacci numbers not exceeding `n`. The Fibonacci sequence starts with `F(1) = 1` and `F(2) = 1`, and for `F(n) > 2`, `F(n) = F(n-1) + F(n-2)`. Ensure `n` is a po...
def unique_paths(m, n): k = min(m-1, n-1) if k == 0: return 1 numerator = 1 denominator = 1 for i in range(k): numerator *= (m + n - 2 - i) denominator *= (i + 1) return numerator // denominator
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the number of unique paths from the top-left corner to the bottom-right corner of a matrix. You can only move either down or right at any point in time.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6460, "level": 1, "question": "Write a python function to find the number of unique paths from the top-left corner to the bottom-right corner of a matrix. You can only move either down or right at any point in time.", "split": "train" }
from itertools import permutations def string_permutations(s: str) -> list: perms = permutations(s) all_perms = [''.join(p) for p in perms] unique_perms = set(all_perms) return list(unique_perms)
simplelr_Taco
[ { "content": "Question:\n## String Permutations\n\nYou are tasked with generating all permutations of a given string. A permutation, also called an \"anagram\", of a string is a rearrangement of its characters into a different order. \n\nWrite a function in Python that takes a string and returns a list containi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6461, "level": 1, "question": "## String Permutations\n\nYou are tasked with generating all permutations of a given string. A permutation, also called an \"anagram\", of a string is a rearrangement of its characters into a different order. \n\nWrite a function in Python that takes a...
def strings_to_length_dict(strings): return {s: len(s) for s in strings if s.isalpha()}
simplelr_Evol
[ { "content": "Question:\nDevelop a function in Python that takes a list of strings as input and returns a dictionary where the keys are the strings and the values are the lengths of those strings. The function should ignore any strings that contain non-alphabetic characters and gracefully handle an empty list i...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6462, "level": 1, "question": "Develop a function in Python that takes a list of strings as input and returns a dictionary where the keys are the strings and the values are the lengths of those strings. The function should ignore any strings that contain non-alphabetic characters an...
from typing import List def rotate_array(arr: List[int], k: int) -> List[int]: n = len(arr) if n == 0 or k == 0: return arr effective_k = k % n if effective_k == 0: return arr return arr[-effective_k:] + arr[:-effective_k]
simplelr_Algorithm
[ { "content": "Question:\n### Array Rotation Challenge\n\nGiven an array of integers and an integer `k`, write a function `rotate_array(arr: List[int], k: int) -> List[int]` that rotates the array to the right by `k` steps. This means that the element at index `i` will be moved to index `(i + k) % len(arr)`.\n\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6463, "level": 1, "question": "### Array Rotation Challenge\n\nGiven an array of integers and an integer `k`, write a function `rotate_array(arr: List[int], k: int) -> List[int]` that rotates the array to the right by `k` steps. This means that the element at index `i` will be moved...
def find_common_characters(str1: str, str2: str) -> list: # Convert both strings to lowercase to ensure case-insensitivity str1_lower = str1.lower() str2_lower = str2.lower() # Create sets of characters for each string set1 = set(str1_lower) set2 = set(str2_lower) # Find the inters...
simplelr_Package
[ { "content": "Question:\nYou are asked to write a Python function named `find_common_characters`. This function will take two strings as input and will return a sorted list of unique characters that are present in both strings.\n\n**Requirements**:\n1. The function should be case-insensitive, meaning 'A' and 'a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6464, "level": 1, "question": "You are asked to write a Python function named `find_common_characters`. This function will take two strings as input and will return a sorted list of unique characters that are present in both strings.\n\n**Requirements**:\n1. The function should be c...
def recursive_selection_sort(arr): if len(arr) <= 1: return arr max_val = max(arr) new_arr = arr.copy() new_arr.remove(max_val) return [max_val] + recursive_selection_sort(new_arr)
simplelr_Filter
[ { "content": "Question:\nGiven a list A of elements, create a code to sort the elements in descending order using Python, without using any built-in sorting functions or libraries. The time complexity of the sorting algorithm should be O(n^2). Additionally, you should implement the sorting algorithm using a rec...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6465, "level": 1, "question": "Given a list A of elements, create a code to sort the elements in descending order using Python, without using any built-in sorting functions or libraries. The time complexity of the sorting algorithm should be O(n^2). Additionally, you should implemen...
def decimal_to_binary(n): if n == 0: return '0' bits = [] while n > 0: remainder = n % 2 bits.append(str(remainder)) n = n // 2 return ''.join(reversed(bits))
simplelr_Filter
[ { "content": "Question:\nI would like to convert a decimal number to a binary number using Python without using any built-in functions. How can I achieve this? I need the solution to work for any decimal number between 0 and 255.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6466, "level": 1, "question": "I would like to convert a decimal number to a binary number using Python without using any built-in functions. How can I achieve this? I need the solution to work for any decimal number between 0 and 255.", "split": "train" }
from collections import deque def custom_top_sort(graph: dict) -> list: if not graph: print("Graph contains a cycle") return [] in_degree = {node: 0 for node in graph} # Calculate in-degrees for u in graph: for v in graph[u]: in_degree[v] += 1 queue = d...
simplelr_Data_Structure
[ { "content": "Question:\n### Topological Sorting with Custom Cycle Handling\n\n#### Objective\nYour task is to implement a function that performs a topological sort on a given directed acyclic graph (DAG) and handles graphs with cycles by returning an appropriate message.\n\n#### Function Signature\n```python\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6467, "level": 1, "question": "### Topological Sorting with Custom Cycle Handling\n\n#### Objective\nYour task is to implement a function that performs a topological sort on a given directed acyclic graph (DAG) and handles graphs with cycles by returning an appropriate message.\n\n#...
def count_even_numbers(nums): return sum(1 for num in nums if num % 2 == 0)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to count the number of even numbers in a given list of integers. The function should return a count of even numbers within the list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6468, "level": 1, "question": "Write a python function to count the number of even numbers in a given list of integers. The function should return a count of even numbers within the list.", "split": "train" }
import math def num_digits(n: int) -> int: if n == 0: return 1 n_abs = abs(n) log_value = math.log10(n_abs) return int(math.floor(log_value)) + 1
simplelr_Data_Structure
[ { "content": "Question:\nYou are required to implement a function that determines the number of digits in an integer. The function should operate in constant time and handle both positive and negative integers as well as zero. Please follow the method described below:\n\n### Function Signature\n```python\ndef n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6469, "level": 1, "question": "You are required to implement a function that determines the number of digits in an integer. The function should operate in constant time and handle both positive and negative integers as well as zero. Please follow the method described below:\n\n### F...
def largest_element(matrix): return max(max(row) for row in matrix)
simplelr_Algorithm
[ { "content": "Question:\n### Question: Largest Element in a Matrix\n\nGiven a matrix of integers, implement a function to find the largest element in the matrix. Your solution should efficiently traverse the matrix and return the maximum value found.\n\n#### Input\n* A 2D list `matrix` where each element is an ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6470, "level": 1, "question": "### Question: Largest Element in a Matrix\n\nGiven a matrix of integers, implement a function to find the largest element in the matrix. Your solution should efficiently traverse the matrix and return the maximum value found.\n\n#### Input\n* A 2D list...
def longest_subsequence_with_diff(arr, k): n = len(arr) if n == 0: return (0, []) dp = [1] * n prev = [-1] * n for i in range(n): for j in range(i): if arr[i] - arr[j] == k: if dp[j] + 1 > dp[i]: dp[i] = dp[j] + 1 ...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `arr`, find a subsequence of array `arr` such that the difference between adjacent elements of the subsequence is exactly `k`. The subsequence should be as long as possible and among all possible such subsequences, return the one that appears first in the orig...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6471, "level": 1, "question": "Given an array of integers `arr`, find a subsequence of array `arr` such that the difference between adjacent elements of the subsequence is exactly `k`. The subsequence should be as long as possible and among all possible such subsequences, return the...
def categorize_words_by_length(words): length_dict = {} for word in words: length = len(word) if length in length_dict: length_dict[length].append(word) else: length_dict[length] = [word] return length_dict
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes as input a list of words and returns a dictionary where the keys are the lengths of the words, and the values are lists containing the words of that length. For example, given the list `[\"apple\", \"banana\", \"pear\", \"kiwi\", \"grape\"]`, the function sho...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6472, "level": 1, "question": "Write a function that takes as input a list of words and returns a dictionary where the keys are the lengths of the words, and the values are lists containing the words of that length. For example, given the list `[\"apple\", \"banana\", \"pear\", \"ki...
def square_and_sort(lst): return sorted([x ** 2 for x in lst])
simplelr_Taco
[ { "content": "Question:\nYou are given a list of integers, which may include both positive and negative numbers. Your task is to return a new list that contains the squares of each integer, sorted in non-decreasing order.\n\nWrite a function that receives this list of integers and outputs the sorted list of squ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6473, "level": 1, "question": "You are given a list of integers, which may include both positive and negative numbers. Your task is to return a new list that contains the squares of each integer, sorted in non-decreasing order.\n\nWrite a function that receives this list of integers...
import os from os.path import splitext def count_file_types(directory_path: str) -> dict: file_counts = {} for root, dirs, files in os.walk(directory_path): for filename in files: _, ext = splitext(filename) if ext: if ext in file_counts: file...
simplelr_Algorithm
[ { "content": "Question:\n### Recursive Directory Listing with File Type Counting\n\nImplement a program that traverses a directory structure recursively and counts the occurrences of different file types. The file type is determined by the file extension. You should return a dictionary where the keys are the fi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6474, "level": 1, "question": "### Recursive Directory Listing with File Type Counting\n\nImplement a program that traverses a directory structure recursively and counts the occurrences of different file types. The file type is determined by the file extension. You should return a d...
from collections import defaultdict def find_shortest_unique_substring(s, charset): if not s or not charset: return "" required = defaultdict(int) for c in charset: required[c] += 1 required_chars = set(required.keys()) s_chars = set(s) if not required_chars.issubset(s...
simplelr_Package
[ { "content": "Question:\nWrite a function named `find_shortest_unique_substring` that takes two parameters: a string `s` and a string `charset`. The function should return the shortest substring of `s` that contains all the characters in `charset` at least once. If no such substring exists, return an empty stri...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6475, "level": 1, "question": "Write a function named `find_shortest_unique_substring` that takes two parameters: a string `s` and a string `charset`. The function should return the shortest substring of `s` that contains all the characters in `charset` at least once. If no such sub...
def is_anagram(s: str, t: str) -> bool: if len(s) != len(t): return False counts = [0] * 26 # One for each letter a-z for char in s: counts[ord(char) - ord('a')] += 1 for char in t: index = ord(char) - ord('a') if counts[index] == 0: return Fal...
simplelr_Data_Structure
[ { "content": "Question:\n**Problem Statement:**\n\nImplement a function `is_anagram` that takes two strings `s` and `t` as input and returns `True` if `t` is an anagram of `s`, and `False` otherwise. An anagram of a string is another string that contains the same characters, only the order of characters can be ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6476, "level": 1, "question": "**Problem Statement:**\n\nImplement a function `is_anagram` that takes two strings `s` and `t` as input and returns `True` if `t` is an anagram of `s`, and `False` otherwise. An anagram of a string is another string that contains the same characters, o...
def spiralOrder(matrix): if not matrix: return [] rows = len(matrix) cols = len(matrix[0]) result = [] row_start, row_end = 0, rows - 1 col_start, col_end = 0, cols - 1 while row_start <= row_end and col_start <= col_end: # Traverse from left to right on the top row ...
simplelr_Filter
[ { "content": "Question:\nThe following code prints all the elements of a matrix (2D array) in a spiral order.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6477, "level": 1, "question": "The following code prints all the elements of a matrix (2D array) in a spiral order.", "split": "train" }
def cocktail_shaker_sort(arr: list[int]) -> list[int]: if len(arr) <= 1: return arr start = 0 end = len(arr) - 1 while start < end: # Left to right pass swapped = False for i in range(start, end): if arr[i] > arr[i + 1]: arr[i], arr[i...
simplelr_Data_Structure
[ { "content": "Question:\n### Coding Task\n\nImplement a function using Cocktail Shaker Sort to sort a list of integers in ascending order. The function should handle various edge cases and include optimization for early termination if the array becomes sorted before completing all passes.\n\n#### Function Signa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6478, "level": 1, "question": "### Coding Task\n\nImplement a function using Cocktail Shaker Sort to sort a list of integers in ascending order. The function should handle various edge cases and include optimization for early termination if the array becomes sorted before completing...
def longest_subarray_with_two_distinct(arr): count = {} max_len = 0 left = 0 for right in range(len(arr)): num = arr[right] if num in count: count[num] += 1 else: count[num] = 1 # Ensure the window contains at most two distinct numbers whil...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers, `arr`, of size `n`, you need to determine the **length** of the **longest contiguous subarray** that contains **at most two distinct numbers**. \n\nReturn the length of this subarray.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6479, "level": 1, "question": "Given an array of integers, `arr`, of size `n`, you need to determine the **length** of the **longest contiguous subarray** that contains **at most two distinct numbers**. \n\nReturn the length of this subarray.", "split": "train" }
def reverse_string(s): return s[::-1]
simplelr_Filter
[ { "content": "Question:\nI need help writing a function in Python to reverse the characters in a string. Can you provide a simple example?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6480, "level": 1, "question": "I need help writing a function in Python to reverse the characters in a string. Can you provide a simple example?", "split": "train" }
def sort_words(sentence): return ' '.join(sorted(sentence.split(), key=str.lower))
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to sort words in a given sentence alphabetically.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6481, "level": 1, "question": "Write a python function to sort words in a given sentence alphabetically.", "split": "train" }
def parse_student_records(records: list) -> dict: result = { "Excellent": [], "Good": [], "Average": [], "Needs Improvement": [], "Invalid": [] } for record in records: name = record['name'] if 'grade' not in record: result["Invalid"].appe...
simplelr_Docs
[ { "content": "Question:\nAdvanced Pattern Matching with Python 3.10\n\n#### Objective:\nAssess students' understanding of pattern matching (a new feature in Python 3.10) along with function implementation and structured data extraction.\n\n#### Problem Statement:\nYou are required to implement a function `parse...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6482, "level": 1, "question": "Advanced Pattern Matching with Python 3.10\n\n#### Objective:\nAssess students' understanding of pattern matching (a new feature in Python 3.10) along with function implementation and structured data extraction.\n\n#### Problem Statement:\nYou are requ...
def rearrangeWithReverses(arr, k): result = [] for i in range(0, len(arr), k): chunk = arr[i:i+k] if len(chunk) == k: result += chunk result += chunk[::-1] else: result += chunk return result
simplelr_Codeforces
[ { "content": "Question:\nGiven an array of integers `arr` and an integer `k`, rearrange the array in such a way that subarrays of size `k` and their reverse counterparts are present adjacent to each other. \n\nMore formally, you need to split the array into as many subarrays of size `k` as possible and for each...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6483, "level": 1, "question": "Given an array of integers `arr` and an integer `k`, rearrange the array in such a way that subarrays of size `k` and their reverse counterparts are present adjacent to each other. \n\nMore formally, you need to split the array into as many subarrays o...
def unique_paths(m: int, n: int) -> int: a = m + n - 2 b = min(m - 1, n - 1) result = 1 for i in range(1, b + 1): result = result * (a - b + i) // i return result
simplelr_Leetcode
[ { "content": "Question:\nA **unique-path** grid is an m x n grid where you can only move to the right or down from each cell. Given two integers m and n, representing the dimensions of the grid, return the number of unique paths from the top-left corner to the bottom-right corner. Every move must only go to the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6484, "level": 1, "question": "A **unique-path** grid is an m x n grid where you can only move to the right or down from each cell. Given two integers m and n, representing the dimensions of the grid, return the number of unique paths from the top-left corner to the bottom-right cor...
import numpy as np from sklearn.datasets import load_wine from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, classification_report def wine_classification(): # Load the...
simplelr_Docs
[ { "content": "Question:\n## Coding Assessment Question: Wine Classification with scikit-learn\n\nIn this assignment, you will demonstrate your understanding of scikit-learn by building a classification model using the Wine dataset. You will load the dataset, preprocess it, split it into training and testing set...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6485, "level": 1, "question": "## Coding Assessment Question: Wine Classification with scikit-learn\n\nIn this assignment, you will demonstrate your understanding of scikit-learn by building a classification model using the Wine dataset. You will load the dataset, preprocess it, spl...
import token def analyze_tokens(token_list): """ Analyzes a list of token values and returns a dictionary with specific information. Parameters: token_list (list of int): A list of numeric token values. Returns: dict: A dictionary containing: - "human_readable" (list of str): List o...
simplelr_Docs
[ { "content": "Question:\n### Token Analysis and Conversion\n\nThe `token` module in Python provides a set of constants that represent various elements of Python's grammar and parse tree. In this assessment, you will demonstrate your understanding of this module by implementing a function that processes a list o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6486, "level": 1, "question": "### Token Analysis and Conversion\n\nThe `token` module in Python provides a set of constants that represent various elements of Python's grammar and parse tree. In this assessment, you will demonstrate your understanding of this module by implementing...
import itertools def generate_combinations(lst): result = [] for r in range(len(lst) + 1): result.extend(itertools.combinations(lst, r)) return result
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to generate all possible combinations of a given list, including the empty set and the list itself. This function should return all combinations in ascending order of their lengths.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6487, "level": 1, "question": "Write a python function to generate all possible combinations of a given list, including the empty set and the list itself. This function should return all combinations in ascending order of their lengths.", "split": "train" }
from typing import List def quick_sort(arr: List[int]) -> List[int]: if len(arr) <= 1: return arr pivot = arr[-1] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort(left) + middle + quick_sort(right)
simplelr_Algorithm
[ { "content": "Question:\n### Context\nSorting algorithms are fundamental for various computer science applications, including search optimization, database algorithms, and more. Understanding and implementing these algorithms can enhance problem-solving efficiency.\n\n### Problem Statement\nIn this task, you ne...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6488, "level": 1, "question": "### Context\nSorting algorithms are fundamental for various computer science applications, including search optimization, database algorithms, and more. Understanding and implementing these algorithms can enhance problem-solving efficiency.\n\n### Prob...
def find_pairs(nums, target): sorted_nums = sorted(nums) pairs = set() n = len(sorted_nums) for i in range(n): for j in range(i + 1, n): a = sorted_nums[i] b = sorted_nums[j] if a + b == target: pairs.add((a, b)) result = sorted(pairs) ...
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a list of integers and a target integer. The function should return all unique pairs of integers from the list that add up to the target. A pair is defined as a tuple of two different numbers such that their sum equals the target.\n\nYour function should avoi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6489, "level": 1, "question": "Write a function that takes a list of integers and a target integer. The function should return all unique pairs of integers from the list that add up to the target. A pair is defined as a tuple of two different numbers such that their sum equals the t...
def generatePattern(N): return ['*' * i + ' ' * (N - i) for i in range(1, N + 1)]
simplelr_Taco
[ { "content": "Question:\nGiven an integer N, generate a pattern of asterisks and spaces in the shape of a right-angled triangle. The triangle should have N rows, where the i-th row contains i asterisks and (N-i) spaces.\n\nExample 1: \nInput: N = 3 \nOutput: \n`* ` \n`** ` \n`***` \n\nExample 2: \nInput...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6490, "level": 1, "question": "Given an integer N, generate a pattern of asterisks and spaces in the shape of a right-angled triangle. The triangle should have N rows, where the i-th row contains i asterisks and (N-i) spaces.\n\nExample 1: \nInput: N = 3 \nOutput: \n`* ` \n`** ...
def list_to_dict_with_length(lst): result = {} counts = {} for s in lst: if s in counts: count = counts[s] key = f"{s}_{count}" counts[s] += 1 else: key = s counts[s] = 1 result[key] = len(s) return result
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python function that converts a list of strings into a dictionary, where each string in the list is a key and the value is the length of the string? If the list contains duplicate strings, the function should handle them appropriately by appending a suffix to the dupli...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6491, "level": 1, "question": "Can you provide a Python function that converts a list of strings into a dictionary, where each string in the list is a key and the value is the length of the string? If the list contains duplicate strings, the function should handle them appropriately...
def sum_of_squares(n): total = 0 for i in range(1, n + 1): total += i ** 2 print(total) return total
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to calculate the sum of squares for the first 'n' natural numbers and then print the result.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6492, "level": 1, "question": "Write a python function to calculate the sum of squares for the first 'n' natural numbers and then print the result.", "split": "train" }
def max_sum_subarray(nums, k): if not nums or k == 0: return 0 n = len(nums) if k > n: return 0 current_sum = sum(nums[:k]) max_sum = current_sum for i in range(1, n - k + 1): current_sum = current_sum - nums[i - 1] + nums[i + k - 1] if current_sum > max_sum: ...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that computes the maximum sum of a subarray of a given size `k` from an array of integers. The function should take two parameters: a list of integers `nums` and an integer `k` representing the size of the subarray. The function should return the maximum sum that...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6493, "level": 1, "question": "Write a Python function that computes the maximum sum of a subarray of a given size `k` from an array of integers. The function should take two parameters: a list of integers `nums` and an integer `k` representing the size of the subarray. The function...
def sort_numbers(numbers): return sorted(numbers)
simplelr_Filter
[ { "content": "Question:\nYou've been tasked with sorting a list of numbers in ascending order. Write a Python function to accomplish this task.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6494, "level": 1, "question": "You've been tasked with sorting a list of numbers in ascending order. Write a Python function to accomplish this task.", "split": "train" }
def list_sum(numbers): return sum(numbers)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in a list of numbers and returns their sum. Let's say I have a list of numbers and I want to get their total sum. How would I do that in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6495, "level": 1, "question": "Create a function that takes in a list of numbers and returns their sum. Let's say I have a list of numbers and I want to get their total sum. How would I do that in Python?", "split": "train" }
import math def factorial_digit_sum(n: int) -> int: factorial_result = math.factorial(n) digit_sum = sum(int(digit) for digit in str(factorial_result)) return digit_sum
simplelr_Algorithm
[ { "content": "Question:\n### Factorial Digit Sum\n\nAs part of an interview for a role in a mathematical software company, you are tasked with solving a problem that involves both mathematical computation and optimization. Your interviewer wants you to write a function that calculates the sum of the digits of t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6496, "level": 1, "question": "### Factorial Digit Sum\n\nAs part of an interview for a role in a mathematical software company, you are tasked with solving a problem that involves both mathematical computation and optimization. Your interviewer wants you to write a function that ca...
def rearrange_even_odd(nums): evens = [] odds = [] for num in nums: if num % 2 == 0: evens.append(num) else: odds.append(num) return evens + odds
simplelr_Apps
[ { "content": "Question:\nYou are given an integer array `nums`. Your task is to rearrange the elements such that all even numbers are at the beginning of the array followed by all odd numbers. The relative order of the even and odd numbers should remain the same as in the original array.\n\n- Input:\n - An a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6497, "level": 1, "question": "You are given an integer array `nums`. Your task is to rearrange the elements such that all even numbers are at the beginning of the array followed by all odd numbers. The relative order of the even and odd numbers should remain the same as in the orig...
def coin_change(coins, amount): if amount == 0: return 0 dp = [float('inf')] * (amount + 1) dp[0] = 0 for i in range(1, amount + 1): for coin in coins: if coin <= i: dp[i] = min(dp[i], dp[i - coin] + 1) return dp[amount] if dp[amount] != float('inf') else ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array `arr` of positive integers and an integer `amount`. Each element in `arr` represents a different coin denomination. You need to determine the **fewest number of coins** needed to make up the given `amount`. If that amount of money cannot be made up by any combinat...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6498, "level": 1, "question": "You are given an array `arr` of positive integers and an integer `amount`. Each element in `arr` represents a different coin denomination. You need to determine the **fewest number of coins** needed to make up the given `amount`. If that amount of mone...
def infix_to_postfix(expression): output = [] stack = [] operators = { '^': {'prec': 4, 'assoc': 'right'}, '*': {'prec': 3, 'assoc': 'left'}, '/': {'prec': 3, 'assoc': 'left'}, '+': {'prec': 2, 'assoc': 'left'}, '-': {'prec': 2, 'assoc': 'left'} } tokens ...
simplelr_Filter
[ { "content": "Question:\nWrite a Python program that converts an infix expression to a postfix expression using the Shunting Yard algorithm. Make sure to handle operators with different precedence and associativity, and support parentheses for grouping. The program should also be able to handle single-digit num...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6499, "level": 1, "question": "Write a Python program that converts an infix expression to a postfix expression using the Shunting Yard algorithm. Make sure to handle operators with different precedence and associativity, and support parentheses for grouping. The program should also...