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 webbrowser def open_multiple_urls(urls: list, new_window: bool = False) -> None: for url in urls: new_parameter = 1 if new_window else 2 try: webbrowser.open(url, new=new_parameter) except Exception as e: print(f"Error opening {url}: {str(e)}")
simplelr_Docs
[ { "content": "Question:\n#### Objective:\nUse the `webbrowser` module to create a function that accepts a list of URLs and automates opening them in specific ways.\n\n#### Problem Statement:\nWrite a Python function called `open_multiple_urls` that takes the following parameters:\n\n- `urls`: A list of URLs (st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7100, "level": 1, "question": "#### Objective:\nUse the `webbrowser` module to create a function that accepts a list of URLs and automates opening them in specific ways.\n\n#### Problem Statement:\nWrite a Python function called `open_multiple_urls` that takes the following paramete...
from collections import deque def min_subarray_len(arr, threshold): n = len(arr) if n == 0: return -1 # Handle empty array case if necessary as per problem constraints # Compute prefix sum array prefix_sum = [0] * (n + 1) for i in range(1, n + 1): prefix_sum[i] = prefix_sum[i ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of `n` integers, `arr`, and an integer `threshold`. Your task is to find the length of the smallest contiguous subarray of `arr` such that the sum of its elements is at least `threshold`. If no such subarray exists, return `-1`.\nAnswer:\nLet's think step by step.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7101, "level": 1, "question": "You are given a list of `n` integers, `arr`, and an integer `threshold`. Your task is to find the length of the smallest contiguous subarray of `arr` such that the sum of its elements is at least `threshold`. If no such subarray exists, return `-1`.", ...
import fnmatch def filter_filenames(filenames: list, include_pattern: str, exclude_pattern: str) -> list: result = [] for filename in filenames: include_match = fnmatch.fnmatch(filename, include_pattern) exclude_match = fnmatch.fnmatch(filename, exclude_pattern) if include_match and not...
simplelr_Docs
[ { "content": "Question:\n### Pattern Matching and Filtering with `fnmatch`\n\nYou are required to implement a function that takes a list of filenames and a pattern, and returns a list of filenames that match the pattern, excluding those that match an exclusion pattern. Your function should use the `fnmatch` mod...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7102, "level": 1, "question": "### Pattern Matching and Filtering with `fnmatch`\n\nYou are required to implement a function that takes a list of filenames and a pattern, and returns a list of filenames that match the pattern, excluding those that match an exclusion pattern. Your fu...
def process_operations(ops): s = [] for op in ops: typ, idx, char = op[0], op[1], op[2] if typ == 1: if idx > len(s): s.append(char) else: s.insert(idx, char) elif typ == 2: if idx < len(s): del s[idx] ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array representing a sequence of operations involving a single string. Each operation is represented as `ops[i] = [type, index, char]`, where:\n\n- `type` can be either `1` or `2`. If it is `1`, it indicates an insertion operation, and if it is `2`, it indicates a delet...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7103, "level": 1, "question": "You are given an array representing a sequence of operations involving a single string. Each operation is represented as `ops[i] = [type, index, char]`, where:\n\n- `type` can be either `1` or `2`. If it is `1`, it indicates an insertion operation, and...
from typing import List def remove_duplicates_and_sort(numbers: List[int]) -> List[int]: return sorted(set(numbers))
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nImplement a function `remove_duplicates_and_sort` that takes a list of integers, removes any duplicate elements, and returns a new list containing the sorted unique integers.\n\n### Requirements\n\n1. **Function Signature**: \n ```python\n def remove_dupli...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7104, "level": 1, "question": "### Problem Statement\n\nImplement a function `remove_duplicates_and_sort` that takes a list of integers, removes any duplicate elements, and returns a new list containing the sorted unique integers.\n\n### Requirements\n\n1. **Function Signature**: \n...
import math def cosine_similarity(vector_a, vector_b): if len(vector_a) != len(vector_b): raise ValueError("Vectors must be of the same length.") dot_product = sum(a * b for a, b in zip(vector_a, vector_b)) magnitude_a = math.sqrt(sum(a**2 for a in vector_a)) magnitude_b = math.sqrt(s...
simplelr_Filter
[ { "content": "Question:\nCould you provide a more detailed explanation of how to implement the cosine similarity calculation in Python, including any necessary libraries and code snippets?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7105, "level": 1, "question": "Could you provide a more detailed explanation of how to implement the cosine similarity calculation in Python, including any necessary libraries and code snippets?", "split": "train" }
def merge_sorted_lists(list1, list2): i = 0 j = 0 result = [] while i < len(list1) and j < len(list2): if list1[i] <= list2[j]: result.append(list1[i]) i += 1 else: result.append(list2[j]) j += 1 # Add remaining elements from list1, if ...
simplelr_Algorithm
[ { "content": "Question:\nMerging Two Sorted Lists\n\nYou are required to implement a function that merges two given sorted lists into a single sorted list. The input lists are sorted in ascending order and may contain both integers and floating-point numbers. Your job is to ensure the merged list is also sorted...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7106, "level": 1, "question": "Merging Two Sorted Lists\n\nYou are required to implement a function that merges two given sorted lists into a single sorted list. The input lists are sorted in ascending order and may contain both integers and floating-point numbers. Your job is to en...
import itertools def generate_subsets(nums: list[int]) -> set[tuple[int]]: subsets = set() for r in range(len(nums) + 1): for subset in itertools.combinations(nums, r): subsets.add(subset) return subsets
simplelr_Data_Structure
[ { "content": "Question:\n### Question: Generate All Subsets of a Set\n\nYou are given a list of distinct integers. Your task is to write a function `generate_subsets` that returns all possible subsets of these integers.\n\n### Function Signature:\n```python\ndef generate_subsets(nums: List[int]) -> Set[Tuple[in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7107, "level": 1, "question": "### Question: Generate All Subsets of a Set\n\nYou are given a list of distinct integers. Your task is to write a function `generate_subsets` that returns all possible subsets of these integers.\n\n### Function Signature:\n```python\ndef generate_subse...
def maximum_sum_subarray(arr): if not arr: return 0 max_current = max_global = arr[0] for num in arr[1:]: max_current = max(num, max_current + num) if max_current > max_global: max_global = max_current return max_global
simplelr_Prefill
[ { "content": "Question:\nWrite a function to implement the algorithm thatachieves the maximum sum subarray problem. Explain the key steps of the algorithm.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7108, "level": 1, "question": "Write a function to implement the algorithm thatachieves the maximum sum subarray problem. Explain the key steps of the algorithm.", "split": "train" }
from typing import List def find_first_occurrence(nums: List[int], target: int) -> int: low = 0 high = len(nums) - 1 result = -1 while low <= high: mid = (low + high) // 2 if nums[mid] == target: result = mid high = mid - 1 # Continue searching left for earlier ...
simplelr_Data_Structure
[ { "content": "Question:\n#### Context\nYou are given a sorted array of integers in increasing order. Your task is to find the index of the first occurrence of a given target value in this array using an efficient search method. This is a common problem in settings where large amounts of sorted data need to be s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7109, "level": 1, "question": "#### Context\nYou are given a sorted array of integers in increasing order. Your task is to find the index of the first occurrence of a given target value in this array using an efficient search method. This is a common problem in settings where large ...
def most_frequent_character(s): if not s: return '' char_count = {} for char in s: if char in char_count: char_count[char] += 1 else: char_count[char] = 1 max_count = 0 result = s[0] for char, count in char_count.items(): if count > max_cou...
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes a string as input and returns the most frequent character in the string. In case of a tie, return the character that appears first in the string.\ninput_string = \"programming\"\noutput = \"g\"\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7110, "level": 1, "question": "Write a function that takes a string as input and returns the most frequent character in the string. In case of a tie, return the character that appears first in the string.\ninput_string = \"programming\"\noutput = \"g\"", "split": "train" }
def is_anagram(str1, str2): return sorted(str1) == sorted(str2)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function `is_anagram` that checks if two given strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Your function should be case-sensitive...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7111, "level": 1, "question": "Write a Python function `is_anagram` that checks if two given strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. You...
def intersection_of_sorted_lists(list1, list2): i = j = 0 result = [] while i < len(list1) and j < len(list2): if list1[i] == list2[j]: result.append(list1[i]) i += 1 j += 1 elif list1[i] < list2[j]: i += 1 else: j += 1 ...
simplelr_Filter
[ { "content": "Question:\nGiven two sorted lists, write a function to return a new list containing the elements that are present in both lists. Do not use set data structure or built-in Python function for this problem.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7112, "level": 1, "question": "Given two sorted lists, write a function to return a new list containing the elements that are present in both lists. Do not use set data structure or built-in Python function for this problem.", "split": "train" }
from collections import deque def shortest_distance(matrix): if not matrix: return -1 rows = len(matrix) cols = len(matrix[0]) if rows > 0 else 0 if rows == 0 or cols == 0: return -1 distance = [[float('inf')] * cols for _ in range(rows)] queue = deque() for i...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the shortest distance from any cell of the matrix with value 0 to any cell of the matrix with value 1. Each cell has a path with weight 1 in the matrix.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7113, "level": 1, "question": "Write a python function to find the shortest distance from any cell of the matrix with value 0 to any cell of the matrix with value 1. Each cell has a path with weight 1 in the matrix.", "split": "train" }
def first_non_repeating_character(s): if not s: return None counts = {} for char in s: counts[char] = counts.get(char, 0) + 1 for char in s: if counts[char] == 1: return char return None
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the first Non-repeating character in a String. Your function should return null if every character in the string is repeating. For example, if input string is 'AsString', output should be 'A' because 'A' is the first character that does not repeat and app...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7114, "level": 1, "question": "Write a python function to find the first Non-repeating character in a String. Your function should return null if every character in the string is repeating. For example, if input string is 'AsString', output should be 'A' because 'A' is the first cha...
def sum_above_threshold(numbers, threshold): return sum(num for num in numbers if num > threshold)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to calculate the sum of all elements in a list of numbers, but only for those numbers that are greater than a specified threshold.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7115, "level": 1, "question": "Write a python function to calculate the sum of all elements in a list of numbers, but only for those numbers that are greater than a specified threshold.", "split": "train" }
import seaborn.objects as so from seaborn import load_dataset def create_custom_bar_plot(): # Load the tips dataset tips = load_dataset("tips") # Create a Plot object with day on the x-axis plot = so.Plot(tips, x="day") # Add a bar layer, count statistic, and dodge by sex plot = plot.add(so.B...
simplelr_Docs
[ { "content": "Question:\n**Coding Assessment Question**\n\nIn this assessment, your goal is to demonstrate your understanding of fundamental and advanced concepts of the `seaborn` package, particularly using the `seaborn.objects` module. You will be required to create a customized bar plot using the `tips` data...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7116, "level": 1, "question": "**Coding Assessment Question**\n\nIn this assessment, your goal is to demonstrate your understanding of fundamental and advanced concepts of the `seaborn` package, particularly using the `seaborn.objects` module. You will be required to create a custom...
def append_lists(a, b): a.extend(b) return a
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to append all elements of list 'b' to the end of list 'a'.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7117, "level": 1, "question": "Write a python function to append all elements of list 'b' to the end of list 'a'.", "split": "train" }
from collections import defaultdict def max_sum_subarray_with_n_distinct(arr, n): if not arr or n == 0: return 0 left = 0 sum_current = 0 max_sum = float('-inf') freq = defaultdict(int) distinct = 0 for right in range(len(arr)): num = arr[right] freq[num] +...
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `arr` and an integer `n`, return the maximum possible sum of a subarray with at most `n` distinct elements. If there are multiple subarrays with the same maximum sum, return the sum of any one of them. A subarray is a contiguous part of the array.\nAnswer:\nLet's ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7118, "level": 1, "question": "Given an integer array `arr` and an integer `n`, return the maximum possible sum of a subarray with at most `n` distinct elements. If there are multiple subarrays with the same maximum sum, return the sum of any one of them. A subarray is a contiguous ...
def reverse_words(s): return ' '.join(reversed(s.split()))
simplelr_Prefill
[ { "content": "Question:\nWrite a function to reverse the words in a given string `s`. The function should take a single parameter `s`, which is a string, and return the reversed word count. Additionally, the function should ignore leading, trailing, and multiple spaces between words.\nAnswer:\nLet's think step ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7119, "level": 1, "question": "Write a function to reverse the words in a given string `s`. The function should take a single parameter `s`, which is a string, and return the reversed word count. Additionally, the function should ignore leading, trailing, and multiple spaces between...
def average(numbers): if not numbers: return 0 return sum(numbers) / len(numbers)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers as input and returns the average of all the elements in the list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7120, "level": 1, "question": "Create a function that takes a list of integers as input and returns the average of all the elements in the list.", "split": "train" }
def hailstone_length(n: int) -> int: length = 1 current = n while current != 1: if current % 2 == 0: current = current // 2 else: current = 3 * current + 1 length += 1 return length
simplelr_Data_Structure
[ { "content": "Question:\n### Question: Hailstone Sequence Length\n\nGiven the starting point `n` of a hailstone sequence as described in the algorithm, implement a function `hailstone_length(n)` that returns the length of the hailstone sequence (including the initial `n` and the final `1`).\n\n#### Function Sig...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7121, "level": 1, "question": "### Question: Hailstone Sequence Length\n\nGiven the starting point `n` of a hailstone sequence as described in the algorithm, implement a function `hailstone_length(n)` that returns the length of the hailstone sequence (including the initial `n` and t...
def reverse_words_in_string(s: str) -> str: words = s.split() reversed_words = [word[::-1] for word in words] return ' '.join(reversed_words)
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are given a string that contains alphanumeric characters and spaces. The goal is to reverse each word individually while keeping the words' order intact. Whitespace should be maintained as they are between words, but no leading or trailing spaces exist in th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7122, "level": 1, "question": "### Problem Statement\n\nYou are given a string that contains alphanumeric characters and spaces. The goal is to reverse each word individually while keeping the words' order intact. Whitespace should be maintained as they are between words, but no lea...
from typing import List def limit_identifiers(lst: List[int], N: int) -> List[int]: if N == 0: return [] counts = {} result = [] for num in lst: if num in counts: if counts[num] < N: result.append(num) counts[num] += 1 else: ...
simplelr_Data_Structure
[ { "content": "Question:\n### Question\n\n**Context**: You are tasked with designing a system that processes a list of identifiers received from different sources. Each identifier should not appear more than a specified number of times in the final processed list. The order of identifiers must be preserved.\n\n*...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7123, "level": 1, "question": "### Question\n\n**Context**: You are tasked with designing a system that processes a list of identifiers received from different sources. Each identifier should not appear more than a specified number of times in the final processed list. The order of ...
def sieve_of_eratosthenes(n): if n <= 2: return [] sieve = [True] * n sieve[0], sieve[1] = False, False for i in range(2, int(n**0.5) + 1): if sieve[i]: for j in range(i * i, n, i): sieve[j] = False primes = [i for i, is_prime in enumerate(sieve) if is_pri...
simplelr_Taco
[ { "content": "Question:\nWrite a program that takes an integer value `n` and returns a list of all prime numbers less than `n`. A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. The function should be efficient for large values of `n`.\n\nFor example, if the input ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7124, "level": 1, "question": "Write a program that takes an integer value `n` and returns a list of all prime numbers less than `n`. A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. The function should be efficient for large values of...
def remove_duplicates(input_list): seen = set() result = [] for element in input_list: if element not in seen: seen.add(element) result.append(element) return result
simplelr_Prefill
[ { "content": "Question:\nWrite a function to remove all duplicate elements from a list while preserving the original order of the elements. You should ensure that your solution is efficient in terms of both time and space complexity.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7125, "level": 1, "question": "Write a function to remove all duplicate elements from a list while preserving the original order of the elements. You should ensure that your solution is efficient in terms of both time and space complexity.", "split": "train" }
import numpy as np def process_coordinates(coord_array, transformation_function): """ Applies a transformation function to each coordinate set in a 3D NumPy array. Args: coord_array (numpy.ndarray): A 3D NumPy array where the last dimension represents (x, y, z) coordinates. transformation_...
simplelr_Filter
[ { "content": "Question:\nDesign a Python function `process_coordinates` that processes a batch of 3D coordinate sets, applying a given transformation function to each coordinate in the sets. The input is a 3D NumPy array where the last dimension represents coordinates (x, y, z), and a transformation function th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7126, "level": 1, "question": "Design a Python function `process_coordinates` that processes a batch of 3D coordinate sets, applying a given transformation function to each coordinate in the sets. The input is a 3D NumPy array where the last dimension represents coordinates (x, y, z...
def highest_scores(arr): first_max = 0 second_max = 0 for num in arr: if num > first_max: second_max = first_max first_max = num elif num > second_max: second_max = num return (first_max, second_max, first_max + second_max)
simplelr_Taco
[ { "content": "Question:\n# Introduction\n\nYou are given an array of unique integers where each integer is between 1 and 100 (inclusive), and the length of the array is less than 100. The integers represent the scores of participants in a competition.\n\n# Task:\nWrite a function that takes this array as input ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7127, "level": 1, "question": "# Introduction\n\nYou are given an array of unique integers where each integer is between 1 and 100 (inclusive), and the length of the array is less than 100. The integers represent the scores of participants in a competition.\n\n# Task:\nWrite a funct...
def maxNonAdjacentSum(nums): if not nums: return 0 prev_inc = 0 prev_exc = 0 for num in nums: current_inc = prev_exc + num current_exc = max(prev_inc, prev_exc) prev_inc, prev_exc = current_inc, current_exc return max(prev_inc, prev_exc)
simplelr_Taco
[ { "content": "Question:\nGiven an integer array nums of size n, return the maximum sum you can obtain by removing non-adjacent elements from the array. You may assume all elements are non-negative.\n\nExample 1:\nInput: nums = [3, 2, 5, 10, 7]\nOutput: 15\nExplanation: You can remove 3, 10 and 2 or 5 and 10\n\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7128, "level": 1, "question": "Given an integer array nums of size n, return the maximum sum you can obtain by removing non-adjacent elements from the array. You may assume all elements are non-negative.\n\nExample 1:\nInput: nums = [3, 2, 5, 10, 7]\nOutput: 15\nExplanation: You can...
def reverse_stack(s): s_aux = [] while s: x = s.pop() while s_aux: y = s_aux.pop() s.append(y) s_aux.append(x) while s: y = s.pop() s_aux.append(y) return s_aux
simplelr_Prefill
[ { "content": "Question:\nWrite a function to reverse a stack using exactly one additional stack. You are not allowed to use any other data structures.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7129, "level": 1, "question": "Write a function to reverse a stack using exactly one additional stack. You are not allowed to use any other data structures.", "split": "train" }
def reverse_string(s): s_list = list(s) s_list.reverse() return ''.join(s_list)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to reverse a string without using additional data structures. reorder the string in-place.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7130, "level": 1, "question": "Write a python function to reverse a string without using additional data structures. reorder the string in-place.", "split": "train" }
import heapq def dijkstra_shortest_path(matrix, source, destination): n = len(matrix) if source == destination: return 0 distances = [float('inf')] * n distances[source] = 0 heap = [] heapq.heappush(heap, (0, source)) while heap: current_dist, u = heapq.heappo...
simplelr_Leetcode
[ { "content": "Question:\nGiven a matrix of dimensions `n x n` representing the connections in an undirected, weighted graph, where `matrix[i][j]` contains the weight of the edge between nodes `i` and `j`, and `matrix[i][j] = 0` indicates no direct edge exists between node `i` and node `j`. Design an algorithm t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7131, "level": 1, "question": "Given a matrix of dimensions `n x n` representing the connections in an undirected, weighted graph, where `matrix[i][j]` contains the weight of the edge between nodes `i` and `j`, and `matrix[i][j] = 0` indicates no direct edge exists between node `i` ...
def contains_nearby_duplicate(nums, k): last_occurrence = {} for i in range(len(nums)): num = nums[i] if num in last_occurrence: if i - last_occurrence[num] <= k: return True last_occurrence[num] = i return False
simplelr_Apps
[ { "content": "Question:\nGiven an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.\n\nExample 1:\nInput: nums = [1,2,3,1], k = 3\nOutput: true\nExplanation: There are two 1's in the array, at indices 0 and 3...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7132, "level": 1, "question": "Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.\n\nExample 1:\nInput: nums = [1,2,3,1], k = 3\nOutput: true\nExplanation: There are two 1...
def swap_pair(num: int) -> int: """ Function to swap odd and even bits in a 32-bit integer. :param num: A 32-bit non-negative integer :return: Integer with swapped odd and even bits """ # Using masks to separate even and odd bits # Odd bits (0xAAAAAAAA) are shifted right by 1 odd = ...
simplelr_Data_Structure
[ { "content": "Question:\nBit Manipulation\n\n#### Context\n\nYou are working on a project that requires efficient bit manipulation for performance-critical tasks. One part of the project involves writing a function that swaps each pair of adjacent bits in a 32-bit integer. For example, bit 0 with bit 1, bit 2 w...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7133, "level": 1, "question": "Bit Manipulation\n\n#### Context\n\nYou are working on a project that requires efficient bit manipulation for performance-critical tasks. One part of the project involves writing a function that swaps each pair of adjacent bits in a 32-bit integer. For...
import math def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False max_divisor = math.isqrt(n) for i in range(3, max_divisor + 1, 2): if n % i == 0: return False return True
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find whether a number is prime or not. Return True if the number is prime, otherwise return False. The function should handle numbers up to 10^6 efficiently.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7134, "level": 1, "question": "Write a python function to find whether a number is prime or not. Return True if the number is prime, otherwise return False. The function should handle numbers up to 10^6 efficiently.", "split": "train" }
from typing import List, Tuple def manage_warehouse(commands: List[str]) -> List[Tuple[str, int]]: inventory = {} for cmd in commands: parts = cmd.split() op = parts[0] if op == 'ADD': product = parts[1] qty = int(parts[2]) if product in inventory: ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement:\n\nYou have been tasked with writing a function that simulates the logistics of a small warehouse. The warehouse contains different products, and your task is to manage the inventory operations such as adding new products, removing products, and updating quantitie...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7135, "level": 1, "question": "### Problem Statement:\n\nYou have been tasked with writing a function that simulates the logistics of a small warehouse. The warehouse contains different products, and your task is to manage the inventory operations such as adding new products, removi...
from datetime import date, timedelta def is_valid_weekday_with_holidays(date_str): try: d = date.fromisoformat(date_str) except ValueError: return False # Invalid date # Check if the date is a weekend if d.weekday() >= 5: # 5 = Saturday, 6 = Sunday return False y...
simplelr_Filter
[ { "content": "Question:\nAs a developer, you are tasked to create a function to determine if a given date is valid or not. However, your function must also check if the input is not only a valid date but also falls on a weekday (Monday to Friday) and not on a weekend (Saturday or Sunday). Moreover, your functio...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7136, "level": 1, "question": "As a developer, you are tasked to create a function to determine if a given date is valid or not. However, your function must also check if the input is not only a valid date but also falls on a weekday (Monday to Friday) and not on a weekend (Saturday...
import matplotlib.pyplot as plt import seaborn as sns def customize_plot_context(): # 1. Retrieve and display default context parameters default_context = sns.plotting_context() print("Default plotting context parameters:") print(default_context) # 2. Switch to 'talk' context and create a plot...
simplelr_Docs
[ { "content": "Question:\n### Seaborn Plot Context Customization\n\n**Objective:**\n\nYour task is to demonstrate your understanding of Seaborn's `plotting_context` function. You will need to implement a Python function that performs the following operations and generates relevant visualizations.\n\n**Problem St...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7137, "level": 1, "question": "### Seaborn Plot Context Customization\n\n**Objective:**\n\nYour task is to demonstrate your understanding of Seaborn's `plotting_context` function. You will need to implement a Python function that performs the following operations and generates relev...
def single_number(nums): xor1 = 0 for num in nums: xor1 ^= num # Now, find the sum of elements that appear exactly three times thrice_sum = 0 count = {} for num in nums: count[num] = count.get(num, 0) + 1 for num, cnt in count.items(): if cnt == 3: ...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers, each integer appears either twice or three times except for one integer which appears exactly once. Write a function to find _the single integer that appears only once_. Your solution should have a linear runtime complexity `O(n)` and use only constant extra ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7138, "level": 1, "question": "Given an array of integers, each integer appears either twice or three times except for one integer which appears exactly once. Write a function to find _the single integer that appears only once_. Your solution should have a linear runtime complexity ...
from typing import List def find_peaks(numbers: List[int]) -> List[int]: peaks = [] n = len(numbers) for i in range(n): if i == 0: if n == 1: peaks.append(numbers[i]) else: if numbers[i] > numbers[i + 1]: peaks.append(numbe...
simplelr_Apps
[ { "content": "Question:\nWrite a function that takes a list of integers as input and returns a new list containing only the peaks. A peak is defined as an element that is strictly greater than its neighbours. \n\nFor example:\n- In the list `[1, 2, 3, 1]`, the number `3` is a peak.\n- In the list `[1, 3, 2, 3, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7139, "level": 1, "question": "Write a function that takes a list of integers as input and returns a new list containing only the peaks. A peak is defined as an element that is strictly greater than its neighbours. \n\nFor example:\n- In the list `[1, 2, 3, 1]`, the number `3` is a ...
import re def find_paragraph_with_max_word_freq(paragraphs, word): escaped_word = re.escape(word) pattern = re.compile(r'\b{}\b'.format(escaped_word), flags=re.IGNORECASE) counts = [] for paragraph in paragraphs: matches = pattern.findall(paragraph) counts.append(len(matches)) max_c...
simplelr_Codeforces
[ { "content": "Question:\nYou are given a text document that has several paragraphs. Each paragraph contains multiple sentences. Your task is to determine the paragraph that has the highest frequency of a specified word.\n\nWrite a function, `find_paragraph_with_max_word_freq(paragraphs, word)`, that takes as in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7140, "level": 1, "question": "You are given a text document that has several paragraphs. Each paragraph contains multiple sentences. Your task is to determine the paragraph that has the highest frequency of a specified word.\n\nWrite a function, `find_paragraph_with_max_word_freq(p...
def final_position(command): x = 0 y = 0 for c in command: if c == 'U': y += 1 elif c == 'D': y -= 1 elif c == 'L': x -= 1 elif c == 'R': x += 1 return (x, y)
simplelr_Apps
[ { "content": "Question:\n## Your story\nA friend of yours is a robotics enthusiast and has recently been trying to implement a small robot capable of navigating a grid pattern. The grid is represented by a series of commands, each telling the robot to move in a specific direction. The robot starts at position (...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7141, "level": 1, "question": "## Your story\nA friend of yours is a robotics enthusiast and has recently been trying to implement a small robot capable of navigating a grid pattern. The grid is represented by a series of commands, each telling the robot to move in a specific direct...
import seaborn.objects as so from seaborn import load_dataset import matplotlib.pyplot as plt def create_penguin_plots(): # Load the penguins dataset penguins = load_dataset("penguins") # Create the first plot (species vs body_mass_g with horizontal jitter) plt.figure(figsize=(10, 6)) # Set figur...
simplelr_Docs
[ { "content": "Question:\nYou are tasked with creating a comprehensive analysis of the `penguins` dataset using seaborn's `so.Plot` and `so.Jitter`. Your analysis should:\n\n1. **Load the `penguins` dataset** using seaborn.\n2. **Create a plot** displaying the relationship between `species` and `body_mass_g`, ap...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7142, "level": 1, "question": "You are tasked with creating a comprehensive analysis of the `penguins` dataset using seaborn's `so.Plot` and `so.Jitter`. Your analysis should:\n\n1. **Load the `penguins` dataset** using seaborn.\n2. **Create a plot** displaying the relationship betw...
def rearrange_list(lst): evens = [] odds = [] for num in lst: if num % 2 == 0: evens.append(num) else: odds.append(num) return evens + odds
simplelr_Taco
[ { "content": "Question:\nGiven a list of integers, write a function that rearranges the list so that all the even numbers appear before all the odd numbers. The relative order of the even and odd numbers should be preserved. Return the modified list.\n\nHere are some examples:\n\n```python\nrearrange_list([1, 2...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7143, "level": 1, "question": "Given a list of integers, write a function that rearranges the list so that all the even numbers appear before all the odd numbers. The relative order of the even and odd numbers should be preserved. Return the modified list.\n\nHere are some examples:...
def shell_sort_custom_gap(arr, gaps): # Check if gaps are valid if not gaps: return [] if gaps[-1] != 1: return [] for i in range(len(gaps) - 1): if gaps[i] <= gaps[i + 1]: return [] # Create a copy of the input array to avoid modification copy = arr.copy...
simplelr_Data_Structure
[ { "content": "Question:\nYou are given a list of integers that you need to sort using Shell Sort. Implement the function `shell_sort_custom_gap` that takes an array of integers and a custom list of gap values (integers) as its parameters. The function should sort the array based on the provided gap sequence. If...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7144, "level": 1, "question": "You are given a list of integers that you need to sort using Shell Sort. Implement the function `shell_sort_custom_gap` that takes an array of integers and a custom list of gap values (integers) as its parameters. The function should sort the array bas...
def find_pairs(nums, target): # Check if inputs are valid if not isinstance(nums, list) or not isinstance(target, int): return 'Invalid input!' for x in nums: if type(x) is not int: return 'Invalid input!' seen = set() pairs = set() result = [] for num i...
simplelr_Apps
[ { "content": "Question:\nYour task is to write a **function** that takes a **list of integers** and a **target integer** as inputs. The function should **return a list of pairs of integers** from the input list that add up to the target integer. Each pair should be a list of two integers in ascending order, and...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7145, "level": 1, "question": "Your task is to write a **function** that takes a **list of integers** and a **target integer** as inputs. The function should **return a list of pairs of integers** from the input list that add up to the target integer. Each pair should be a list of t...
def three_sum(nums): nums.sort() result = [] n = len(nums) for i in range(n - 2): # Skip duplicate 'a's if i > 0 and nums[i] == nums[i - 1]: continue a = nums[i] left = i + 1 right = n - 1 while left < right: current_sum = a + nums[...
simplelr_Filter
[ { "content": "Question:\nGiven an array of integers, write a Python function to find three numbers that together sum to zero. The solution should return all unique triplets in the array which gives the sum of zero. Note that the triplet (a, b, c) and its permutations like (b, a, c), (c, a, b) are considered the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7146, "level": 1, "question": "Given an array of integers, write a Python function to find three numbers that together sum to zero. The solution should return all unique triplets in the array which gives the sum of zero. Note that the triplet (a, b, c) and its permutations like (b, ...
from typing import List def combination_sum(nums: List[int], target: int) -> int: dp = [0] * (target + 1) dp[0] = 1 for i in range(1, target + 1): for num in nums: if num <= i: dp[i] += dp[i - num] return dp[target]
simplelr_Data_Structure
[ { "content": "Question:\nYou are working as a software developer at a company that develops educational tools. Your task is to implement a program that counts the number of possible combinations of elements in an array that add up to a given target. The elements in the array are positive integers, and each comb...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7147, "level": 1, "question": "You are working as a software developer at a company that develops educational tools. Your task is to implement a program that counts the number of possible combinations of elements in an array that add up to a given target. The elements in the array a...
def calculate_total(price, quantity): return price * quantity
simplelr_Filter
[ { "content": "Question:\n### Define a function `calculate_total` that takes in two parameters, `price` and `quantity`, and returns the total cost.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7148, "level": 1, "question": "### Define a function `calculate_total` that takes in two parameters, `price` and `quantity`, and returns the total cost.", "split": "train" }
def power(base: int, exponent: int) -> float: if exponent == 0: return 1.0 if base == 0: if exponent < 0: return float('inf') if exponent < 0: base = 1.0 / base exponent = -exponent result = 1.0 while exponent > 0: if exponent % 2 == 1: # If expon...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Challenge\n\nYou have been hired to develop a feature for a scientific calculator that requires quick and accurate computations of exponential values. One key function in this calculator is to compute the power of a base number raised to a specified exponent. However, the tar...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7149, "level": 1, "question": "### Coding Challenge\n\nYou have been hired to develop a feature for a scientific calculator that requires quick and accurate computations of exponential values. One key function in this calculator is to compute the power of a base number raised to a s...
def is_strong_password(password: str) -> bool: if len(password) < 8: return False has_upper = False has_lower = False has_digit = False has_special = False special_chars = {'@', '#', '$', '%', '^', '&', '*', '(', ')'} for char in password: if char.isupper(): ha...
simplelr_Algorithm
[ { "content": "Question:\n### Question\n\nA company wants to ensure their employees' passwords are strong. A strong password is defined by the following rules:\n\n1. It must be at least 8 characters long.\n2. It must contain at least one uppercase letter.\n3. It must contain at least one lowercase letter.\n4. It...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7150, "level": 1, "question": "### Question\n\nA company wants to ensure their employees' passwords are strong. A strong password is defined by the following rules:\n\n1. It must be at least 8 characters long.\n2. It must contain at least one uppercase letter.\n3. It must contain at...
def moving_average(lst, k): if k <= 0 or k > len(lst): return [] return [sum(lst[i:i + k]) / k for i in range(len(lst) - k + 1)]
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the moving average of a list of numbers using a sliding window of size k. For example, if the input list is `[1, 2, 3, 4, 5]` and `k` is 3, the output should be `[2.0, 3.0, 4.0]` because the average of the first three numbers is 2.0, the second three number...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7151, "level": 1, "question": "Write a function to calculate the moving average of a list of numbers using a sliding window of size k. For example, if the input list is `[1, 2, 3, 4, 5]` and `k` is 3, the output should be `[2.0, 3.0, 4.0]` because the average of the first three numb...
def smallest_subarray_with_sum(arr, x): n = len(arr) min_len = float('inf') left = 0 current_sum = 0 for right in range(n): current_sum += arr[right] while current_sum >= x and left <= right: window_length = right - left + 1 if window_length < min_len: ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of integers `arr` and an integer `x`. You need to find the smallest subarray length for which the sum of the elements is greater than or equal to `x`. If there is no subarray that meets this criterion, return -1.\n\nFor example, given `arr = [1, 2, 3, 4, 5]` and `...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7152, "level": 1, "question": "You are given an array of integers `arr` and an integer `x`. You need to find the smallest subarray length for which the sum of the elements is greater than or equal to `x`. If there is no subarray that meets this criterion, return -1.\n\nFor example, ...
import re def extract_numbers_greater_than_5(s): # Check if there's at least one special character if not re.search(r'[^a-zA-Z0-9\s]', s): return [] # Extract all integers, including negatives numbers = re.findall(r'-?\d+', s) # Convert to integers and filter those greater than 5 ...
simplelr_Filter
[ { "content": "Question:\nUse the re module in Python to extract the numbers greater than 5 from a given string that also contains at least one special character. The input string can be of any length and may contain multiple occurrences of special characters. Special characters are defined as any character that...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7153, "level": 1, "question": "Use the re module in Python to extract the numbers greater than 5 from a given string that also contains at least one special character. The input string can be of any length and may contain multiple occurrences of special characters. Special character...
from typing import List def count_successful_pastries(sales: List[int], T: int) -> int: return sum(1 for s in sales if s >= T)
simplelr_Apps
[ { "content": "Question:\nA bakery is keeping track of their daily sales which are stored in a list where each element represents the number of pastries sold for each type of pastry. They want to know how many types of pastries reached or exceeded a sales target `T` for the day.\n\nWrite a function `count_succes...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7154, "level": 1, "question": "A bakery is keeping track of their daily sales which are stored in a list where each element represents the number of pastries sold for each type of pastry. They want to know how many types of pastries reached or exceeded a sales target `T` for the day...
def median(numbers): if not numbers: raise ValueError("The list is empty.") sorted_numbers = sorted(numbers) n = len(sorted_numbers) if n % 2 == 1: return sorted_numbers[n // 2] else: return (sorted_numbers[n // 2 - 1] + sorted_numbers[n // 2]) / 2
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the median of a list of integers in Python. The function should be efficient and handle large datasets.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7155, "level": 1, "question": "Write a function to calculate the median of a list of integers in Python. The function should be efficient and handle large datasets.", "split": "train" }
def string_to_bytes(s): return list(s.encode('utf-8'))
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to convert a string to a list of bytes.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7156, "level": 1, "question": "Write a python function to convert a string to a list of bytes.", "split": "train" }
def intersection_of_sublists(lists): if not lists: return [] set_list = [set(sublist) for sublist in lists] result = set_list[0] for s in set_list[1:]: result = result.intersection(s) if not result: break return list(result)
simplelr_Filter
[ { "content": "Question:\nGiven a list of lists in Python where each sublist represents a set of items, write a function that returns the intersection of all these sublists. For instance, given `[[1,2,3,4,5], [5,6,7,8,9], [5,10]]`, the function should return `[5]` as it is the only common item across all sublist...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7157, "level": 1, "question": "Given a list of lists in Python where each sublist represents a set of items, write a function that returns the intersection of all these sublists. For instance, given `[[1,2,3,4,5], [5,6,7,8,9], [5,10]]`, the function should return `[5]` as it is the ...
def calculate_sum(s): return sum(int(num) for num in s.split('+'))
simplelr_Evol
[ { "content": "Question:\nWrite a function that accepts a string representing a mathematical addition expression consisting of non-negative integers (each possibly having multiple digits) separated by plus signs (e.g., \"3+25+7+40\"). The function should parse the string to calculate the sum of all the integers ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7158, "level": 1, "question": "Write a function that accepts a string representing a mathematical addition expression consisting of non-negative integers (each possibly having multiple digits) separated by plus signs (e.g., \"3+25+7+40\"). The function should parse the string to cal...
def binary_search(sorted_list, target): low = 0 high = len(sorted_list) - 1 while low <= high: mid = (low + high) // 2 if sorted_list[mid] == target: return mid elif sorted_list[mid] > target: high = mid - 1 else: low = mid + 1 return -...
simplelr_Filter
[ { "content": "Question:\nCreate a Python function named \"binary_search\" that takes a list of integers and an element as input, and returns the index of the element in the list using binary search algorithm. Assume the list is sorted in ascending order.\nAnswer:\nLet's think step by step.\n", "role": "user...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7159, "level": 1, "question": "Create a Python function named \"binary_search\" that takes a list of integers and an element as input, and returns the index of the element in the list using binary search algorithm. Assume the list is sorted in ascending order.", "split": "train" }
def calculate_polygon_area(vertices: list[tuple[float, float]]) -> float: n = len(vertices) sum1 = 0.0 sum2 = 0.0 for i in range(n): x1, y1 = vertices[i] x2, y2 = vertices[(i + 1) % n] sum1 += x1 * y2 sum2 += y1 * x2 area = 0.5 * abs(sum1 - sum2) return area
simplelr_Algorithm
[ { "content": "Question:\n## Question: Polygon Area Calculation\n\n**Scenario**: You are tasked with calculating the area of a simple polygon given the coordinates of its vertices in order. The vertices are provided in a clockwise or counterclockwise direction, and the polygon is non-self-intersecting.\n\n#### P...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7160, "level": 1, "question": "## Question: Polygon Area Calculation\n\n**Scenario**: You are tasked with calculating the area of a simple polygon given the coordinates of its vertices in order. The vertices are provided in a clockwise or counterclockwise direction, and the polygon ...
def factorial(n): if n < 0: raise ValueError("Factorial is not defined for negative numbers.") elif n == 0 or n == 1: return 1 else: return n * factorial(n - 1)
simplelr_Filter
[ { "content": "Question:\nCan you help me understand how to use a recursive function in Python to solve a problem, like calculating the factorial of a number?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7161, "level": 1, "question": "Can you help me understand how to use a recursive function in Python to solve a problem, like calculating the factorial of a number?", "split": "train" }
def factorial(n): if n < 0: raise ValueError("n must be a non-negative integer") result = 1 for i in range(1, n + 1): result *= i return result # Test cases print(factorial(0)) # Expected output: 1 print(factorial(1)) # Expected output: 1 print(factorial(5)) # Expected output: 120...
simplelr_Filter
[ { "content": "Question:\nPlease write a Python code snippet that defines a function to calculate the factorial of a number and then tests this function with a few examples.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7162, "level": 1, "question": "Please write a Python code snippet that defines a function to calculate the factorial of a number and then tests this function with a few examples.", "split": "train" }
from functools import lru_cache @lru_cache(maxsize=128) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) # Example usage print(fibonacci(5)) # Cache miss, computes and stores result print(fibonacci(5)) # Cache hit, returns stored result
simplelr_Filter
[ { "content": "Question:\nPlease explain how to use the `functools.lru_cache` decorator in Python for caching results of function calls.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7163, "level": 1, "question": "Please explain how to use the `functools.lru_cache` decorator in Python for caching results of function calls.", "split": "train" }
from collections import Counter import heapq def reorganizeArray(arr): counts = Counter(arr) n = len(arr) max_freq = (n + 1) // 2 for v in counts.values(): if v > max_freq: return [] heap = [(-v, k) for k, v in counts.items()] heapq.heapify(heap) result = [] ...
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers arr, determine whether the array can be reorganized such that no two adjacent elements are equal. If possible, return any possible reorganized version of the array. If not, return an empty array.\n\nExample 1:\nInput:\narr = [1, 1, 2, 2, 3, 3]\nOutput:\n[1, 2,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7164, "level": 1, "question": "Given an array of integers arr, determine whether the array can be reorganized such that no two adjacent elements are equal. If possible, return any possible reorganized version of the array. If not, return an empty array.\n\nExample 1:\nInput:\narr = ...
def remove_vowels(s): vowels = {'a', 'e', 'i', 'o', 'u'} result = [] for char in s: if char.lower() not in vowels: result.append(char) return ''.join(result)
simplelr_Filter
[ { "content": "Question:\nWrite a function that takes in a string and returns the string with all vowels removed. Vowels are defined as the letters 'a', 'e', 'i', 'o', and 'u' (case-insensitive). If the input string contains no vowels, return the original string. The function should handle both empty strings and...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7165, "level": 1, "question": "Write a function that takes in a string and returns the string with all vowels removed. Vowels are defined as the letters 'a', 'e', 'i', 'o', and 'u' (case-insensitive). If the input string contains no vowels, return the original string. The function s...
import heapq def findKthLargest(nums, k): heap = [] for num in nums: if len(heap) < k: heapq.heappush(heap, num) else: if num > heap[0]: heapq.heappop(heap) heapq.heappush(heap, num) return heap[0]
simplelr_Code_Contests
[ { "content": "Question:\n###\n\nGiven an integer array `nums` and an integer `k`, your task is to find the `k`-th largest element in the sorted order of the array. You are required to implement the function `findKthLargest(nums, k)`. The function should return an integer representing the `k`-th largest element ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7166, "level": 1, "question": "###\n\nGiven an integer array `nums` and an integer `k`, your task is to find the `k`-th largest element in the sorted order of the array. You are required to implement the function `findKthLargest(nums, k)`. The function should return an integer repre...
import math def calculate_shannon_entropy(distribution): """ Calculate the Shannon entropy of a given probability distribution. Args: distribution (list): A list of probabilities where each element is between 0 and 1. Returns: float: The Shannon entropy value of the distri...
simplelr_Filter
[ { "content": "Question:\nCodify the entropy calculation algorithm in Python language utilizing the 'math' library that would accept a probabilistic distribution list as the input and output the Shannon entropy value.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7167, "level": 1, "question": "Codify the entropy calculation algorithm in Python language utilizing the 'math' library that would accept a probabilistic distribution list as the input and output the Shannon entropy value.", "split": "train" }
def replace_words(s, dictionary): dict_set = {word.lower() for word in dictionary} words = s.split() result = [] for word in words: if word.lower() in dict_set: result.append(f'*{word}*') else: result.append(word) return ' '.join(result)
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` and an array of strings `dictionary`. You need to replace the words in `s` that match any word in `dictionary` with the word version surrounded by asterisks (*). Note that a word is defined as a sequence of characters separated by spaces, and the case of the w...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7168, "level": 1, "question": "You are given a string `s` and an array of strings `dictionary`. You need to replace the words in `s` that match any word in `dictionary` with the word version surrounded by asterisks (*). Note that a word is defined as a sequence of characters separat...
def minimumSwapsToSort(arr): sorted_arr = sorted(arr) n = len(arr) pos = {v: i for i, v in enumerate(sorted_arr)} visited = [False] * n swaps = 0 for i in range(n): if not visited[i]: cycle_size = 0 j = i while not visited[j]: visited[...
simplelr_Apps
[ { "content": "Question:\nCreate a function called `minimumSwapsToSort` that takes an array of integers and returns the minimum number of swaps required to sort the array in ascending order. Each swap involves swapping any two distinct elements of the array.\n\nFor example:\n\n```python\nminimumSwapsToSort([4, 3...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7169, "level": 1, "question": "Create a function called `minimumSwapsToSort` that takes an array of integers and returns the minimum number of swaps required to sort the array in ascending order. Each swap involves swapping any two distinct elements of the array.\n\nFor example:\n\n...
from collections import deque def shortest_path(graph, start, target): if start not in graph: return [] queue = deque() queue.append((start, [start])) visited = set() visited.add(start) while queue: current, path = queue.popleft() if current == target: ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a directed acyclic graph (DAG) represented as an adjacency list, where `graph[i]` is a list of all nodes `j` for which there is a directed edge from node `i` to node `j`. Write a function to return the shortest path from a given start node to a target node. If no path exis...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7170, "level": 1, "question": "You are given a directed acyclic graph (DAG) represented as an adjacency list, where `graph[i]` is a list of all nodes `j` for which there is a directed edge from node `i` to node `j`. Write a function to return the shortest path from a given start nod...
def find_pairs_with_sum(arr, target): pairs = set() n = len(arr) for i in range(n): for j in range(i + 1, n): if arr[i] + arr[j] == target: a, b = arr[i], arr[j] pair = (a, b) if a < b else (b, a) pairs.add(pair) sorted_pairs = sorted(p...
simplelr_Package
[ { "content": "Question:\nYou are given a set of integers and need to find all unique pairs of integers that sum up to a given target value. Each pair should be sorted in ascending order, and the list of pairs should be sorted based on the first element of each pair. If multiple pairs have the same first element...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7171, "level": 1, "question": "You are given a set of integers and need to find all unique pairs of integers that sum up to a given target value. Each pair should be sorted in ascending order, and the list of pairs should be sorted based on the first element of each pair. If multipl...
def binary_to_decimal(b): # Check if input is a string if not isinstance(b, str): return None # Check if string is empty if len(b) == 0: return None # Check if all characters are 0 or 1 for char in b: if char not in ('0', '1'): return None # Convert to dec...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that converts a binary number to a decimal number. The function should take a binary number as a string input and return a decimal number as an integer. You should handle edge cases such as an empty string or a string that does not contain a binary number, returning No...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7172, "level": 1, "question": "Create a function that converts a binary number to a decimal number. The function should take a binary number as a string input and return a decimal number as an integer. You should handle edge cases such as an empty string or a string that does not co...
def has_all_unique_characters(s): for i in range(len(s)): for j in range(i + 1, len(s)): if s[i] == s[j]: return False return True
simplelr_Filter
[ { "content": "Question:\nThis is a problem involving python programming. I need to create a program to check whether a given string has all unique characters. The constraint is that I should not use any additional data structures like dictionaries, sets, or lists. How can I achieve this?\nAnswer:\nLet's think s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7173, "level": 1, "question": "This is a problem involving python programming. I need to create a program to check whether a given string has all unique characters. The constraint is that I should not use any additional data structures like dictionaries, sets, or lists. How can I ac...
import os import tempfile def reverse_words(filename: str) -> None: with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp: temp_name = temp.name with open(filename, 'r') as source: for line in source: reversed_line = ' '.join(reversed(line.split())) ...
simplelr_Package
[ { "content": "Question:\nYou are tasked with writing a Python function named `reverse_words` which takes the name of a text file as input. The function should read the contents of the file and for each line, it should reverse the order of the words while maintaining the words themselves in their original form. ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7174, "level": 1, "question": "You are tasked with writing a Python function named `reverse_words` which takes the name of a text file as input. The function should read the contents of the file and for each line, it should reverse the order of the words while maintaining the words ...
from collections import deque def bfs_traversal(graph, start): if start not in graph: return [] visited = set() result = [] queue = deque([start]) visited.add(start) while queue: current = queue.popleft() result.append(current) for neighbor in ...
simplelr_Filter
[ { "content": "Question:\nHere is a Python dictionary, its keys are the names of the cities and values are lists of cities that can be reached directly from them:\n```\ngraph = {\n 'A': ['B', 'D'],\n 'B': ['A', 'C', 'E'],\n 'C': ['B', 'F'],\n 'D': ['A'],\n 'E': ['B', 'F'],\n 'F': ['C', 'E'],\n}...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7175, "level": 1, "question": "Here is a Python dictionary, its keys are the names of the cities and values are lists of cities that can be reached directly from them:\n```\ngraph = {\n 'A': ['B', 'D'],\n 'B': ['A', 'C', 'E'],\n 'C': ['B', 'F'],\n 'D': ['A'],\n 'E': [...
def reverse_each_word(phrase): """ This function takes a phrase as input, reverses each individual word, and returns the modified phrase while maintaining the original word order. """ # Split the phrase into words words = phrase.split() # Reverse each word and collect them into a list r...
simplelr_Filter
[ { "content": "Question:\nUse the following input to write a python program. The program should include a function that allows the user to enter a phrase, then returns the phrase with each word reversed while maintaining the original order of words.\nAnswer:\nLet's think step by step.\n", "role": "user" } ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7176, "level": 1, "question": "Use the following input to write a python program. The program should include a function that allows the user to enter a phrase, then returns the phrase with each word reversed while maintaining the original order of words.", "split": "train" }
def removeKdigits(s: str, k: int) -> str: stack = [] for c in s: while k > 0 and stack and stack[-1] > c: stack.pop() k -= 1 stack.append(c) if k > 0: stack = stack[:-k] return ''.join(stack).lstrip('0') or '0'
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` representing a large integer. Implement an algorithm to remove `k` digits from the string such that the new number is the smallest possible. Return _the resulting string after removing `k` digits_. The string should not contain leading zeros, except the number...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7177, "level": 1, "question": "You are given a string `s` representing a large integer. Implement an algorithm to remove `k` digits from the string such that the new number is the smallest possible. Return _the resulting string after removing `k` digits_. The string should not conta...
def count_unique_characters(s): return len(set(s.lower()))
simplelr_Filter
[ { "content": "Question:\nHow can I design a Python function that takes a string as input and returns the number of unique characters in the string, ignoring case sensitivity?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7178, "level": 1, "question": "How can I design a Python function that takes a string as input and returns the number of unique characters in the string, ignoring case sensitivity?", "split": "train" }
def reverse_array(arr): start = 0 end = len(arr) - 1 while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1 return arr
simplelr_Filter
[ { "content": "Question:\nIntroduce a method that can reorder an array to its inverse sequence without relying on pre-existing reverse functions.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7179, "level": 1, "question": "Introduce a method that can reorder an array to its inverse sequence without relying on pre-existing reverse functions.", "split": "train" }
def lexicographically_smallest_string(s): return ''.join(sorted(s))
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` of lowercase alphabets, you are allowed to perform the following operation any number of times: Choose an index `i` (1 <= i <= s.length - 1) and replace the substring `s[i:i+2]` with its reverse. The goal is to convert the string into its lexicographically smallest po...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7180, "level": 1, "question": "Given a string `s` of lowercase alphabets, you are allowed to perform the following operation any number of times: Choose an index `i` (1 <= i <= s.length - 1) and replace the substring `s[i:i+2]` with its reverse. The goal is to convert the string int...
import string def word_frequency(text, word): text_lower = text.lower() word_lower = word.lower() tokens = text_lower.split() count = 0 for token in tokens: stripped_token = token.strip(string.punctuation) if stripped_token == word_lower: count += 1 return count
simplelr_Prefill
[ { "content": "Question:\nCreate a function that searches a text for a specific word and returns the frequency of its occurrences. You should ignore case and consider only whole words.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7181, "level": 1, "question": "Create a function that searches a text for a specific word and returns the frequency of its occurrences. You should ignore case and consider only whole words.", "split": "train" }
def count_palindromic_substrings(s): count = 0 n = len(s) for i in range(n): for j in range(i, n): substring = s[i:j+1] if substring == substring[::-1]: count += 1 return count
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to count the number of substrings within a string that are palindromes. A palindrome is a string that reads the same forward and backward.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7182, "level": 1, "question": "Write a python function to count the number of substrings within a string that are palindromes. A palindrome is a string that reads the same forward and backward.", "split": "train" }
def reverse_and_analyze_string(s): reversed_s = s[::-1] print(reversed_s) vowels = {'a', 'e', 'i', 'o', 'u'} vowel_count = 0 consonant_count = 0 for char in reversed_s: if char.isalpha(): lower_char = char.lower() if lower_char in vowels: vowel_cou...
simplelr_Filter
[ { "content": "Question:\nCreate a function that prints the string passed to it as an argument, but the string must be reversed before printing. Additionally, the function should count the number of vowels in the reversed string and print the count. The function should also return the number of consonants in the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7183, "level": 1, "question": "Create a function that prints the string passed to it as an argument, but the string must be reversed before printing. Additionally, the function should count the number of vowels in the reversed string and print the count. The function should also ret...
def draw_pyramid(n: int) -> None: for i in range(1, n + 1): spaces = ' ' * (n - i) stars = '*' * (2 * i - 1) print(spaces + stars + spaces)
simplelr_Package
[ { "content": "Question:\nYou are tasked with writing a function that generates a pattern of pyramids using stars. The function should accept a single integer parameter `n` that specifies the number of rows in the pyramid. Each row `i` of the pyramid should contain `2*i - 1` stars, and the stars should be center...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7184, "level": 1, "question": "You are tasked with writing a function that generates a pattern of pyramids using stars. The function should accept a single integer parameter `n` that specifies the number of rows in the pyramid. Each row `i` of the pyramid should contain `2*i - 1` st...
import itertools from functools import reduce import operator from typing import List def process_numbers(numbers: List[int], n: int) -> List[int]: # Step 1: Generate the cycled part by repeating the original list n times cycled_part = list(itertools.chain.from_iterable([numbers] * n)) # Step 2: Combi...
simplelr_Docs
[ { "content": "Question:\nYou have been tasked with writing a function that applies a series of operations on a list of numbers using functionalities from the `itertools`, `functools`, and `operator` modules. The function should demonstrate your ability to utilize these modules effectively.\n\n### Problem Statem...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7185, "level": 1, "question": "You have been tasked with writing a function that applies a series of operations on a list of numbers using functionalities from the `itertools`, `functools`, and `operator` modules. The function should demonstrate your ability to utilize these modules...
from collections import Counter def can_form_palindrome(s: str) -> bool: count = Counter(s) odd_count = 0 for char, cnt in count.items(): if cnt % 2 != 0: odd_count += 1 if odd_count > 1: return False return odd_count <= 1
simplelr_Algorithm
[ { "content": "Question:\n### Palindrome Permutation: Efficient Character Count Evaluation\n\n**Scenario**: A software company is developing a text analysis tool to identify potential palindrome permutations in given strings. This feature aims to enhance search algorithms focused on detecting mirrored word patte...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7186, "level": 1, "question": "### Palindrome Permutation: Efficient Character Count Evaluation\n\n**Scenario**: A software company is developing a text analysis tool to identify potential palindrome permutations in given strings. This feature aims to enhance search algorithms focus...
def compute_balances(transactions: list[list[any]]) -> dict: balances = {} for transaction in transactions: acc_id = transaction[1] amount = transaction[3] if acc_id not in balances: balances[acc_id] = 0 if transaction[2] == 'debit': balances[acc_id] -= am...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Challenge: Financial Transactions Record\n\nYou are given a list of bank transactions, where each transaction has attributes: `transaction_id`, `account_id`, `transaction_type`, and `amount`. Your task is to implement a function that processes these transactions and computes ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7187, "level": 1, "question": "### Coding Challenge: Financial Transactions Record\n\nYou are given a list of bank transactions, where each transaction has attributes: `transaction_id`, `account_id`, `transaction_type`, and `amount`. Your task is to implement a function that process...
def combine_dicts(dict1, dict2): combined_dict = {} # Add all entries from the first dictionary for key, value in dict1.items(): combined_dict[key] = value # Process the second dictionary and update values where keys overlap for key, value in dict2.items(): if key in combined_dict: ...
simplelr_Filter
[ { "content": "Question:\nCraft a Python function that combines two dictionaries maintaining their unique entries, while resolving duplicates by taking the maximum value of the duplicate keys. Assume the values are numeric.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7188, "level": 1, "question": "Craft a Python function that combines two dictionaries maintaining their unique entries, while resolving duplicates by taking the maximum value of the duplicate keys. Assume the values are numeric.", "split": "train" }
def findMaxLength(nums): max_length = 0 current_sum = 0 first_occurrence = {0: -1} for i, num in enumerate(nums): current_sum += 1 if num == 1 else -1 if current_sum in first_occurrence: length = i - first_occurrence[current_sum] if length > max_length: ...
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers nums, you are tasked with determining the length of the longest contiguous subarray that contains an equal number of 0s and 1s.\n\nExample 1:\n\nInput: nums = [0, 1, 0]\nOutput: 2\nExplanation: [0, 1] or [1, 0]\n\nExample 2:\n\nInput: nums = [0, 1, 0, 1, 1, 0,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7189, "level": 1, "question": "Given an array of integers nums, you are tasked with determining the length of the longest contiguous subarray that contains an equal number of 0s and 1s.\n\nExample 1:\n\nInput: nums = [0, 1, 0]\nOutput: 2\nExplanation: [0, 1] or [1, 0]\n\nExample 2:\...
import re def decode_string(s): result = '' for num_str, char in re.findall(r'(\d+)([a-z])', s): result += char * int(num_str) return result
simplelr_Leetcode
[ { "content": "Question:\nImagine you are given an encoded string in which each digit indicates the number of times the following character (which is guaranteed to be a lowercase letter) appears. For example, the string `\"3a2b1c\"` means `'a'` appears 3 times, `'b'` appears 2 times, and `'c'` appears 1 time. Wr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7190, "level": 1, "question": "Imagine you are given an encoded string in which each digit indicates the number of times the following character (which is guaranteed to be a lowercase letter) appears. For example, the string `\"3a2b1c\"` means `'a'` appears 3 times, `'b'` appears 2 ...
def iterative_binomial_coefficient(n: int, k: int) -> int: if k == 0 or k == n: return 1 k = min(k, n - k) result = 1 for i in range(1, k + 1): result = result * (n - k + i) // i return result
simplelr_Data_Structure
[ { "content": "Question:\n**Question**:\nYou are given the task of developing a function to compute the binomial coefficient \\( C(n, k) \\) using a more efficient iterative approach as an alternative to the recursive method shown above. The binomial coefficient \\( C(n, k) \\) represents the number of ways to c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7191, "level": 1, "question": "**Question**:\nYou are given the task of developing a function to compute the binomial coefficient \\( C(n, k) \\) using a more efficient iterative approach as an alternative to the recursive method shown above. The binomial coefficient \\( C(n, k) \\)...
def is_valid_palindrome(s): processed = s.lower().replace(' ', '') return processed == processed[::-1]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check if a given string is a valid palindrome ignoring cases and spaces.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7192, "level": 1, "question": "Write a python function to check if a given string is a valid palindrome ignoring cases and spaces.", "split": "train" }
def count_letter_frequency(s): letter_counts = {} for char in s: if char.isalpha(): lower_char = char.lower() if lower_char in letter_counts: letter_counts[lower_char] += 1 else: letter_counts[lower_char] = 1 return letter_counts
simplelr_Filter
[ { "content": "Question:\nI have a string in Python, and I want to find out how often each letter appears in it. Can you help me write a function that does this?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7193, "level": 1, "question": "I have a string in Python, and I want to find out how often each letter appears in it. Can you help me write a function that does this?", "split": "train" }
def maximalSquare(grid): if not grid or len(grid) == 0: return 0 m = len(grid) n = len(grid[0]) dp = [[0] * n for _ in range(m)] max_side = 0 for i in range(m): for j in range(n): if grid[i][j] == 1: if i == 0 or j == 0: dp[i][j] = ...
simplelr_Leetcode
[ { "content": "Question:\nGiven an `m x n` matrix `grid` of integers (where `m` and `n` represent the number of rows and columns respectively), a __square__ is defined as a contiguous section in the grid bounded by four corners. Return the length of the side of the largest square containing only 1's. If there is...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7194, "level": 1, "question": "Given an `m x n` matrix `grid` of integers (where `m` and `n` represent the number of rows and columns respectively), a __square__ is defined as a contiguous section in the grid bounded by four corners. Return the length of the side of the largest squa...
def max_different_types_of_candies(nums, k): unique_types = len(set(nums)) return min(unique_types, k)
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of integers `nums`, where each integer represents a different type of candy, and you are also given an integer `k` which represents the number of candies you can pick. Return the maximum number of different types of candies you can pick if you can select `k` candi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7195, "level": 1, "question": "You are given an array of integers `nums`, where each integer represents a different type of candy, and you are also given an integer `k` which represents the number of candies you can pick. Return the maximum number of different types of candies you c...
def optimized_gcd(a: int, b: int) -> int: shift = 0 # Remove common factors of 2 while (a & 1) == 0 and (b & 1) == 0: a >>= 1 b >>= 1 shift += 1 # Compute GCD using Euclidean algorithm while b != 0: a, b = b, a % b return a << shift
simplelr_Data_Structure
[ { "content": "Question:\n**Context**:\nThe greatest common divisor (GCD) of two integers is the largest positive integer that divides both numbers without leaving a remainder. The Euclidean algorithm is a classic method to compute the GCD via iterative division, while bitwise manipulation can offer an alternate...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7196, "level": 1, "question": "**Context**:\nThe greatest common divisor (GCD) of two integers is the largest positive integer that divides both numbers without leaving a remainder. The Euclidean algorithm is a classic method to compute the GCD via iterative division, while bitwise ...
def optimized_exchange_sort(arr): n = len(arr) if n <= 1: return arr end = n - 1 swapped = True while swapped: swapped = False for j in range(end): if arr[j] > arr[j + 1]: # Swap elements arr[j], arr[j + 1] = arr[j + 1], a...
simplelr_Data_Structure
[ { "content": "Question:\n### Exchange Sort - Advanced Version\n\n#### Context:\nYou are working on improving a basic sorting algorithm for a small embedded system with very limited resources. You have identified that the Exchange Sort algorithm is simple enough to implement within the constraints. Nevertheless,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7197, "level": 1, "question": "### Exchange Sort - Advanced Version\n\n#### Context:\nYou are working on improving a basic sorting algorithm for a small embedded system with very limited resources. You have identified that the Exchange Sort algorithm is simple enough to implement wi...
def nth_fibonacci(n: int) -> int: if n == 0: return 0 elif n == 1: return 1 else: a, b = 0, 1 for i in range(2, n + 1): c = a + b a = b b = c return b
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Context\nYou have been asked to implement a function that efficiently finds the nth Fibonacci number. The traditional recursive approach for calculating Fibonacci numbers is not optimal due to its exponential time complexity. You are required to op...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7198, "level": 1, "question": "### Coding Assessment Question\n\n#### Context\nYou have been asked to implement a function that efficiently finds the nth Fibonacci number. The traditional recursive approach for calculating Fibonacci numbers is not optimal due to its exponential time...
def reverse_string(s): reversed_str = "" for char in reversed(s): reversed_str += char return reversed_str # Example usage: print(reverse_string("hello")) # Output: "olleh"
simplelr_Filter
[ { "content": "Question:\nGive me a code snippet to reverse a string in Python without using slicing?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 7199, "level": 1, "question": "Give me a code snippet to reverse a string in Python without using slicing?", "split": "train" }