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 product_of_odd_numbers(numbers): product = 1 for number in numbers: if number % 2 != 0: product *= number return product
simplelr_Filter
[ { "content": "Question:\nI need to create a Python function that takes a list of integers and returns the product of all the odd numbers in the list. Can you help me with that?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4400, "level": 1, "question": "I need to create a Python function that takes a list of integers and returns the product of all the odd numbers in the list. Can you help me with that?", "split": "train" }
def intersection(set1, set2): return set1 & set2
simplelr_Filter
[ { "content": "Question:\nI need to write a Python function that finds the intersection of two sets of integers. The function should take two sets as input and return a set containing the common elements. How can I do this?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4401, "level": 1, "question": "I need to write a Python function that finds the intersection of two sets of integers. The function should take two sets as input and return a set containing the common elements. How can I do this?", "split": "train" }
def min_swaps_to_sort(arr): arr = arr.copy() sorted_arr = sorted(arr) swaps = 0 for i in range(len(arr)): if arr[i] != sorted_arr[i]: # Find the position to swap j = i while j < len(arr) and arr[j] != sorted_arr[i]: j += 1 # Swap th...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of `n` integers, where each integer represents the height of a person in a line. A line is considered to be “out of order” if there are two people in a row such that the person on the left is taller than the person on the right. Your task is to calculate the minim...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4402, "level": 1, "question": "You are given an array of `n` integers, where each integer represents the height of a person in a line. A line is considered to be “out of order” if there are two people in a row such that the person on the left is taller than the person on the right. ...
def remove_character(s, char): return s.replace(char, '')
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to remove all occurrences of a specified character from a string. For example, remove all occurrences of the character 'a' from the string \"apple\". The function should return the modified string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4403, "level": 1, "question": "Write a python function to remove all occurrences of a specified character from a string. For example, remove all occurrences of the character 'a' from the string \"apple\". The function should return the modified string.", "split": "train" }
def print_hello_world(): print("Hello, World!")
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to print a message \"Hello, World!\".\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4404, "level": 1, "question": "Write a python function to print a message \"Hello, World!\".", "split": "train" }
def is_valid_isbn10(s): if len(s) != 10: return False for i in range(9): if not s[i].isdigit(): return False if not (s[9].isdigit() or s[9] == 'X'): return False total = 0 for i in range(10): if i < 9: num = int(s[i]) else: ...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to check if a given number is a valid ISBN10 number.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4405, "level": 1, "question": "Write a function to check if a given number is a valid ISBN10 number.", "split": "train" }
def insert_value(lst, index, value): if 0 <= index <= len(lst): return lst[:index] + [value] + lst[index:] else: return lst
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of integers, an index, and a value to insert. The function should insert the value at the specified index in the list, while maintaining the order of the other elements. However, if the index is out of bounds, the function should not insert the value ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4406, "level": 1, "question": "Create a function that takes a list of integers, an index, and a value to insert. The function should insert the value at the specified index in the list, while maintaining the order of the other elements. However, if the index is out of bounds, the fu...
def isMatch(s, p): m = len(s) n = len(p) dp = [[False] * (n + 1) for _ in range(m + 1)] dp[0][0] = True # Empty pattern matches empty string for i in range(m + 1): for j in range(1, n + 1): if p[j-1] == '*': if j == 1: # The pattern is ex...
simplelr_Leetcode
[ { "content": "Question:\nGiven an input string `s` and a pattern `p`, implement wildcard pattern matching with support for `'.'` and `'*'`. The matching should cover the entire input string (not partial). \n- `'.'` Matches any single character. \n- `'*'` Matches zero or more of the preceding element. \n\nThe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4407, "level": 1, "question": "Given an input string `s` and a pattern `p`, implement wildcard pattern matching with support for `'.'` and `'*'`. The matching should cover the entire input string (not partial). \n- `'.'` Matches any single character. \n- `'*'` Matches zero or more...
def portfolio_evaluation(stock_quantities: dict, stock_prices: dict, percentage_changes: dict) -> dict: individual_values = {} total_value = 0.0 for ticker in stock_quantities: quantity = stock_quantities[ticker] price = stock_prices[ticker] individual_value = quantity * price ...
simplelr_Algorithm
[ { "content": "Question:\n### Financial Portfolio Evaluation\n\nTo further your grasp on financial modeling and data manipulation, you are to create a function to evaluate the performance of a stock portfolio. The function will calculate the total portfolio value and return a comprehensive assessment based on in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4408, "level": 1, "question": "### Financial Portfolio Evaluation\n\nTo further your grasp on financial modeling and data manipulation, you are to create a function to evaluate the performance of a stock portfolio. The function will calculate the total portfolio value and return a c...
from collections import Counter def canFormPalindrome(s: str) -> bool: count = Counter(s) odd_counts = sum(1 for c in count.values() if c % 2 != 0) if len(s) % 2 == 0: return odd_counts == 0 else: return odd_counts == 1
simplelr_Taco
[ { "content": "Question:\nYou are given a string of lowercase alphabet characters. Your task is to determine whether the string is a palindrome or can be rearranged to form a palindrome. \n\nA `palindrome` is a word that reads the same backward as forward. For example, \"madam\" is a palindrome but \"apple\" is ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4409, "level": 1, "question": "You are given a string of lowercase alphabet characters. Your task is to determine whether the string is a palindrome or can be rearranged to form a palindrome. \n\nA `palindrome` is a word that reads the same backward as forward. For example, \"madam\...
def tokenizer(documents: list, delimiter: str) -> dict: token_indices = {} next_index = 0 for document in documents: tokens = document.split(delimiter) for token in tokens: if token: # Skip empty tokens if token not in token_indices: token_ind...
simplelr_Package
[ { "content": "Question:\nIn data processing pipelines, transforming text data into numerical data is a common prerequisite for many machine learning tasks. One such transformation is to convert tokens (words or phrases) into unique integer indices which can be used directly in machine learning models.\n\nWe wan...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4410, "level": 1, "question": "In data processing pipelines, transforming text data into numerical data is a common prerequisite for many machine learning tasks. One such transformation is to convert tokens (words or phrases) into unique integer indices which can be used directly in...
def decimal_to_binary(n): if n == 0: return '0' binary_digits = [] while n > 0: remainder = n % 2 binary_digits.append(str(remainder)) n = n // 2 return ''.join(reversed(binary_digits))
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to convert a decimal number to a binary string, and also provide a brief explanation of how the function works.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4411, "level": 1, "question": "Write a Python function to convert a decimal number to a binary string, and also provide a brief explanation of how the function works.", "split": "train" }
def apply_discount(order_total): if order_total < 0: raise ValueError("Order total cannot be negative") elif order_total > 100: return order_total - 20 else: raise ValueError("Order total does not qualify for discount")
simplelr_Filter
[ { "content": "Question:\nYour company is running a sales promotion in which you offer a $20 discount on all orders over $100. Write a function `apply_discount` that takes the order total as an argument and returns the new total after applying the discount if the order is eligible. If the order is not eligible,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4412, "level": 1, "question": "Your company is running a sales promotion in which you offer a $20 discount on all orders over $100. Write a function `apply_discount` that takes the order total as an argument and returns the new total after applying the discount if the order is eligi...
def fruits_with_length(fruit_list): return [f"{fruit}{len(fruit)}" for fruit in fruit_list]
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that takes a list containing unpaired fruit names and returns a new list with each fruit name concatenated with the count of its characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4413, "level": 1, "question": "Create a Python function that takes a list containing unpaired fruit names and returns a new list with each fruit name concatenated with the count of its characters.", "split": "train" }
import random 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 True elif sorted_list[mid] < target: low = mid + 1 else: high = mid ...
simplelr_Filter
[ { "content": "Question:\nGiven a list of shuffled numbers 1 to 100 inclusive in a random order, write a program that uses a binary search algorithm to find if a specific number is present in the list. For testing, assume the number you're looking for is 47.\nAnswer:\nLet's think step by step.\n", "role": "u...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4414, "level": 1, "question": "Given a list of shuffled numbers 1 to 100 inclusive in a random order, write a program that uses a binary search algorithm to find if a specific number is present in the list. For testing, assume the number you're looking for is 47.", "split": "train...
def get_mystery_number(numbers): positive_nums = set() for num in numbers: if num > 0: positive_nums.add(num) i = 1 while i in positive_nums: i += 1 return i
simplelr_Filter
[ { "content": "Question:\nWrite a function in Python called get_mystery_number that takes a list of numbers and returns the smallest positive number that is not in the list. If there is no such number, the function should return -1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4415, "level": 1, "question": "Write a function in Python called get_mystery_number that takes a list of numbers and returns the smallest positive number that is not in the list. If there is no such number, the function should return -1.", "split": "train" }
def has_unique_characters(s): seen = set() for c in s: if c in seen: return False seen.add(c) return True
simplelr_Filter
[ { "content": "Question:\n### Problem\nYou are tasked with writing a function that determines whether a given string consists of unique characters. What is the most efficient way to do this?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4416, "level": 1, "question": "### Problem\nYou are tasked with writing a function that determines whether a given string consists of unique characters. What is the most efficient way to do this?", "split": "train" }
import numpy as np from scipy import signal as sig import matplotlib.pyplot as plt # Generate a signal with noise t = np.linspace(0, 1, 1000, endpoint=False) x = np.sin(2 * np.pi * 10 * t) + 0.5 * np.sin(2 * np.pi * 20 * t) + 0.1 * np.random.randn(len(t)) # Fourier Transform X = np.fft.fft(x) # Define your smoother ...
simplelr_Filter
[ { "content": "Question:\nI have created a new smoother function and I want to apply it to a signal. I'm using Python and I want to know how to use it with a signal from the scipy library. \nFirst, I'll need to generate a noisy signal, then apply a Fourier Transform, and afterwards, use my smoother function.\n\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4417, "level": 1, "question": "I have created a new smoother function and I want to apply it to a signal. I'm using Python and I want to know how to use it with a signal from the scipy library. \nFirst, I'll need to generate a noisy signal, then apply a Fourier Transform, and afterw...
import math from typing import List def bucket_sort(arr: List[int]) -> List[int]: if not arr: return [] n = len(arr) if n == 1: return arr.copy() min_val = min(arr) max_val = max(arr) if min_val == max_val: return arr.copy() delta = max_val - min_val k ...
simplelr_Data_Structure
[ { "content": "Question:\n**Bucket Sort with Advanced Implementation**\n\nYou are tasked with implementing a version of the Bucket Sort algorithm which must be optimized to handle both evenly and unevenly distributed data efficiently. For this task, you need to design and code the bucket sort function that can s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4418, "level": 1, "question": "**Bucket Sort with Advanced Implementation**\n\nYou are tasked with implementing a version of the Bucket Sort algorithm which must be optimized to handle both evenly and unevenly distributed data efficiently. For this task, you need to design and code ...
from collections import defaultdict def find_min_length_subarray(arr, k): unique = len(set(arr)) if unique < k: return -1 min_len = float('inf') freq = defaultdict(int) distinct = 0 left = 0 for right in range(len(arr)): num = arr[right] if freq[num] == 0: ...
simplelr_Taco
[ { "content": "Question:\nGiven an integer array `arr` and a positive integer `k`, you need to find the minimum possible length of a subarray of `arr` such that there are at least `k` distinct integers in that subarray. If no such subarray exists, return `-1`.\n\nA subarray is a contiguous portion of the array.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4419, "level": 1, "question": "Given an integer array `arr` and a positive integer `k`, you need to find the minimum possible length of a subarray of `arr` such that there are at least `k` distinct integers in that subarray. If no such subarray exists, return `-1`.\n\nA subarray is ...
def count_even_sum_subarrays(arr): MOD = 10**9 + 7 count_even = 1 # Initially, the prefix sum of 0 (even) count_odd = 0 result = 0 current_mod = 0 # Tracks the current prefix sum modulo 2 for num in arr: current_mod = (current_mod + num) % 2 if current_mod == 0: ...
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `arr` of length `n`, return the number of subarrays with an even sum. Since the answer may be very large, return it **modulo `10^9 + 7`**.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4420, "level": 1, "question": "Given an integer array `arr` of length `n`, return the number of subarrays with an even sum. Since the answer may be very large, return it **modulo `10^9 + 7`**.", "split": "train" }
def can_split_into_three_equal_sum_subarrays(nums): total = sum(nums) if total % 3 != 0: return False target = total // 3 current_sum = 0 found_i = -1 for i in range(len(nums)): current_sum += nums[i] if current_sum == target: found_i = i brea...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `nums`, you need to determine if it is possible to split the array into three contiguous subarrays such that the sum of each subarray is equal. If possible, return `true`; otherwise, return `false`. Note that each subarray must contain at least one element.\nA...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4421, "level": 1, "question": "Given an array of integers `nums`, you need to determine if it is possible to split the array into three contiguous subarrays such that the sum of each subarray is equal. If possible, return `true`; otherwise, return `false`. Note that each subarray mu...
def max_subarray_sum(nums): if not nums: return 0 # Returns 0 for an empty list; can be adjusted based on requirements current_max = max_so_far = nums[0] for num in nums[1:]: current_max = max(num, current_max + num) max_so_far = max(max_so_far, current_max) return max_so_far
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the maximum sum of subarray in a given list. The function should return the maximum sum. The list can contain negative numbers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4422, "level": 1, "question": "Write a python function to find the maximum sum of subarray in a given list. The function should return the maximum sum. The list can contain negative numbers.", "split": "train" }
from typing import List def find_most_frequent_digit(numbers: List[int]) -> int: # Initialize frequency dictionary for digits 0-9 freq = {i: 0 for i in range(10)} for number in numbers: # Convert each number to a string to process each digit for digit in str(number): d = in...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement:\n\nYou are given a list of integers. Your task is to write a function `find_most_frequent_digit` that finds and returns the digit (0-9) that appears most frequently across all numbers in the list. If there is a tie (i.e., multiple digits appear with the same maxim...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4423, "level": 1, "question": "### Problem Statement:\n\nYou are given a list of integers. Your task is to write a function `find_most_frequent_digit` that finds and returns the digit (0-9) that appears most frequently across all numbers in the list. If there is a tie (i.e., multipl...
def can_transform(stacks, targetStacks): if len(stacks) != len(targetStacks): return False for s in stacks: if s < 0: return False for t in targetStacks: if t < 0: return False if sum(stacks) != sum(targetStacks): return False return True
simplelr_Leetcode
[ { "content": "Question:\nYou are given `n` stacks of coins, each represented by an integer array `stacks`, where `stacks[i]` is the number of coins in the `i-th` stack. You are also given an integer array `targetStacks` where `targetStacks[i]` is the target number of coins you want in the `i-th` stack. In one m...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4424, "level": 1, "question": "You are given `n` stacks of coins, each represented by an integer array `stacks`, where `stacks[i]` is the number of coins in the `i-th` stack. You are also given an integer array `targetStacks` where `targetStacks[i]` is the target number of coins you...
from collections import defaultdict def count_subarrays_with_sum(arr: list, target_sum: int) -> int: prefix_counts = defaultdict(int) prefix_counts[0] = 1 # Initialize with prefix sum 0 occurring once current_sum = 0 count = 0 for num in arr: current_sum += num count += prefix_cou...
simplelr_Algorithm
[ { "content": "Question:\n### Count Subarrays with Sum\n\nYou are given an array of integers and a target sum. Your task is to implement a function that finds the number of subarrays (contiguous sequences) that sum up to the target sum.\n\n#### Function Signature\n```python\ndef count_subarrays_with_sum(arr: lis...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4425, "level": 1, "question": "### Count Subarrays with Sum\n\nYou are given an array of integers and a target sum. Your task is to implement a function that finds the number of subarrays (contiguous sequences) that sum up to the target sum.\n\n#### Function Signature\n```python\nde...
def english_to_morse(text): MORSE_CODE_DICT = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '...
simplelr_Filter
[ { "content": "Question:\nYou've been asked to write a code that converts English text into Morse code.\n\nHere's the challenge:\n\n1. **Input:** The code should accept a string of English text as input.\n\n2. **Conversion:** It should convert each letter and number in the input to its corresponding Morse code r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4426, "level": 1, "question": "You've been asked to write a code that converts English text into Morse code.\n\nHere's the challenge:\n\n1. **Input:** The code should accept a string of English text as input.\n\n2. **Conversion:** It should convert each letter and number in the inpu...
import matplotlib.pyplot as plt import seaborn as sns def custom_residplot(data, x, y, order=1, lowess=False, line_color="r", save_path="residual_plot.png"): plt.figure() line_kws = None if lowess: line_kws = {'color': line_color} ax = sns.residplot(data=data, x=x, y=y, order=order, l...
simplelr_Docs
[ { "content": "Question:\nWrite a function `custom_residplot` that generates and saves a customized residual plot using the seaborn library. Your function should adhere to the following specifications:\n\n1. **Function Signature**:\n ```python\n def custom_residplot(data, x, y, order=1, lowess=False, line_co...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4427, "level": 1, "question": "Write a function `custom_residplot` that generates and saves a customized residual plot using the seaborn library. Your function should adhere to the following specifications:\n\n1. **Function Signature**:\n ```python\n def custom_residplot(data, x...
from typing import List def summarize_ranges(array: List[int]) -> List[str]: result = [] if not array: return result current_start = current_end = array[0] for num in array[1:]: if num == current_end + 1: current_end = num else: # Add the curren...
simplelr_Data_Structure
[ { "content": "Question:\n### Task\n\nYou are given a sorted list of integers with no duplicates. Write a function `summarize_ranges` that processes this list to return a summary of consecutive ranges in the format specified below.\n\n### Function Signature\n```python\ndef summarize_ranges(array: List[int]) -> L...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4428, "level": 1, "question": "### Task\n\nYou are given a sorted list of integers with no duplicates. Write a function `summarize_ranges` that processes this list to return a summary of consecutive ranges in the format specified below.\n\n### Function Signature\n```python\ndef summ...
def count_subarrays_with_sum(arr: list, t: int) -> int: """ Returns the number of subarrays that sum up to t within the given list arr. """ prefix_counts = {0: 1} # Initialize with 0 to handle cases where subarray starts from index 0 current_sum = 0 result = 0 for num in arr: curre...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are tasked with implementing a function that returns the number of subarrays with a sum equal to a given target integer `t` within a given list of integers.\n\n### Function Signature\n```python\ndef count_subarrays_with_sum(arr: list, t: int) -> int:\n \"\"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4429, "level": 1, "question": "### Problem Statement\nYou are tasked with implementing a function that returns the number of subarrays with a sum equal to a given target integer `t` within a given list of integers.\n\n### Function Signature\n```python\ndef count_subarrays_with_sum(a...
import json from collections import Counter def store_and_count_words(): sentences = [ "Happy coding to you all.", "May you find all the bugs today.", "Keep calm and code on.", "Debugging is fun if you have the right mindset.", "Happy learning, happy coding." ] # Wr...
simplelr_Package
[ { "content": "Question:\nIn this problem, you are required to write a Python function named `store_and_count_words` that utilizes the `json` and `collections` libraries. The function should perform the following tasks:\n\n1. Create a list of sentences.\n2. Store these sentences in a JSON file named `sentences.j...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4430, "level": 1, "question": "In this problem, you are required to write a Python function named `store_and_count_words` that utilizes the `json` and `collections` libraries. The function should perform the following tasks:\n\n1. Create a list of sentences.\n2. Store these sentence...
def max_product(nums): try: if len(nums) < 2: raise ValueError("Array must contain at least two elements.") sorted_nums = sorted(nums) max_product_candidate1 = sorted_nums[-1] * sorted_nums[-2] max_product_candidate2 = sorted_nums[0] * sorted_nums[1] max_product =...
simplelr_Evol
[ { "content": "Question:\nDevelop a Python function to identify the maximum product of two distinct elements within an array of integers. The function must handle potential exceptions, such as empty arrays or arrays with fewer than two elements, and return an appropriate message or value in such cases. \n\nEnsur...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4431, "level": 1, "question": "Develop a Python function to identify the maximum product of two distinct elements within an array of integers. The function must handle potential exceptions, such as empty arrays or arrays with fewer than two elements, and return an appropriate messag...
import zlib def calculate_crc32(file_path): with open(file_path, 'rb') as f: crc = 0 while True: chunk = f.read(4096) if not chunk: break crc = zlib.crc32(chunk, crc) return crc
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python code snippet to calculate the checksum of a file using the CRC32 algorithm?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4432, "level": 1, "question": "Can you provide a Python code snippet to calculate the checksum of a file using the CRC32 algorithm?", "split": "train" }
def fibonacci(n): if n <= 0: return [] fib_sequence = [] if n >= 1: fib_sequence.append(0) if n >= 2: fib_sequence.append(1) for i in range(2, n): next_num = fib_sequence[i-1] + fib_sequence[i-2] fib_sequence.append(next_num) return fib_sequence
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to generate the first n Fibonacci numbers. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence is represented as 0, 1, 1, 2, 3, 5, 8, 13, ...\nAnswer:\nLet's think step ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4433, "level": 1, "question": "Write a python function to generate the first n Fibonacci numbers. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence is represented as 0, 1, 1, 2, 3, 5, 8, ...
def fibonacci(n): """ Returns the Fibonacci sequence up to the nth term. Args: n (int): The number of terms in the sequence. Returns: list: A list containing the first n Fibonacci numbers. """ if n <= 0: return [] elif n == 1: return [0] fib_sequ...
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python code snippet to calculate the Fibonacci sequence up to the nth term?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4434, "level": 1, "question": "Can you provide a Python code snippet to calculate the Fibonacci sequence up to the nth term?", "split": "train" }
def multiply_complex(z1, z2): a = z1.real b = z1.imag c = z2.real d = z2.imag real_part = a * c - b * d imaginary_part = a * d + b * c return complex(real_part, imaginary_part)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to multiply two complex numbers in Python.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4435, "level": 1, "question": "Write a python function to multiply two complex numbers in Python.", "split": "train" }
def isWellFormed(s: str) -> bool: stack = [] mapping = { '(': ')', '{': '}', '[': ']' } for char in s: if char in mapping: stack.append(mapping[char]) else: if not stack or stack.pop() != char: return False return len(stack) == 0
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string containing only the characters '(', ')', '{', '}', '[' and ']'. Write a function to check if the given string is a well-formed string of parentheses. A string is considered well-formed if the brackets are closed in the correct order, i.e., every opening bracket ha...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4436, "level": 1, "question": "You are given a string containing only the characters '(', ')', '{', '}', '[' and ']'. Write a function to check if the given string is a well-formed string of parentheses. A string is considered well-formed if the brackets are closed in the correct or...
def selection_sort(arr): for i in range(len(arr)): min_index = i for j in range(i + 1, len(arr)): if arr[j] < arr[min_index]: min_index = j arr[i], arr[min_index] = arr[min_index], arr[i] return arr # Example usage: arr = [64, 25, 12, 22, 11] print("Original ...
simplelr_Filter
[ { "content": "Question:\nCan you explain the concept of a selection sort and provide a simple implementation in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4437, "level": 1, "question": "Can you explain the concept of a selection sort and provide a simple implementation in Python?", "split": "train" }
def findTriplets(arr, target): if len(arr) < 3: return False arr_sorted = sorted(arr) for i in range(len(arr_sorted) - 2): left = i + 1 right = len(arr_sorted) - 1 while left < right: current_sum = arr_sorted[i] + arr_sorted[left] + arr_sorted[right] i...
simplelr_Taco
[ { "content": "Question:\nYour task is to implement the function `findTriplets`. The function takes an array of integers and a target sum as arguments. The function should return `True` if there exists a triplet in the array which sums up to the target sum, otherwise it should return `False`.\n\nExample 1:\nInpu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4438, "level": 1, "question": "Your task is to implement the function `findTriplets`. The function takes an array of integers and a target sum as arguments. The function should return `True` if there exists a triplet in the array which sums up to the target sum, otherwise it should ...
def max_subarray_sum(nums): if not nums: return 0 current_sum = nums[0] max_sum = nums[0] for num in nums[1:]: current_sum = max(num, current_sum + num) if current_sum > max_sum: max_sum = current_sum return max_sum
simplelr_Filter
[ { "content": "Question:\nIn this task, you will be asked to write a Python function to find the maximum sum of a subarray within a given one-dimensional array of integers. This function should take as input a list of integers and return the maximum sum of a subarray. \n\nHere is an algorithm to solve this probl...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4439, "level": 1, "question": "In this task, you will be asked to write a Python function to find the maximum sum of a subarray within a given one-dimensional array of integers. This function should take as input a list of integers and return the maximum sum of a subarray. \n\nHere ...
def check_for_duplicate_logs(logs): seen = set() for log in logs: if log in seen: return True seen.add(log) return False
simplelr_Code_Contests
[ { "content": "Question:\nYour task is to help locate a bug in a company's software system. The system maintains log records of various operations. Each log record contains the timestamp of when the operation occurred and a unique operation identifier. The company suspects that the system log might contain dupli...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4440, "level": 1, "question": "Your task is to help locate a bug in a company's software system. The system maintains log records of various operations. Each log record contains the timestamp of when the operation occurred and a unique operation identifier. The company suspects that...
def gnome_sort(arr: list[int]) -> list[int]: n = len(arr) if n <= 1: return arr index = 1 while index < n: if arr[index - 1] <= arr[index]: index += 1 else: arr[index], arr[index - 1] = arr[index - 1], arr[index] if index > 1: i...
simplelr_Data_Structure
[ { "content": "Question:\n### Gnome Sort Implementation Challenge\n\nYou are tasked with implementing the Gnome Sort algorithm to sort a list of integers. The Gnome Sort algorithm is a simple sorting algorithm that iterates through the list and whenever an element is found out of order compared to its previous e...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4441, "level": 1, "question": "### Gnome Sort Implementation Challenge\n\nYou are tasked with implementing the Gnome Sort algorithm to sort a list of integers. The Gnome Sort algorithm is a simple sorting algorithm that iterates through the list and whenever an element is found out ...
def is_valid_parentheses(s): stack = [] matching = {')': '(', '}': '{', ']': '['} opening = set(matching.values()) closing = set(matching.keys()) for char in s: if char in opening: stack.append(char) elif char in closing: if not stack: ret...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to check if the parentheses in a string are correctly matched.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4442, "level": 1, "question": "Write a function to check if the parentheses in a string are correctly matched.", "split": "train" }
def partition(lst, pivot): less = [x for x in lst if x < pivot] equal = [x for x in lst if x == pivot] greater = [x for x in lst if x > pivot] return less + equal + greater
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to partition a given list of integers around a pivot value, such that all elements less than the pivot are on the left, and all elements greater than the pivot are on the right. The pivot element itself should be in its correct position. This is similar to the pa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4443, "level": 1, "question": "Write a python function to partition a given list of integers around a pivot value, such that all elements less than the pivot are on the left, and all elements greater than the pivot are on the right. The pivot element itself should be in its correct ...
import math def find_perfect_squares(numbers: list[int]) -> list[int]: result = [] seen = set() for num in numbers: # Check if the number is an integer and not a boolean if not (isinstance(num, int) and not isinstance(num, bool)): continue if num < 0: continu...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question: Perfect Square Identifier\n\n#### Context\nYou need to identify and return a list of numbers that are perfect squares from a given list of integers. A perfect square is an integer that is the square of another integer.\n\n#### Task\nWrite a function `find...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4444, "level": 1, "question": "### Coding Assessment Question: Perfect Square Identifier\n\n#### Context\nYou need to identify and return a list of numbers that are perfect squares from a given list of integers. A perfect square is an integer that is the square of another integer.\n...
def grams_to_kilograms(grams): """ Converts a given weight in grams to kilograms. Args: grams (int or float): The weight in grams. Returns: float: The weight in kilograms. """ return grams / 1000.0
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to convert grams to kilograms.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4445, "level": 1, "question": "Write a python function to convert grams to kilograms.", "split": "train" }
def reverse_string_using_stack(s): stack = [] for char in s: stack.append(char) reversed_str = "" while stack: reversed_str += stack.pop() return reversed_str
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that reverses the characters in a string using a stack data structure?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4446, "level": 1, "question": "How can I create a Python function that reverses the characters in a string using a stack data structure?", "split": "train" }
import seaborn as sns import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap def visualize_data(df, cat_column, num_columns, num_colors): # Create a bar plot with the 'Set2' colormap for the categorical data unique_categories = len(df[cat_column].uni...
simplelr_Docs
[ { "content": "Question:\nYou are given a dataset containing numerical and categorical data. Your task is to visualize this data using seaborn, focusing on colormap manipulation to create distinct and informative plots. Specifically, you will need to utilize the `mpl_palette` function to address the following re...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4447, "level": 1, "question": "You are given a dataset containing numerical and categorical data. Your task is to visualize this data using seaborn, focusing on colormap manipulation to create distinct and informative plots. Specifically, you will need to utilize the `mpl_palette` f...
def count_unique_pairs(arr, target): val_to_index = {val: idx for idx, val in enumerate(arr)} count = 0 for i in range(len(arr)): complement = target - arr[i] if complement in val_to_index: j = val_to_index[complement] if j > i: count += 1 return c...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of distinct integers `arr` and an integer `target`, return the number of unique pairs `(i, j)` such that `arr[i] + arr[j] == target`, where `i` and `j` are indices of the array and `i < j`. Note that the pairs `(i, j)` and `(j, i)` are considered the same and should be co...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4448, "level": 1, "question": "Given an array of distinct integers `arr` and an integer `target`, return the number of unique pairs `(i, j)` such that `arr[i] + arr[j] == target`, where `i` and `j` are indices of the array and `i < j`. Note that the pairs `(i, j)` and `(j, i)` are c...
def longest_consecutive_subsequence(arr): s = set(arr) max_length = 0 for num in s: current_length = 0 current_num = num while current_num in s: current_length += 1 current_num += 1 if current_length > max_length: max_length = current_lengt...
simplelr_Leetcode
[ { "content": "Question:\nImplement a function that takes in a list of integers `arr` and returns the length of the longest subsequence such that all elements of the subsequence are consecutive integers. The consecutive numbers can be in any order. For example, for the input list `[4, 2, 1, 6, 5]`, the longest ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4449, "level": 1, "question": "Implement a function that takes in a list of integers `arr` and returns the length of the longest subsequence such that all elements of the subsequence are consecutive integers. The consecutive numbers can be in any order. For example, for the input l...
def split_into_words(s): return s.split()
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string and returns a list of words separated by spaces.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4450, "level": 1, "question": "Create a function that takes a string and returns a list of words separated by spaces.", "split": "train" }
def negate_every_other_integer(integers): return [x if i % 2 == 0 else -x for i, x in enumerate(integers)]
simplelr_Filter
[ { "content": "Question:\nGiven a list of words, write a program to reverse every other word in the list, starting with the second word. \n\nFor example, given the list [\"hello\", \"world\", \"python\", \"code\"], the output should be [\"hello\", \"dlrow\", \"python\", \"edoc\"]. \n\nHere's a Python solution:\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4451, "level": 1, "question": "Given a list of words, write a program to reverse every other word in the list, starting with the second word. \n\nFor example, given the list [\"hello\", \"world\", \"python\", \"code\"], the output should be [\"hello\", \"dlrow\", \"python\", \"edoc\...
import heapq def kthSmallest(matrix, k): if not matrix or not matrix[0]: return None rows = len(matrix) cols = len(matrix[0]) heap = [] # Push the first element of each row into the heap for i in range(rows): heapq.heappush(heap, (matrix[i][0], i, 0)) count = 0 ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a matrix where each row is sorted in ascending order and each column is sorted in ascending order. Write a function to find the k-th smallest element in the matrix. It is guaranteed that k is between 1 and the total number of elements in the matrix. \n\n**Example:**\nGiven...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4452, "level": 1, "question": "You are given a matrix where each row is sorted in ascending order and each column is sorted in ascending order. Write a function to find the k-th smallest element in the matrix. It is guaranteed that k is between 1 and the total number of elements in ...
def sum_of_squares_of_evens(n): """ Calculate the sum of the squares of all even numbers between 1 and n. Args: n (int): The upper limit (inclusive). Must be a positive integer. Returns: int: The sum of the squares of all even numbers up to n. Raises: ValueErro...
simplelr_Filter
[ { "content": "Question:\nWrite a Python program that calculates the sum of the squares of all even numbers between 1 and a given number n. Ensure your code is efficient and handles edge cases such as negative inputs or non-integer inputs. Include comments to explain key parts of your code.\nAnswer:\nLet's think...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4453, "level": 1, "question": "Write a Python program that calculates the sum of the squares of all even numbers between 1 and a given number n. Ensure your code is efficient and handles edge cases such as negative inputs or non-integer inputs. Include comments to explain key parts ...
import numpy as np from scipy import spatial def knn_anomaly_detection(data, k, threshold): """ Detects anomalies in a dataset using the k-Nearest Neighbors algorithm. Parameters: - data: A 2D NumPy array of shape (n_samples, n_features) representing the dataset. - k: The number of nearest neighbo...
simplelr_Algorithm
[ { "content": "Question:\n### Question: Anomaly Detection using k-Nearest Neighbors\n\nAs part of a machine learning project, you are tasked with developing an anomaly detection system using the k-Nearest Neighbors (k-NN) algorithm. Your goal is to implement a function that detects anomalies in a dataset and ret...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4454, "level": 1, "question": "### Question: Anomaly Detection using k-Nearest Neighbors\n\nAs part of a machine learning project, you are tasked with developing an anomaly detection system using the k-Nearest Neighbors (k-NN) algorithm. Your goal is to implement a function that det...
import string def is_pangram(s): alphabet = set(string.ascii_lowercase) s_lower = set(s.lower()) return s_lower.issuperset(alphabet)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check if a string is a pangram. A pangram is a sentence containing every letter of the alphabet at least once.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4455, "level": 1, "question": "Write a python function to check if a string is a pangram. A pangram is a sentence containing every letter of the alphabet at least once.", "split": "train" }
def intersection_of_lists(list1, list2): return sorted(set(list1) & set(list2))
simplelr_Filter
[ { "content": "Question:\nCreate a python function which finds the intersection of two lists and returns a sorted list of the common elements.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4456, "level": 1, "question": "Create a python function which finds the intersection of two lists and returns a sorted list of the common elements.", "split": "train" }
from typing import List def rotate_matrix(matrix: List[List[int]]) -> None: n = len(matrix) # Transpose the matrix for i in range(n): for j in range(i + 1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # Reverse each row for row in matrix: row.reverse()
simplelr_Apps
[ { "content": "Question:\n*** Matrix Rotation ***\n\nIn this exercise, you are given a square matrix represented as a 2D list. Write a function to rotate the matrix 90 degrees clockwise. The matrix has NxN dimensions where N is the number of rows (and columns) of the matrix. You are not allowed to use any additi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4457, "level": 1, "question": "*** Matrix Rotation ***\n\nIn this exercise, you are given a square matrix represented as a 2D list. Write a function to rotate the matrix 90 degrees clockwise. The matrix has NxN dimensions where N is the number of rows (and columns) of the matrix. Yo...
def min_cost_to_combine_items(values): n = len(values) if n == 0: return 0 # Compute prefix sums prefix = [0] * (n + 1) for i in range(n): prefix[i+1] = prefix[i] + values[i] # Initialize DP table dp = [[0] * n for _ in range(n)] for length in range(2, n+1): ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array `values` where each `values[i]` represents the value of a unique item. You can combine any two **adjacent** items into a single item whose value is the sum of the two individual items, and this combination process costs the sum of the values of the items. Return _...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4458, "level": 1, "question": "You are given an array `values` where each `values[i]` represents the value of a unique item. You can combine any two **adjacent** items into a single item whose value is the sum of the two individual items, and this combination process costs the sum o...
def filter_even_numbers(numbers): return [num for num in numbers if num % 2 == 0]
simplelr_Filter
[ { "content": "Question:\nPlease provide a Python function that takes a list of numbers and returns a new list containing only the even numbers from the original list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4459, "level": 1, "question": "Please provide a Python function that takes a list of numbers and returns a new list containing only the even numbers from the original list.", "split": "train" }
import re def is_valid_email(email): pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" return bool(re.match(pattern, email)) # Example usage: # print(validate_email("test@example.com")) # Returns: True # print(validate_email("invalid@example")) # Returns: False
simplelr_Prefill
[ { "content": "Question:\nCreate a function that will validate an email address format.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4460, "level": 1, "question": "Create a function that will validate an email address format.", "split": "train" }
def move_zeros(array: list) -> list: non_zeros = [] zeros = [] for elem in array: if elem == 0 and type(elem) is not bool: zeros.append(elem) else: non_zeros.append(elem) return non_zeros + zeros
simplelr_Data_Structure
[ { "content": "Question:\n### Array Manipulation Challenge: Move Zeros to the End\n\n#### Context\nYou are tasked with cleaning up an array by moving all zero values to the end. This is common in data cleaning operations where zero values are considered irrelevant or placeholders for missing data.\n\n#### Object...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4461, "level": 1, "question": "### Array Manipulation Challenge: Move Zeros to the End\n\n#### Context\nYou are tasked with cleaning up an array by moving all zero values to the end. This is common in data cleaning operations where zero values are considered irrelevant or placeholde...
def even_numbers(numbers): return [num for num in numbers if num % 2 == 0]
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a list of integers and returns a new list containing only the even numbers from the original list.\n\n``` \nInput: [1, 2, 3, 4, 5, 6]\nOutput: [2, 4, 6]\n```\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4462, "level": 1, "question": "Write a function that takes a list of integers and returns a new list containing only the even numbers from the original list.\n\n``` \nInput: [1, 2, 3, 4, 5, 6]\nOutput: [2, 4, 6]\n```", "split": "train" }
import numpy as np def generate_mandelbrot_set(width: int, height: int, x_min: float, x_max: float, y_min: float, y_max: float, max_iterations: int) -> np.ndarray: """ Generate Mandelbrot set and return a matrix of iteration counts. Args: width: Width of the output image. height: Heigh...
simplelr_Algorithm
[ { "content": "Question:\n### Context:\nIn this task, you will be required to implement a function that generates a Mandelbrot set image. The Mandelbrot set is a set of complex numbers for which the function does not diverge when iterated.\n\n### Function Specification:\nImplement a function `generate_mandelbrot...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4463, "level": 1, "question": "### Context:\nIn this task, you will be required to implement a function that generates a Mandelbrot set image. The Mandelbrot set is a set of complex numbers for which the function does not diverge when iterated.\n\n### Function Specification:\nImplem...
def binary_to_integer(binary_string): return int(binary_string, 2)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that converts a binary string to an integer. The binary string consists of only '1's and '0's. Assume the binary string is non-empty and does not contain any leading zeros. You should handle cases where the binary string represents a large number. How would you approac...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4464, "level": 1, "question": "Create a function that converts a binary string to an integer. The binary string consists of only '1's and '0's. Assume the binary string is non-empty and does not contain any leading zeros. You should handle cases where the binary string represents a ...
def shortest_word_length(s): words = s.split() if not words: return 0 return min(len(word) for word in words)
simplelr_Taco
[ { "content": "Question:\nWrite a function that takes a string as input and returns the length of the shortest word in the string. For the purposes of this task, a word is defined as any sequence of non-space characters. Punctuation and digits count as part of the word.\n\n```\nExample:\nInput: \"The quick brown...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4465, "level": 1, "question": "Write a function that takes a string as input and returns the length of the shortest word in the string. For the purposes of this task, a word is defined as any sequence of non-space characters. Punctuation and digits count as part of the word.\n\n```\...
from typing import List def canReachEnd(arr: List[int]) -> bool: max_reach = 0 n = len(arr) for i in range(n): if i > max_reach: return False max_reach = max(max_reach, i + arr[i]) if max_reach >= n - 1: return True return False
simplelr_Taco
[ { "content": "Question:\nYou are given an array of integers where each element represents the maximum length you can jump forward from that position. Write a function `canReachEnd(arr)` that determines if you can reach the last index starting from the first index. You can assume that the input array will contai...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4466, "level": 1, "question": "You are given an array of integers where each element represents the maximum length you can jump forward from that position. Write a function `canReachEnd(arr)` that determines if you can reach the last index starting from the first index. You can assu...
def fibonacci(n): if n < 0: return [] fib_sequence = [0] if n == 0: return fib_sequence fib_sequence.append(1) while True: next_num = fib_sequence[-1] + fib_sequence[-2] if next_num > n: break fib_sequence.append(next_num) return fib_sequence
simplelr_Filter
[ { "content": "Question:\nCan you provide me with a code snippet to generate Fibonacci numbers up to a given number `n`?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4467, "level": 1, "question": "Can you provide me with a code snippet to generate Fibonacci numbers up to a given number `n`?", "split": "train" }
def rearrange_string(input_str: str) -> str: letters = [] digits = [] for c in input_str: if c.isalpha(): letters.append(c) else: digits.append(c) return ''.join(letters) + ''.join(digits)
simplelr_Taco
[ { "content": "Question:\nYou have a string consisting of randomly placed numbers and letters. Your task is to rearrange the characters so that all digits are placed at the end of the string while preserving the relative order of appearance of both the letters and the digits.\n\n### Function Signature\n```python...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4468, "level": 1, "question": "You have a string consisting of randomly placed numbers and letters. Your task is to rearrange the characters so that all digits are placed at the end of the string while preserving the relative order of appearance of both the letters and the digits.\n...
def compress_string(s: str) -> str: if not s: return s current_char = s[0] count = 1 compressed = [] for char in s[1:]: if char == current_char: count += 1 else: compressed.append(current_char + str(count)) current_char = char ...
simplelr_Apps
[ { "content": "Question:\n# String Compressor\n\n## Task\n\nImplement a function to perform basic string compression using the counts of repeated characters. For example, the string `\"aabcccccaaa\"` would become `\"a2b1c5a3\"`. If the compressed string would not become smaller than the original string, your fun...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4469, "level": 1, "question": "# String Compressor\n\n## Task\n\nImplement a function to perform basic string compression using the counts of repeated characters. For example, the string `\"aabcccccaaa\"` would become `\"a2b1c5a3\"`. If the compressed string would not become smaller...
def min_total_distance(nums): nums.sort() n = len(nums) median = nums[n // 2] total = 0 for num in nums: total += abs(num - median) return total
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of integers `nums`, where each integer represents a position on a number line. Your task is to find the minimum total distance required to align all the positions such that they are at the same point. Note that you can choose any point on the number line as the al...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4470, "level": 1, "question": "You are given an array of integers `nums`, where each integer represents a position on a number line. Your task is to find the minimum total distance required to align all the positions such that they are at the same point. Note that you can choose any...
from typing import List def first_occurrence(array: List[int], query: int) -> int: if not array: return -1 result = -1 low, high = 0, len(array) - 1 while low <= high: mid = (low + high) // 2 if array[mid] == query: result = mid high = mid - 1 eli...
simplelr_Data_Structure
[ { "content": "Question:\nYou are tasked with finding the index of the first occurrence of a target value in a sorted array of integers. The array is sorted in increasing order and may contain duplicate values. Implement the function `first_occurrence` to achieve this.\n\n### Function Signature\n\n```python\ndef...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4471, "level": 1, "question": "You are tasked with finding the index of the first occurrence of a target value in a sorted array of integers. The array is sorted in increasing order and may contain duplicate values. Implement the function `first_occurrence` to achieve this.\n\n### F...
import re def parse_report(report: str) -> dict: # Split the report into lines and strip any leading/trailing whitespace lines = [line.strip() for line in report.strip().split('\n')] # Extract Title, Date, and Author from the first three non-empty lines title, date, author = '', '', '' if line...
simplelr_Docs
[ { "content": "Question:\n**Title: Regex-based Report Parsing**\n\n**Objective:**\nYour task is to implement a function that parses a structured report using regular expressions. The report contains various sections, and your function should extract specific information from it.\n\n**Problem Statement:**\n\nYou ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4472, "level": 1, "question": "**Title: Regex-based Report Parsing**\n\n**Objective:**\nYour task is to implement a function that parses a structured report using regular expressions. The report contains various sections, and your function should extract specific information from it...
def reverse_string(s): return s[::-1]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to reverse a given string, but keep the original string unchanged.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4473, "level": 1, "question": "Write a python function to reverse a given string, but keep the original string unchanged.", "split": "train" }
def euler_totient(n: int) -> int: if n == 1: return 1 result = n i = 2 while i * i <= n: if n % i == 0: while n % i == 0: n //= i result = result // i * (i - 1) i += 1 if n > 1: result = result // n * (n - 1) return result
simplelr_Data_Structure
[ { "content": "Question:\n### Euler's Totient Function Implementation\n\n#### Background\nEuler's Totient function, ϕ(n), gives the number of integers from 1 to n which are coprime to n. Two numbers are defined as coprime if their greatest common divisor (GCD) is 1.\n\n#### Problem Statement\nWrite a function `e...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4474, "level": 1, "question": "### Euler's Totient Function Implementation\n\n#### Background\nEuler's Totient function, ϕ(n), gives the number of integers from 1 to n which are coprime to n. Two numbers are defined as coprime if their greatest common divisor (GCD) is 1.\n\n#### Pro...
def maximal_square(matrix: list[list[int]]) -> int: if not matrix or not matrix[0]: return 0 r = len(matrix) c = len(matrix[0]) max_size = 0 prev = [0] * c # Previous row's dynamic programming values for i in range(r): curr = [0] * c for j in range(c): if m...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement: Maximal Square of 1's in Binary Matrix\n\nYou are given a binary matrix `m` of size `r x c` (where each element is either 0 or 1). Your task is to find the side length of the largest square containing only `1`s in the matrix.\n\n### Detailed Requirements:\n\n- You...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4475, "level": 1, "question": "### Problem Statement: Maximal Square of 1's in Binary Matrix\n\nYou are given a binary matrix `m` of size `r x c` (where each element is either 0 or 1). Your task is to find the side length of the largest square containing only `1`s in the matrix.\n\n...
def generate_numbers(n): numbers = [str(i) for i in range(1, n+1)] return ','.join(numbers)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that generates a comma-separated string of numbers from 1 to n.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4476, "level": 1, "question": "Create a function that generates a comma-separated string of numbers from 1 to n.", "split": "train" }
from typing import List def stoogesort(arr: List[int], l: int, h: int) -> None: if l >= h: return # Swap if the first element is larger than the last if arr[l] > arr[h]: arr[l], arr[h] = arr[h], arr[l] # If the segment length is more than 2, divide and recurse if h - l + 1 > 2: ...
simplelr_Data_Structure
[ { "content": "Question:\n### Advanced Sorting Implementation: Stooge Sort\n\n**Problem Statement**: Given an array of integers, implement the Stooge Sort algorithm to sort the array in ascending order.\n\n**Function Signature**:\n```python\ndef stoogesort(arr: List[int], l: int, h: int) -> None:\n # your cod...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4477, "level": 1, "question": "### Advanced Sorting Implementation: Stooge Sort\n\n**Problem Statement**: Given an array of integers, implement the Stooge Sort algorithm to sort the array in ascending order.\n\n**Function Signature**:\n```python\ndef stoogesort(arr: List[int], l: in...
from collections import deque def find_word_ladder(start, end, word_list): if start == end: return [start] if len(start) != len(end): return [] word_set = set(word_list) if end not in word_set: return [] queue = deque() queue.append((start, [start])) visite...
simplelr_Package
[ { "content": "Question:\n---\nWrite a function named `find_word_ladder` that generates the shortest sequence of words (word ladder) from a given start word to an end word. \n\nA word ladder is defined such that:\n\n1. Each word in the ladder changes exactly one character from the previous word.\n2. Each interme...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4478, "level": 1, "question": "---\nWrite a function named `find_word_ladder` that generates the shortest sequence of words (word ladder) from a given start word to an end word. \n\nA word ladder is defined such that:\n\n1. Each word in the ladder changes exactly one character from ...
def sum_excluding_self(lst): total = sum(lst) return [total - x for x in lst]
simplelr_Evol
[ { "content": "Question:\nWrite a Python function that receives a list of integers and returns a new list where each element is the sum of all elements in the original list excluding the element at the corresponding index. For example, given the list [1, 2, 3, 4], the function should return [9, 8, 7, 6].\nAnswer...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4479, "level": 1, "question": "Write a Python function that receives a list of integers and returns a new list where each element is the sum of all elements in the original list excluding the element at the corresponding index. For example, given the list [1, 2, 3, 4], the function ...
def find_consecutive_sequences(lst, k): if k <= 0: return [] return [lst[i:i+k] for i in range(len(lst) - k + 1)]
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that finds all the consecutive sequences of a given length in a list. For example, if the input list is `[1, 2, 3, 4, 5]` and the sequence length is `3`, the output should be `[[1, 2, 3], [2, 3, 4], [3, 4, 5]]`.\nAnswer:\nLet's think step by step.\n", "role":...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4480, "level": 1, "question": "Write a Python function that finds all the consecutive sequences of a given length in a list. For example, if the input list is `[1, 2, 3, 4, 5]` and the sequence length is `3`, the output should be `[[1, 2, 3], [2, 3, 4], [3, 4, 5]]`.", "split": "tr...
def bibliographic_summary(books): sorted_books = sorted(books, key=lambda x: x[0]) formatted = [f"{title} {year}" for title, year in sorted_books] return '\n'.join(formatted)
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nYou are contributing to a library management system that helps in categorizing books and their authors. One feature needed is to generate a bibliographic summary of an author's works given a list of their books and publication years. The ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4481, "level": 1, "question": "### Coding Assessment Question\n\n#### Scenario\nYou are contributing to a library management system that helps in categorizing books and their authors. One feature needed is to generate a bibliographic summary of an author's works given a list of thei...
def typewriter_display(N, S): displays = [] for i in range(len(S)): current = S[:i+1] if len(current) > N: displays.append(current[-N:]) else: displays.append(current.ljust(N, '.')) return displays
simplelr_Taco
[ { "content": "Question:\nCreate a function that simulates a simple version of an old-style typewriter. The typewriter has a single row of characters and can print only one character at a time, moving from left to right. When it reaches the end of the row, it moves back to the start. Additionally, the typewriter...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4482, "level": 1, "question": "Create a function that simulates a simple version of an old-style typewriter. The typewriter has a single row of characters and can print only one character at a time, moving from left to right. When it reaches the end of the row, it moves back to the ...
def reverse_list(lst): return lst[::-1]
simplelr_Filter
[ { "content": "Question:\nYou've been tasked with creating a function to reverse the order of elements in a given list. The list may contain duplicate elements, and the function should be able to handle this. Implement the function in Python.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4483, "level": 1, "question": "You've been tasked with creating a function to reverse the order of elements in a given list. The list may contain duplicate elements, and the function should be able to handle this. Implement the function in Python.", "split": "train" }
def tuples_to_dict(tuples_list): result = {} for key, value in tuples_list: if key in result: result[key].append(value) else: result[key] = [value] return result
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of tuples, with each tuple consisting of two elements, a key and a value. The function should return a dictionary where the keys are the first elements of the tuples, and the values are lists containing all the corresponding values from the tuples.\nA...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4484, "level": 1, "question": "Create a function that takes a list of tuples, with each tuple consisting of two elements, a key and a value. The function should return a dictionary where the keys are the first elements of the tuples, and the values are lists containing all the corre...
def find_first_occurrence(arr, x): low = 0 high = len(arr) - 1 result = -1 while low <= high: mid = (low + high) // 2 if arr[mid] < x: low = mid + 1 elif arr[mid] > x: high = mid - 1 else: result = mid high = mid - 1 # Cont...
simplelr_Filter
[ { "content": "Question:\nfind the position of the first occurrence of an element x in a sorted array that may have duplicates. If the element is not present in the array, return -1. Explain the approach to solve this problem and provide a Python code snippet to demonstrate your solution.\nAnswer:\nLet's think s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4485, "level": 1, "question": "find the position of the first occurrence of an element x in a sorted array that may have duplicates. If the element is not present in the array, return -1. Explain the approach to solve this problem and provide a Python code snippet to demonstrate you...
import heapq from collections import Counter def reorganize_string(s): count = Counter(s) n = len(s) max_freq = (n + 1) // 2 # Check if any character's frequency exceeds the allowed maximum for v in count.values(): if v > max_freq: return "" # Create a max heap usi...
simplelr_Filter
[ { "content": "Question:\nI want to create an algorithm that will take a string and reorder its characters so that no two adjacent characters are the same. If it's not possible to reorder the characters in such a way, the algorithm should return an empty string.\nAnswer:\nLet's think step by step.\n", "role"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4486, "level": 1, "question": "I want to create an algorithm that will take a string and reorder its characters so that no two adjacent characters are the same. If it's not possible to reorder the characters in such a way, the algorithm should return an empty string.", "split": "t...
from collections import deque def sliding_window_max(nums, k): dq = deque() result = [] for i in range(len(nums)): # Remove elements from the end which are smaller than current while dq and nums[i] >= nums[dq[-1]]: dq.pop() dq.append(i) # Remove elements from fro...
simplelr_Taco
[ { "content": "Question:\nYou are tasked with implementing a sliding window maximum algorithm. Given an integer array `nums` and a sliding window size `k`, you need to find the maximum value in each sliding window.\n\nSpecifically, you need to create a function `sliding_window_max(nums, k)` that returns a list o...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4487, "level": 1, "question": "You are tasked with implementing a sliding window maximum algorithm. Given an integer array `nums` and a sliding window size `k`, you need to find the maximum value in each sliding window.\n\nSpecifically, you need to create a function `sliding_window_...
from typing import List def daily_temperatures(temperatures: List[int]) -> List[int]: stack = [] result = [0] * len(temperatures) for i in range(len(temperatures)): while stack and temperatures[i] > temperatures[stack[-1]]: popped = stack.pop() result[popped] = i - popped ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem: Daily Temperature Tracker\n\nYou are required to implement the function `daily_temperatures(temperatures: List[int]) -> List[int]`. This function receives:\n- `temperatures`: a list of integers where each value represents the daily temperature recorded in a city.\n\nYour go...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4488, "level": 1, "question": "### Problem: Daily Temperature Tracker\n\nYou are required to implement the function `daily_temperatures(temperatures: List[int]) -> List[int]`. This function receives:\n- `temperatures`: a list of integers where each value represents the daily tempera...
def longest_common_subsequence(s1: str, s2: str) -> int: m = len(s1) n = len(s2) # Create a DP table initialized with zeros dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if s1[i-1] == s2[j-1]: dp[i][j] = dp[i-1][j-1...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Context\nThe task involves determining the longest common subsequence (LCS) between two strings, a classic problem in computer science, particularly within the domains of bioinformatics and natural language processing. Calculating the LCS is instru...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4489, "level": 1, "question": "### Coding Assessment Question\n\n#### Context\nThe task involves determining the longest common subsequence (LCS) between two strings, a classic problem in computer science, particularly within the domains of bioinformatics and natural language proces...
def contains_nearby_duplicate(nums, k): last_occurrence = {} for i, num in enumerate(nums): if num in last_occurrence: if i - last_occurrence[num] <= k: return True last_occurrence[num] = i return False
simplelr_Leetcode
[ { "content": "Question:\n**[Question 4]:** Given an array of integers and an integer `k`, return `true` if there are two distinct indices `i` and `j` in the array such that `nums[i]` is equal to `nums[j]` and the absolute difference between `i` and `j` is at most `k`. Otherwise, return `false`.\nAnswer:\nLet's ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4490, "level": 1, "question": "**[Question 4]:** Given an array of integers and an integer `k`, return `true` if there are two distinct indices `i` and `j` in the array such that `nums[i]` is equal to `nums[j]` and the absolute difference between `i` and `j` is at most `k`. Otherwis...
def generate_multiplication_table(number): table = [] for i in range(1, 11): product = number * i table.append(f"{number} x {i} = {product}") return table
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to generate a multiplication table for a given number up to 10. The function should take an integer as input and return a list of strings, where each string represents a line in the multiplication table.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4491, "level": 1, "question": "Write a Python function to generate a multiplication table for a given number up to 10. The function should take an integer as input and return a list of strings, where each string represents a line in the multiplication table.", "split": "train" }
from collections import deque def level_order_traversal(nodes): if not nodes or nodes[0] is None: return [] result = [] q = deque() q.append(0) while q: level_length = len(q) current_level = [] for _ in range(level_length): index = q.popleft() ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a binary tree represented as a list `nodes`, where `nodes[i]` represents the value of the `i-th` node. The left child of the node at index `i` is located at index `2*i + 1` and the right child is at index `2*i + 2`. Some nodes may be `null`, indicating that the node does n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4492, "level": 1, "question": "You are given a binary tree represented as a list `nodes`, where `nodes[i]` represents the value of the `i-th` node. The left child of the node at index `i` is located at index `2*i + 1` and the right child is at index `2*i + 2`. Some nodes may be `nul...
def my_function(*args): return sum(args)
simplelr_Filter
[ { "content": "Question:\nI've been having some trouble understanding how to write a function that can take in multiple arguments. I was wondering how to write a function that can take in a variable number of arguments in Python.\n\nHere is an example function that I have so far:\n```\ndef my_function(a, b, c):\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4493, "level": 1, "question": "I've been having some trouble understanding how to write a function that can take in multiple arguments. I was wondering how to write a function that can take in a variable number of arguments in Python.\n\nHere is an example function that I have so fa...
def sum_to_n(n): if n < 1: return 0 return n * (n + 1) // 2
simplelr_Filter
[ { "content": "Question:\nPlese help me write a Python function that calculates the sum of all integers from 1 to a given number `n`. The function should be named `sum_to_n` and should take a single integer `n` as its parameter. The function should return the sum of all integers from 1 to `n`. For example, `sum_...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4494, "level": 1, "question": "Plese help me write a Python function that calculates the sum of all integers from 1 to a given number `n`. The function should be named `sum_to_n` and should take a single integer `n` as its parameter. The function should return the sum of all integer...
def has_pair_with_sum(numbers, target_sum): """ Checks if there are two numbers in a list that add up to a target sum. Args: numbers (list): A list of numbers. target_sum (int): The target sum to check for. Returns: bool: True if a pair exists that sums to the target, False oth...
simplelr_Filter
[ { "content": "Question:\n. Implement a Python function that takes two arguments:\n - A list of numbers.\n - A target sum.\n \n The function should return True if there exist two numbers in the list that add up to the target sum, and False otherwise.\n\n For example:\n - has_pair_with_sum([1, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4495, "level": 1, "question": ". Implement a Python function that takes two arguments:\n - A list of numbers.\n - A target sum.\n \n The function should return True if there exist two numbers in the list that add up to the target sum, and False otherwise.\n\n For exa...
from typing import List def two_sum(nums: List[int], target: int) -> List[int]: num_map = {} for i, num in enumerate(nums): complement = target - num if complement in num_map: return [num_map[complement], i] num_map[num] = i return []
simplelr_Apps
[ { "content": "Question:\nGiven an array of integers, return the indices of the two numbers that add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.\n\n### Function Signature\n```python\ndef two_sum(nums: List[int], target: int)...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4496, "level": 1, "question": "Given an array of integers, return the indices of the two numbers that add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.\n\n### Function Signature\n```python\ndef tw...
import string from collections import Counter def find_top_k_words(file_path, stop_words, k): try: with open(file_path, 'r') as f: text = f.read() except FileNotFoundError: raise FileNotFoundError(f"File {file_path} not found.") text_lower = text.lower() tokens = text_l...
simplelr_Algorithm
[ { "content": "Question:\n### Scenario\nYou are tasked with developing a utility to process large text files. A common requirement is to identify the top-k most frequent words in a document, excluding a given list of stop words. To accomplish this, you decide to create a Python function that reads a text file, p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4497, "level": 1, "question": "### Scenario\nYou are tasked with developing a utility to process large text files. A common requirement is to identify the top-k most frequent words in a document, excluding a given list of stop words. To accomplish this, you decide to create a Python...
def towers_of_hanoi(n, source, destination, auxiliary): if n == 1: print(f"Move disk 1 from {source} to {destination}") else: towers_of_hanoi(n - 1, source, auxiliary, destination) print(f"Move disk {n} from {source} to {destination}") towers_of_hanoi(n - 1, auxiliary, destinatio...
simplelr_Filter
[ { "content": "Question:\nFor this week's \"Coding Challenge\", we ask you to write code that implements the **Towers of Hanoi** puzzle.\n\n**Background:**\n\nThe Towers of Hanoi is a classic mathematical puzzle consisting of three rods (let's call them A, B, and C) and a number of disks of different sizes which...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4498, "level": 1, "question": "For this week's \"Coding Challenge\", we ask you to write code that implements the **Towers of Hanoi** puzzle.\n\n**Background:**\n\nThe Towers of Hanoi is a classic mathematical puzzle consisting of three rods (let's call them A, B, and C) and a numbe...
def pairSum(arr, target): seen = set() result = [] for num in arr: complement = target - num if complement in seen: result.append([complement, num]) seen.add(num) return result
simplelr_Taco
[ { "content": "Question:\nGiven an array of distinct integers, find all pairs of elements that sum up to a given target number. Each pair should be returned as a list of two elements, and the result should be a list of lists where each inner list represents a pair. The pairs can be returned in any order.\n\nExam...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4499, "level": 1, "question": "Given an array of distinct integers, find all pairs of elements that sum up to a given target number. Each pair should be returned as a list of two elements, and the result should be a list of lists where each inner list represents a pair. The pairs ca...