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 average_grade(students, subject): total = 0 for student in students: total += student.get(subject, 0) if not students: return 0.00 average = total / len(students) return round(average, 2)
simplelr_Apps
[ { "content": "Question:\nYou are given two parameters, `students` (an array of dictionaries) and `subject` (a string). Each dictionary in `students` contains the name of a student and their grades in various subjects in the form of key-value pairs. Your task is to find the average grade for the given subject ac...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8000, "level": 1, "question": "You are given two parameters, `students` (an array of dictionaries) and `subject` (a string). Each dictionary in `students` contains the name of a student and their grades in various subjects in the form of key-value pairs. Your task is to find the ave...
import string from collections import Counter def word_frequency(text): # Convert the text to lowercase to ensure case insensitivity text_lower = text.lower() # Split the text into words based on whitespace words = text_lower.split() # Clean each word by stripping leading and trailing punctuation ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the frequency of each word in a text.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8001, "level": 1, "question": "Write a python function to find the frequency of each word in a text.", "split": "train" }
def extended_gcd(num1, num2): """ Extended GCD algorithm. Return s, t, g such that num1 * s + num2 * t = GCD(num1, num2) and s and t are co-prime. Args: num1 (int): First integer num2 (int): Second integer Returns: int, int, int: Coefficients s, t and GCD of num1 an...
simplelr_Data_Structure
[ { "content": "Question:\n### Question\n\n#### Context:\nYou are tasked with implementing a function to find the coefficients of Bézout's identity for two given integers \\(num1\\) and \\(num2\\). These coefficients \\(s\\) and \\(t\\) must satisfy the equation \\(num1 \\cdot s + num2 \\cdot t = GCD(num1, num2)\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8002, "level": 1, "question": "### Question\n\n#### Context:\nYou are tasked with implementing a function to find the coefficients of Bézout's identity for two given integers \\(num1\\) and \\(num2\\). These coefficients \\(s\\) and \\(t\\) must satisfy the equation \\(num1 \\cdot s...
import math def rotatePoint(x: float, y: float, angle_deg: float) -> (float, float): theta = math.radians(angle_deg) cos_theta = math.cos(theta) sin_theta = math.sin(theta) new_x = x * cos_theta - y * sin_theta new_y = x * sin_theta + y * cos_theta return (new_x, new_y)
simplelr_Package
[ { "content": "Question:\nYou are tasked with writing a Python function called `rotatePoint` that calculates the new position of a point after it has been rotated by a given angle around the origin (0, 0). The rotation should be done in a counterclockwise direction.\n\nThe relevant trigonometric functions to use...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8003, "level": 1, "question": "You are tasked with writing a Python function called `rotatePoint` that calculates the new position of a point after it has been rotated by a given angle around the origin (0, 0). The rotation should be done in a counterclockwise direction.\n\nThe rele...
import re def segment_sentences(text: str) -> list[str]: """ Segments the input text into a list of sentences. """ # Split the text into sentences based on the punctuation followed by optional whitespace sentences = re.split(r'(?<=[.?!])\s*', text) # Strip whitespace from each sentence and remo...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\nYou are required to implement a function that performs a sentence segmentation operation on a given text without relying on external libraries like nltk. The function should split the text into individual sentences based on punctuation marks (period '.'...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8004, "level": 1, "question": "### Coding Assessment Question\n\nYou are required to implement a function that performs a sentence segmentation operation on a given text without relying on external libraries like nltk. The function should split the text into individual sentences bas...
def min_edit_distance(s1: str, s2: str) -> int: m = len(s1) n = len(s2) # Create a DP table with (m+1) rows and (n+1) columns dp = [[0] * (n + 1) for _ in range(m + 1)] # Initialize the first row and column for i in range(m + 1): dp[i][0] = i for j in range(n + 1): dp[0]...
simplelr_Taco
[ { "content": "Question:\nYou are given two strings, `s1` and `s2`, both consisting of lowercase alphabets. Your task is to determine the minimum number of operations required to convert `s1` into `s2`. The allowed operations are:\n\n1. **Insertion**: Insert a single character into `s1`.\n2. **Deletion**: Delete...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8005, "level": 1, "question": "You are given two strings, `s1` and `s2`, both consisting of lowercase alphabets. Your task is to determine the minimum number of operations required to convert `s1` into `s2`. The allowed operations are:\n\n1. **Insertion**: Insert a single character ...
def longest_common_substring(s1, s2): m = len(s1) n = len(s2) dp = [[0] * (n + 1) for _ in range(m + 1)] max_len = 0 end = 0 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] + 1 if dp[i][j] > m...
simplelr_Filter
[ { "content": "Question:\nI am working on a project where I need to find the longest common substring between two given strings. Could you provide me with a Python function to achieve this?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8006, "level": 1, "question": "I am working on a project where I need to find the longest common substring between two given strings. Could you provide me with a Python function to achieve this?", "split": "train" }
def dutch_national_flag_sort(arr): low = 0 mid = 0 high = len(arr) - 1 while mid <= high: if arr[mid] == 0: arr[low], arr[mid] = arr[mid], arr[low] low += 1 mid += 1 elif arr[mid] == 1: mid += 1 else: # arr[mid] == 2 ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to sort an array of 0s, 1s, and 2s in ascending order using the Dutch National Flag problem solution.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8007, "level": 1, "question": "Write a python function to sort an array of 0s, 1s, and 2s in ascending order using the Dutch National Flag problem solution.", "split": "train" }
def filter_range(arr, min_val=None, max_val=None): if not arr: return [] lower = min_val if min_val is not None else -float('inf') upper = max_val if max_val is not None else float('inf') return [x for x in arr if lower <= x <= upper]
simplelr_Data_Structure
[ { "content": "Question:\n#### Context\nIn an IoT monitoring system, we often need to process sensor data to extract readings within a specific range. For example, you might only be interested in temperature readings within a safe range for a given environment. Hence, you need a function that efficiently filters...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8008, "level": 1, "question": "#### Context\nIn an IoT monitoring system, we often need to process sensor data to extract readings within a specific range. For example, you might only be interested in temperature readings within a safe range for a given environment. Hence, you need ...
def find_longest_sequence(s): max_seq = '' max_start = -1 max_length = 0 current_seq = '' current_start = 0 for index, char in enumerate(s): if char.isdigit(): if not current_seq: current_start = index current_seq += char else: ...
simplelr_Filter
[ { "content": "Question:\nDevelop a Python program that can identify and locate the position of the longest uninterrupted sequence of numbers in a string. The program should return the sequence itself and its starting index in the string. If there are multiple sequences of the same maximum length, the program sh...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8009, "level": 1, "question": "Develop a Python program that can identify and locate the position of the longest uninterrupted sequence of numbers in a string. The program should return the sequence itself and its starting index in the string. If there are multiple sequences of the ...
def max_profit(prices): if not prices: return 0 min_price = prices[0] max_profit = 0 for price in prices: if price < min_price: min_price = price potential_profit = price - min_price if potential_profit > max_profit: max_profit = potential_profit ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to get the maximum profit that can be earned from the stock market in a single transaction. The price of the stock on a given day is stored in a list where the index represents the day. You can only buy and sell once. For example, if the list is [7,1,5,3,6,4], th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8010, "level": 1, "question": "Write a python function to get the maximum profit that can be earned from the stock market in a single transaction. The price of the stock on a given day is stored in a list where the index represents the day. You can only buy and sell once. For exampl...
def filter_tasks(tasks, threshold): return [task for task in tasks if task['duration'] > threshold]
simplelr_Filter
[ { "content": "Question:\nHere is a problem I am trying to solve:\n\nI have a list of dictionaries, each dictionary representing a \"task\". Each task has the following keys:\n\n- `name`: (string) The name of the task.\n- `duration`: (integer) The duration of the task in minutes.\n\n**Example:**\n\n```python\nta...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8011, "level": 1, "question": "Here is a problem I am trying to solve:\n\nI have a list of dictionaries, each dictionary representing a \"task\". Each task has the following keys:\n\n- `name`: (string) The name of the task.\n- `duration`: (integer) The duration of the task in minute...
def create_spiral(n): grid = [[0 for _ in range(n)] for _ in range(n)] top = 0 bottom = n - 1 left = 0 right = n - 1 num = 1 while top <= bottom and left <= right: # Fill top row from left to right for i in range(left, right + 1): grid[top][i] = num n...
simplelr_Filter
[ { "content": "Question:\nHere's a challenge for you!\n\nI have a 100x100 grid. I need to create a function that will fill the grid in a spiral pattern. \n\nCould you show me an example of how to create this function in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8012, "level": 1, "question": "Here's a challenge for you!\n\nI have a 100x100 grid. I need to create a function that will fill the grid in a spiral pattern. \n\nCould you show me an example of how to create this function in Python?", "split": "train" }
def longest_repeated_sequence(s): if not s: return "" max_length = 0 max_seq = "" current_char = s[0] current_count = 1 for char in s[1:]: if char == current_char: current_count += 1 else: if current_count > max_length: ma...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string and returns the longest sequence of repeated characters in that string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8013, "level": 1, "question": "Create a function that takes a string and returns the longest sequence of repeated characters in that string.", "split": "train" }
def int_divide(decompose: int) -> int: n = decompose if n < 0: return 0 p = [0] * (n + 1) p[0] = 1 # Base case: one way to partition 0 (the empty set) for i in range(1, n + 1): sum_p = 0 m = 1 while True: g1 = m * (3 * m - 1) // 2 g2 = m ...
simplelr_Data_Structure
[ { "content": "Question:\n### Integer Partition Count\n\n#### Context:\nGiven a positive integer `n`, an integer partition of `n` is a way of writing `n` as a sum of positive integers. Partitions that differ only in the order of their summands are considered the same.\n\n#### Task:\nWrite a function `int_divide(...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8014, "level": 1, "question": "### Integer Partition Count\n\n#### Context:\nGiven a positive integer `n`, an integer partition of `n` is a way of writing `n` as a sum of positive integers. Partitions that differ only in the order of their summands are considered the same.\n\n#### T...
def sort_numbers(numbers): n = len(numbers) for i in range(n): for j in range(0, n - i - 1): if numbers[j] > numbers[j + 1]: numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j] return numbers numbers = [5, 2, 8, 1, 9] sorted_numbers = sort_numbers(numbers) print(sort...
simplelr_Filter
[ { "content": "Question:\nThis code is written in Python. It is supposed to sort numbers in ascending order.\n\n```python\ndef sort_numbers(numbers):\n \"\"\"Sorts numbers in ascending order.\"\"\"\n\n n = len(numbers)\n for i in range(n):\n for j in range(0, n - i - 1):\n if numbers[j] > numbers[j + ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8015, "level": 1, "question": "This code is written in Python. It is supposed to sort numbers in ascending order.\n\n```python\ndef sort_numbers(numbers):\n \"\"\"Sorts numbers in ascending order.\"\"\"\n\n n = len(numbers)\n for i in range(n):\n for j in range(0, n - i - 1):\...
def transpose_matrix(matrix: list[list[int]]) -> list[list[int]]: return [list(row) for row in zip(*matrix)]
simplelr_Algorithm
[ { "content": "Question:\n### Problem: Matrix Transpose Implementation\n\nYou are working on a data analysis tool and your task is to implement a function that calculates the transpose of a given matrix. The transpose of a matrix is generated by swapping the rows and columns.\n\n#### Function Signature\n```pytho...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8016, "level": 1, "question": "### Problem: Matrix Transpose Implementation\n\nYou are working on a data analysis tool and your task is to implement a function that calculates the transpose of a given matrix. The transpose of a matrix is generated by swapping the rows and columns.\n...
from typing import Tuple def finalPosition(movements: str) -> Tuple[int, int]: x, y = 0, 0 directions = { 'U': (0, 1), 'D': (0, -1), 'R': (1, 0), 'L': (-1, 0) } for move in movements: dx, dy = directions[move] x += dx y += dy return (x, y)
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are developing a program to simulate the movement of a robot on a 2D grid. The robot can move in four directions: up, down, left, and right. Each movement is represented by a character: 'U' for up, 'D' for down, 'L' for left, and 'R' for right. The robot start...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8017, "level": 1, "question": "### Problem Statement\nYou are developing a program to simulate the movement of a robot on a 2D grid. The robot can move in four directions: up, down, left, and right. Each movement is represented by a character: 'U' for up, 'D' for down, 'L' for left,...
def meets_criteria(s: str) -> bool: """ Checks if the number of unique characters in the string is twice the number of uppercase characters and if the length of the string is greater than 10. Args: s (str): The input string to be checked. Returns: bool: True if the string m...
simplelr_Filter
[ { "content": "Question:\nI need help with developing a Python function that can determine if a given string meets certain criteria. Specifically, I want the function to check if the number of unique characters in the string is twice the number of uppercase characters, and if the length of the string is greater ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8018, "level": 1, "question": "I need help with developing a Python function that can determine if a given string meets certain criteria. Specifically, I want the function to check if the number of unique characters in the string is twice the number of uppercase characters, and if t...
def character_frequency(s): freq_dict = {} for char in s: freq_dict[char] = freq_dict.get(char, 0) + 1 return freq_dict
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that takes in a string and returns a dictionary with the frequency of each character in the string. For example, if the input is \"hello\", the output should be {'h': 1, 'e': 1, 'l': 2, 'o': 1}.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8019, "level": 1, "question": "Create a Python function that takes in a string and returns a dictionary with the frequency of each character in the string. For example, if the input is \"hello\", the output should be {'h': 1, 'e': 1, 'l': 2, 'o': 1}.", "split": "train" }
def switch_case(text): return text.swapcase()
simplelr_Taco
[ { "content": "Question:\n**All Star Code Challenge #30**\n\nAlice has been given a text message and needs to switch the case of every letter in the message to confuse her twin brother Bob. Every lowercase letter should become uppercase, and every uppercase letter should become lowercase. Non-alphabet characters...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8020, "level": 1, "question": "**All Star Code Challenge #30**\n\nAlice has been given a text message and needs to switch the case of every letter in the message to confuse her twin brother Bob. Every lowercase letter should become uppercase, and every uppercase letter should become...
def sum_elements(file_name: str) -> int: total = 0 try: with open(file_name, 'r') as file: for line in file: stripped_line = line.strip() try: num = int(stripped_line) total += num except ValueError: ...
simplelr_Package
[ { "content": "Question:\nYou are tasked with creating a Python function `sum_elements` that will sum the elements of a list of numbers. This function will read numbers from a `.txt` file and return their sum.\n\n**Function Definition**:\n- `sum_elements(file_name: str) -> int` - This function takes the name of ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8021, "level": 1, "question": "You are tasked with creating a Python function `sum_elements` that will sum the elements of a list of numbers. This function will read numbers from a `.txt` file and return their sum.\n\n**Function Definition**:\n- `sum_elements(file_name: str) -> int`...
def unique_paths(m: int, n: int) -> int: """ Calculate the number of unique paths in an m x n grid from top-left to bottom-right. :param m: Number of rows in the grid. :param n: Number of columns in the grid. :return: The number of unique paths. """ total = m + n - 2 k = min(m - 1, n - ...
simplelr_Algorithm
[ { "content": "Question:\n### Context\nDynamic programming is a powerful technique used to solve problems by breaking them down into simpler subproblems and storing the results of these subproblems to avoid redundant computations. One classic example is the problem of finding the number of unique paths in a grid...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8022, "level": 1, "question": "### Context\nDynamic programming is a powerful technique used to solve problems by breaking them down into simpler subproblems and storing the results of these subproblems to avoid redundant computations. One classic example is the problem of finding t...
def word_frequency(input_string: str) -> dict: if not input_string: return {} words = input_string.split() frequency = {} for word in words: processed = ''.join([c for c in word if c.isalnum()]).lower() if processed: frequency[processed] = frequency.get(processed, 0) ...
simplelr_Apps
[ { "content": "Question:\nYou are working on a text editor, and you need to implement a function to count the frequency of each distinct word in a given string. The function should take a single string as input and return a dictionary where the keys are words, and the values are the number of times each word app...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8023, "level": 1, "question": "You are working on a text editor, and you need to implement a function to count the frequency of each distinct word in a given string. The function should take a single string as input and return a dictionary where the keys are words, and the values ar...
def count_alphabetic_characters(s): count = 0 for char in s: if char.isalpha(): count += 1 return count
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string as input and returns an integer representing the number of alphabetic characters in the string, ignoring spaces and non-alphabetic characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8024, "level": 1, "question": "Create a function that takes a string as input and returns an integer representing the number of alphabetic characters in the string, ignoring spaces and non-alphabetic characters.", "split": "train" }
def most_frequent_char(s): if not s: return None freq = {} for char in s: freq[char] = freq.get(char, 0) + 1 max_count = max(freq.values()) candidates = [char for char in freq if freq[char] == max_count] for char in s: if char in candidates: return char re...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a string as input and returns the character that appears most frequently in the string. If there are multiple characters that appear with the same highest frequency, the function should return the one that appears first in the string. For example, for ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8025, "level": 1, "question": "Write a Python function that takes a string as input and returns the character that appears most frequently in the string. If there are multiple characters that appear with the same highest frequency, the function should return the one that appears fir...
def binary_search(arr, target): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 # Example usage: # ar...
simplelr_Filter
[ { "content": "Question:\nCould you provide me with a Python code snippet to perform a binary search on a sorted array and return the index of the target element if it exists, or -1 if it does not exist?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8026, "level": 1, "question": "Could you provide me with a Python code snippet to perform a binary search on a sorted array and return the index of the target element if it exists, or -1 if it does not exist?", "split": "train" }
def merge_sorted_arrays(arr1, arr2): if not arr1: return list(arr2) if not arr2: return list(arr1) result = [] i = j = 0 len1, len2 = len(arr1), len(arr2) while i < len1 and j < len2: if arr1[i] <= arr2[j]: result.append(arr1[i]) i += 1 ...
simplelr_Package
[ { "content": "Question:\nYou need to implement a function named `merge_sorted_arrays(arr1, arr2)` that takes two sorted arrays as input and returns a single sorted array by merging the two provided arrays.\n\nYour function should work as follows:\n1. **Parameters**:\n - `arr1` (list): A list of integers sorte...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8027, "level": 1, "question": "You need to implement a function named `merge_sorted_arrays(arr1, arr2)` that takes two sorted arrays as input and returns a single sorted array by merging the two provided arrays.\n\nYour function should work as follows:\n1. **Parameters**:\n - `arr...
def sort_descending(numbers): return sorted(numbers, reverse=True)
simplelr_Filter
[ { "content": "Question:\nAs an AI language model, I want to generate a Python function that takes in a list of numbers and returns a new list with the numbers sorted in descending order. How can I achieve this?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8028, "level": 1, "question": "As an AI language model, I want to generate a Python function that takes in a list of numbers and returns a new list with the numbers sorted in descending order. How can I achieve this?", "split": "train" }
def power_mod(x, y, z): if z == 0: raise ValueError("Modulus cannot be zero.") if y < 0: raise ValueError("Exponent must be a non-negative integer.") if y == 0: if x == 0: raise ValueError("0^0 is undefined.") else: return 1 % z x = x % z resul...
simplelr_Filter
[ { "content": "Question:\nConsider the Python function pow(x, y, z). This function returns the value of x to the power y, modulus z. However, there is a mistake in the following code snippet. Your task is to identify and correct the error, then successfully implement a function to calculate (x^y) modulus z in th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8029, "level": 1, "question": "Consider the Python function pow(x, y, z). This function returns the value of x to the power y, modulus z. However, there is a mistake in the following code snippet. Your task is to identify and correct the error, then successfully implement a function...
from collections import Counter def most_frequent_smallest(nums: list) -> int: frequency = Counter(nums) max_freq = max(frequency.values()) candidates = [num for num, freq in frequency.items() if freq == max_freq] return min(candidates)
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Problem Description\nYou are required to write a function that finds the most frequent value in a list of integers. If there are multiple values with the same frequency, return the smallest one.\n\n#### Function Signature\n```python\ndef most_frequ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8030, "level": 1, "question": "### Coding Assessment Question\n\n#### Problem Description\nYou are required to write a function that finds the most frequent value in a list of integers. If there are multiple values with the same frequency, return the smallest one.\n\n#### Function S...
import csv import json def csv_to_json(csv_path, json_path): """ Converts a CSV file to a JSON file. Args: csv_path (str): Path to the CSV file. json_path (str): Path to the output JSON file. """ with open(csv_path, 'r', encoding='utf-8') as csv_file: # Read the CSV fil...
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python script that reads data from a CSV file and converts it into a JSON format? How can I handle large CSV files efficiently in this process?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8031, "level": 1, "question": "Can you provide a Python script that reads data from a CSV file and converts it into a JSON format? How can I handle large CSV files efficiently in this process?", "split": "train" }
def flatten(nested_list): result = [] for element in nested_list: if isinstance(element, list): result.extend(flatten(element)) else: result.append(element) return result
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to convert a nested list into a flat list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8032, "level": 1, "question": "Write a python function to convert a nested list into a flat list.", "split": "train" }
def find_next_permutation(nums): # Step 1: Find the pivot pivot = -1 for i in range(len(nums) - 2, -1, -1): if nums[i] < nums[i + 1]: pivot = i break if pivot == -1: nums.reverse() return # Step 2: Find the smallest element to the right of pivot t...
simplelr_Package
[ { "content": "Question:\nYou are tasked with writing a function `find_next_permutation(nums)` that transforms a given list of integers into its next lexicographical permutation. The function should rearrange the numbers in-place to achieve this. If the next permutation is not possible, the function should rearr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8033, "level": 1, "question": "You are tasked with writing a function `find_next_permutation(nums)` that transforms a given list of integers into its next lexicographical permutation. The function should rearrange the numbers in-place to achieve this. If the next permutation is not ...
def has_duplicates(s): for i in range(len(s)): for j in range(i + 1, len(s)): if s[i] == s[j]: return True return False
simplelr_Filter
[ { "content": "Question:\nCreate a function to determine if a given string contains any duplicate characters. This function should:\n- Return `True` if the string contains any duplicate characters.\n- Return `False` otherwise.\n- Be case-sensitive (i.e., 'a' and 'A' are considered different characters).\n- Not u...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8034, "level": 1, "question": "Create a function to determine if a given string contains any duplicate characters. This function should:\n- Return `True` if the string contains any duplicate characters.\n- Return `False` otherwise.\n- Be case-sensitive (i.e., 'a' and 'A' are conside...
def find_single_number(nums: list[int]) -> int: result = 0 for num in nums: result ^= num return result
simplelr_Algorithm
[ { "content": "Question:\n### Problem Description\nYou are provided with a list of integers where every element appears twice except for one. Implement a function to find that single one. Your solution should utilize bitwise operations to achieve optimal space and time complexity.\n\n### Function Signature\n```p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8035, "level": 1, "question": "### Problem Description\nYou are provided with a list of integers where every element appears twice except for one. Implement a function to find that single one. Your solution should utilize bitwise operations to achieve optimal space and time complexi...
def is_match(s: str, p: str) -> bool: len_s = len(s) len_p = len(p) dp = [[False] * (len_p + 1) for _ in range(len_s + 1)] dp[0][0] = True for i in range(len_s + 1): for j in range(len_p + 1): if i == 0 and j == 0: continue if j > 0 and p[j-1] == '*':...
simplelr_Data_Structure
[ { "content": "Question:\n### Regex Matching Problem\n\nYou are tasked with designing a function that determines whether a given string matches a pattern containing two special characters, '.' and '*'. The '.' character matches any single character, while '*' matches zero or more of the preceding element. The fu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8036, "level": 1, "question": "### Regex Matching Problem\n\nYou are tasked with designing a function that determines whether a given string matches a pattern containing two special characters, '.' and '*'. The '.' character matches any single character, while '*' matches zero or mo...
def calculate_factorial(n: int) -> int: result = 1 for i in range(1, n + 1): result *= i return result
simplelr_Algorithm
[ { "content": "Question:\n### Question: Calculate the Factorial of a Number\n\n#### Statement:\nYou are required to implement a function that calculates the factorial of a non-negative integer. The factorial of a number \\( n \\) is the product of all positive integers less than or equal to \\( n \\).\n\n#### Fu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8037, "level": 1, "question": "### Question: Calculate the Factorial of a Number\n\n#### Statement:\nYou are required to implement a function that calculates the factorial of a non-negative integer. The factorial of a number \\( n \\) is the product of all positive integers less tha...
def classify_emails(emails): classified = {} for email in emails: domain = email.split('@')[-1].lower() if domain in classified: classified[domain].append(email) else: classified[domain] = [email] return classified
simplelr_Prefill
[ { "content": "Question:\nCreate a function that automatically classifies a list of email addresses based on their domain. For example, classify emails as '@gmail.com', '@yahoo.com', '@outlook.com' etc.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8038, "level": 1, "question": "Create a function that automatically classifies a list of email addresses based on their domain. For example, classify emails as '@gmail.com', '@yahoo.com', '@outlook.com' etc.", "split": "train" }
def multiply(num1: str, num2: str) -> str: if num1 == "0" or num2 == "0": return "0" len1 = len(num1) len2 = len(num2) result = [0] * (len1 + len2) for i in range(len1): for j in range(len2): product = int(num1[i]) * int(num2[j]) pos = len1 + le...
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario\nYou are working on a project involving cryptographic computations with extremely large numerical values. Directly converting these values to integers could lead to overflow, increasing the importance of handling such values via string manipulations efficiently.\n\n### Prob...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8039, "level": 1, "question": "### Scenario\nYou are working on a project involving cryptographic computations with extremely large numerical values. Directly converting these values to integers could lead to overflow, increasing the importance of handling such values via string man...
def is_sorted_subarray(arr, start, end): if start < 0 or end >= len(arr) or start > end: return False if start == end: return True is_ascending = True for i in range(start, end): if arr[i] > arr[i+1]: is_ascending = False break if is_ascending: ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes three parameters: an array of integers, the starting index, and the ending index. The function should return a boolean value indicating whether or not the elements in the array between the specified start and end indices are sorted in either ascending or des...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8040, "level": 1, "question": "Create a function that takes three parameters: an array of integers, the starting index, and the ending index. The function should return a boolean value indicating whether or not the elements in the array between the specified start and end indices ar...
def countValleys(path): current_altitude = 0 valleys = 0 for step in path: if step == 'U': current_altitude += 1 else: current_altitude -= 1 # Check if this step caused returning to sea level from below if step == 'U' and current_altitude == 0: ...
simplelr_Taco
[ { "content": "Question:\nJohn is an avid hiker who plans to climb a mountain. The mountain's trail can be represented as a series of steps. Each step can either go uphill ('U') or downhill ('D'). He starts his journey at sea level and every upward step increases his altitude by one unit and every downward step ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8041, "level": 1, "question": "John is an avid hiker who plans to climb a mountain. The mountain's trail can be represented as a series of steps. Each step can either go uphill ('U') or downhill ('D'). He starts his journey at sea level and every upward step increases his altitude b...
def is_palindrome(s): filtered = ''.join([c for c in s if c.isalnum()]).lower() return filtered == filtered[::-1]
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s`, implement a function to determine if it is a valid **palindrome**, considering only alphanumeric characters and ignoring cases. A palindrome is a word, phrase, or sequence that reads the same backwards as forwards.\nAnswer:\nLet's think step by step.\n", "role": ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8042, "level": 1, "question": "Given a string `s`, implement a function to determine if it is a valid **palindrome**, considering only alphanumeric characters and ignoring cases. A palindrome is a word, phrase, or sequence that reads the same backwards as forwards.", "split": "tra...
from typing import List, Union def enhanced_ternary_search(arr: List[int], key: int, return_index: bool) -> Union[int, bool]: if not arr: return -1 if return_index else False left = 0 right = len(arr) - 1 while left <= right: mid1 = left + (right - left) // 3 mid2 = right - (r...
simplelr_Data_Structure
[ { "content": "Question:\nImplementing Enhanced Ternary Search \n\n#### Scenario:\nSuppose you are working for a company that handles large datasets, and you have learned about the efficiency of the ternary search algorithm over binary search for specific sorted datasets. Your task is to implement an enhanced ve...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8043, "level": 1, "question": "Implementing Enhanced Ternary Search \n\n#### Scenario:\nSuppose you are working for a company that handles large datasets, and you have learned about the efficiency of the ternary search algorithm over binary search for specific sorted datasets. Your ...
def has_pair_with_sum(nums, target): if len(nums) < 2: return False # Sort the list to apply two-pointer technique nums_sorted = sorted(nums) left = 0 right = len(nums_sorted) - 1 while left < right: current_sum = nums_sorted[left] + nums_sorted[right] if current_sum...
simplelr_Evol
[ { "content": "Question:\nDesign a Python function that accepts a list of integers and an integer target value, and determines whether any two distinct integers in the list sum up to the target value without using Python's combination functions. The function should return True if such a pair exists, and False ot...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8044, "level": 1, "question": "Design a Python function that accepts a list of integers and an integer target value, and determines whether any two distinct integers in the list sum up to the target value without using Python's combination functions. The function should return True ...
from collections import Counter def most_frequent_word(s): words = s.split() counts = Counter(words) max_count = max(counts.values()) max_words = [word for word, cnt in counts.items() if cnt == max_count] return min(max_words)
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` representing a list of words separated by spaces. All the words in the string are in lower case and are at least one character long. Write a function to return the word with the highest frequency. In case of a tie, return the lexicographically smallest word.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8045, "level": 1, "question": "You are given a string `s` representing a list of words separated by spaces. All the words in the string are in lower case and are at least one character long. Write a function to return the word with the highest frequency. In case of a tie, return the...
def find_pair_with_sum(nums, target): seen = {} for i, num in enumerate(nums): complement = target - num if complement in seen: return (seen[complement], i) seen[num] = i return None
simplelr_Evol
[ { "content": "Question:\nWrite a function called `find_pair_with_sum` that takes a list of integers and a target sum as input. The function should return a tuple with the indices of two numbers in the list that add up to the target sum. If no such pair exists, return `None`. The function should have a time comp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8046, "level": 1, "question": "Write a function called `find_pair_with_sum` that takes a list of integers and a target sum as input. The function should return a tuple with the indices of two numbers in the list that add up to the target sum. If no such pair exists, return `None`. T...
def extract_phrases(phrases, k): phrases_set = set() for phrase in phrases: words = phrase.split() n = len(words) if n < k: continue for i in range(n - k + 1): current_phrase = ' '.join(words[i:i+k]) phrases_set.add(current_phrase) return s...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of strings `phrases` and an integer `k`. Each string in `phrases` consists of words separated by single spaces. A **phrase** is defined as a string containing exactly `k` length *contiguous* words from any string in `phrases`. Implement a method that extracts all ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8047, "level": 1, "question": "You are given an array of strings `phrases` and an integer `k`. Each string in `phrases` consists of words separated by single spaces. A **phrase** is defined as a string containing exactly `k` length *contiguous* words from any string in `phrases`. Im...
from collections import defaultdict def find_frequent_purchases(data: list[tuple[str, str]]) -> dict[str, str]: """ Identify the most frequently purchased product per customer. Args: - data (list[tuple[str, str]]): A list of tuples where each tuple contains a customer ID and a product ID representing ...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n**Scenario**:\nYou are working for a tech company that provides analytics services. As part of their offering, they analyze the purchase history of customers to identify frequent buying patterns. Your task is to extend the provided data analysis functio...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8048, "level": 1, "question": "### Coding Assessment Question\n\n**Scenario**:\nYou are working for a tech company that provides analytics services. As part of their offering, they analyze the purchase history of customers to identify frequent buying patterns. Your task is to extend...
def minimize_sum(arr): m = min(arr) return m * len(arr)
simplelr_Taco
[ { "content": "Question:\nYou are given an array of integers of length N. You can perform the following operation as many times as you wish:\n\n* Choose an element from the array and decrease it by 1.\n\nThe goal is to make all elements in the array equal. However, you should minimize the sum of the elements aft...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8049, "level": 1, "question": "You are given an array of integers of length N. You can perform the following operation as many times as you wish:\n\n* Choose an element from the array and decrease it by 1.\n\nThe goal is to make all elements in the array equal. However, you should m...
def roman_to_int(s: str) -> int: roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} total = 0 prev_value = 0 for char in s: current = roman_map[char] if current > prev_value: total = total - 2 * prev_value + current else: total +...
simplelr_Data_Structure
[ { "content": "Question:\n### Roman Numeral Decimal Conversion\n\n#### Problem Statement\nGiven a string representing a Roman numeral, convert it to an integer. You need to write a function called `roman_to_int` that takes a Roman numeral string as input and returns its corresponding integer value.\n\n#### Expec...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8050, "level": 1, "question": "### Roman Numeral Decimal Conversion\n\n#### Problem Statement\nGiven a string representing a Roman numeral, convert it to an integer. You need to write a function called `roman_to_int` that takes a Roman numeral string as input and returns its corresp...
def check_balance_with_wildcards(s: str) -> bool: low = high = 0 for c in s: if c == '(': low += 1 high += 1 elif c == ')': low -= 1 high -= 1 else: # case for '*' low -= 1 high += 1 # If high is ne...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Balanced Parentheses with Wildcards\n\nYou are tasked with designing a function that determines whether a sequence of characters can be considered as balanced parentheses. The sequence can include three types of characters: `'('`, `')'`, and `'*'`....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8051, "level": 1, "question": "### Coding Assessment Question\n\n#### Balanced Parentheses with Wildcards\n\nYou are tasked with designing a function that determines whether a sequence of characters can be considered as balanced parentheses. The sequence can include three types of c...
def rgb_to_cmyk(R, G, B): r = R / 255.0 g = G / 255.0 b = B / 255.0 k = 1.0 - max(r, g, b) if k == 1.0: return (0.0, 0.0, 0.0, 1.0) else: c = (1.0 - r - k) / (1.0 - k) m = (1.0 - g - k) / (1.0 - k) y = (1.0 - b - k) / (1.0 - k) return (c, m, y, k)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that converts a given RGB color to its corresponding CMYK values. The RGB values should be in the range 0-255, and the output should be a tuple of CMYK values (c, m, y, k) where each value is a float between 0 and 1.\nAnswer:\nLet's think step by step.\n", "r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8052, "level": 1, "question": "Write a Python function that converts a given RGB color to its corresponding CMYK values. The RGB values should be in the range 0-255, and the output should be a tuple of CMYK values (c, m, y, k) where each value is a float between 0 and 1.", "split"...
def count_pairs_with_sum(N: int, array: [int], target: int) -> int: if N < 2: return 0 count_map = {} result = 0 for num in array: complement = target - num if complement in count_map: result += count_map[complement] count_map[num] = count_map.get(num, 0) + 1 ...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nYou are given an array of integers and a target sum. Your goal is to find the total number of distinct pairs (i, j) in the array such that the sum of array[i] and array[j] equals the target sum, and i < j.\n\n### Input\n* An integer N (1 <= N <= 10^5) representing...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8053, "level": 1, "question": "### Problem Statement\nYou are given an array of integers and a target sum. Your goal is to find the total number of distinct pairs (i, j) in the array such that the sum of array[i] and array[j] equals the target sum, and i < j.\n\n### Input\n* An inte...
def get_histogram(input_list: list) -> dict: """ Get histogram representation of product purchases. :param input_list: list of product IDs :return: dictionary where keys are product IDs and values are their frequencies """ histogram = {} for product in input_list: if product in histo...
simplelr_Data_Structure
[ { "content": "Question:\n#### Scenario\nYou are working on developing a function for analyzing customer purchase data. The data is provided as a list where each element represents a product ID bought by a customer. You need to create a function to count how many times each product was purchased.\n\n#### Task\nI...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8054, "level": 1, "question": "#### Scenario\nYou are working on developing a function for analyzing customer purchase data. The data is provided as a list where each element represents a product ID bought by a customer. You need to create a function to count how many times each pro...
def longest_consecutive_sequence(intervals): if not intervals: return 0 intervals.sort(key=lambda x: x[0]) merged_intervals = [list(intervals[0])] # Ensure it's a list for mutation for current_interval in intervals[1:]: current_start, current_end = current_interval last_start, ...
simplelr_Filter
[ { "content": "Question:\nThis is the given problem: \nGiven an array of intervals where each interval is a pair of integers, find the length of the longest consecutive sequence.\n\nExample:\nInput: [[1, 3], [4, 5], [1, 6], [2, 3]]\nOutput: 6, because the union of all intervals that overlap with each other is [1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8055, "level": 1, "question": "This is the given problem: \nGiven an array of intervals where each interval is a pair of integers, find the length of the longest consecutive sequence.\n\nExample:\nInput: [[1, 3], [4, 5], [1, 6], [2, 3]]\nOutput: 6, because the union of all intervals...
def sum_of_squares_above_threshold(numbers, threshold): total = 0 for num in numbers: if num > threshold: total += num ** 2 return total
simplelr_Filter
[ { "content": "Question:\nI want to create a function that can take in a list of numbers and return the sum of the squares of all the numbers that are greater than a specified threshold. \nFor example, if the input is the list `[1, 2, 3, 4, 5]` and the threshold is `3`, the function should return `4^2 + 5^2 = 41...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8056, "level": 1, "question": "I want to create a function that can take in a list of numbers and return the sum of the squares of all the numbers that are greater than a specified threshold. \nFor example, if the input is the list `[1, 2, 3, 4, 5]` and the threshold is `3`, the fun...
import re def find_longest_word(s): words = re.findall(r'[a-zA-Z]+', s) if not words: return '' return max(words, key=len)
simplelr_Filter
[ { "content": "Question:\nWhat is the most efficient way to find the longest word in a string in Python? This time, consider a scenario where the string contains punctuation marks and numbers that should not be counted as part of words. Also, assume that a word is defined as a sequence of letters separated by wh...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8057, "level": 1, "question": "What is the most efficient way to find the longest word in a string in Python? This time, consider a scenario where the string contains punctuation marks and numbers that should not be counted as part of words. Also, assume that a word is defined as a ...
def computeStringLengths(str_list: list) -> list: length_list = [] for s in str_list: length_list.append(len(s)) return length_list
simplelr_Package
[ { "content": "Question:\nYou are tasked with creating a function named `computeStringLengths` that calculates and returns the lengths of strings in a given list of strings.\n\nSpecifically:\n1. Iterate through each string in the input list and determine its length.\n2. Store the lengths in a list.\n\nTo impleme...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8058, "level": 1, "question": "You are tasked with creating a function named `computeStringLengths` that calculates and returns the lengths of strings in a given list of strings.\n\nSpecifically:\n1. Iterate through each string in the input list and determine its length.\n2. Store t...
def throttle_controller(desired_speed, current_speed): if desired_speed == current_speed: return {'throttle': 0.0, 'action': 'maintain'} elif desired_speed > current_speed: difference = desired_speed - current_speed if difference >= 50: throttle_pct = 100.0 else: ...
simplelr_Algorithm
[ { "content": "Question:\nWrite a function that simulates a throttle controller for an electric vehicle. The throttle controller takes a desired speed and current speed as inputs and determines the throttle percentage to achieve the desired speed. The function should consider if the vehicle is currently accelera...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8059, "level": 1, "question": "Write a function that simulates a throttle controller for an electric vehicle. The throttle controller takes a desired speed and current speed as inputs and determines the throttle percentage to achieve the desired speed. The function should consider i...
def sort_dicts(dict_list, sort_order): """ Sorts a list of dictionaries based on multiple keys with specified sort order. Args: dict_list (list): The list of dictionaries to be sorted. sort_order (list): A list of tuples where each tuple contains a key and a boolean indicating the sort dire...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to sort a list of dictionaries based on multiple keys with specified sort order for each key. The function should handle ascending and descending order for each key provided in a list of tuples, where each tuple contains a key and a boolean indicating the sort di...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8060, "level": 1, "question": "Write a Python function to sort a list of dictionaries based on multiple keys with specified sort order for each key. The function should handle ascending and descending order for each key provided in a list of tuples, where each tuple contains a key a...
def merge_sorted_lists(list1, list2): i = j = 0 merged = [] while i < len(list1) and j < len(list2): if list1[i] <= list2[j]: merged.append(list1[i]) i += 1 else: merged.append(list2[j]) j += 1 merged.extend(list1[i:]) merged.extend(lis...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to merge two sorted lists and return the merged list. The function should be able to handle lists with duplicate values and maintain the relative order of the elements.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8061, "level": 1, "question": "Write a python function to merge two sorted lists and return the merged list. The function should be able to handle lists with duplicate values and maintain the relative order of the elements.", "split": "train" }
def count_characters(strings): counts = {} for string in strings: for char in string: counts[char] = counts.get(char, 0) + 1 return counts
simplelr_Filter
[ { "content": "Question:\nI need a Python function that takes a list of strings and returns a dictionary where the keys are the distinct characters in the strings, and the values are the counts of those characters across all strings in the list. How can I achieve this?\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8062, "level": 1, "question": "I need a Python function that takes a list of strings and returns a dictionary where the keys are the distinct characters in the strings, and the values are the counts of those characters across all strings in the list. How can I achieve this?", "spl...
def box_volume_calculator(length, width, height): if length <= 0 or width <= 0 or height <= 0: raise ValueError("All dimensions must be positive") return length * width * height # Example usage: # print(box_volume_calculator(2.0, 3.0, 4.0)) # Output: 24.0 # print(box_volume_calculator(5.5, 7.5, 3.0)) #...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question: Box Volume Calculator\n\n#### Context:\nYou are tasked with developing a function that calculates the volume of a rectangular box. The formula for the volume \\( V \\) of a box is:\n\\[ V = \\text{length} \\times \\text{width} \\times \\text{height} \\]\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8063, "level": 1, "question": "### Coding Assessment Question: Box Volume Calculator\n\n#### Context:\nYou are tasked with developing a function that calculates the volume of a rectangular box. The formula for the volume \\( V \\) of a box is:\n\\[ V = \\text{length} \\times \\text{...
import math def rotate_2d_vector(vector, angle): x, y = vector theta = math.radians(angle) new_x = x * math.cos(theta) - y * math.sin(theta) new_y = x * math.sin(theta) + y * math.cos(theta) return (new_x, new_y)
simplelr_Package
[ { "content": "Question:\nYou are tasked with writing a Python function `rotate_2d_vector(vector, angle)` that rotates a 2-dimensional vector by a given angle. The function should use trigonometric functions from the `math` library to perform the rotation. \n\nThe function should take the following parameters:\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8064, "level": 1, "question": "You are tasked with writing a Python function `rotate_2d_vector(vector, angle)` that rotates a 2-dimensional vector by a given angle. The function should use trigonometric functions from the `math` library to perform the rotation. \n\nThe function shou...
def longestZeroSumSubarray(nums): prefix_sums = {0: -1} current_sum = 0 max_length = 0 for i, num in enumerate(nums): current_sum += num if current_sum in prefix_sums: length = i - prefix_sums[current_sum] if length > max_length: max_length = lengt...
simplelr_Filter
[ { "content": "Question:\nThis is a question about a specific coding challenge:\n\n**Challenge:** Given an array of integers, find the length of the longest subarray with a sum equal to zero.\n\n**Example:**\n\nInput: `nums = [15, -2, 2, -8, 1, 7, 10, 23]`\n\nOutput: `5`\n\nExplanation:\n\nThe longest subarray w...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8065, "level": 1, "question": "This is a question about a specific coding challenge:\n\n**Challenge:** Given an array of integers, find the length of the longest subarray with a sum equal to zero.\n\n**Example:**\n\nInput: `nums = [15, -2, 2, -8, 1, 7, 10, 23]`\n\nOutput: `5`\n\nExp...
def move_zeroes(nums: list[int]) -> list[int]: non_zero = [] zero_count = 0 for num in nums: if num != 0: non_zero.append(num) else: zero_count += 1 return non_zero + [0] * zero_count
simplelr_Algorithm
[ { "content": "Question:\n### Move Zeroes to End\n\nYou are tasked with writing a function that moves all the zeroes in a given list of integers to the end while maintaining the relative order of the non-zero elements. \n\n### Function Signature\n```python\ndef move_zeroes(nums: list[int]) -> list[int]:\n pas...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8066, "level": 1, "question": "### Move Zeroes to End\n\nYou are tasked with writing a function that moves all the zeroes in a given list of integers to the end while maintaining the relative order of the non-zero elements. \n\n### Function Signature\n```python\ndef move_zeroes(nums...
def sum_of_elements(numbers): return sum(numbers)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of integers as input and returns the sum of all the elements in the list. The function should be designed to handle large lists efficiently.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8067, "level": 1, "question": "Write a Python function that takes a list of integers as input and returns the sum of all the elements in the list. The function should be designed to handle large lists efficiently.", "split": "train" }
from typing import List, Dict from collections import Counter def unique_elements_frequency(nums: List[int]) -> Dict[int, int]: return Counter(nums)
simplelr_Package
[ { "content": "Question:\nIn this problem, you are required to write a Python function `unique_elements_frequency` that calculates the frequency of unique elements in a given list of integers. The function should return a dictionary where the keys are the unique elements from the list, and the values are the cor...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8068, "level": 1, "question": "In this problem, you are required to write a Python function `unique_elements_frequency` that calculates the frequency of unique elements in a given list of integers. The function should return a dictionary where the keys are the unique elements from t...
def distinct_characters(s): seen = set() result = [] for char in s: if char not in seen: seen.add(char) result.append(char) return ''.join(result)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to print distinct characters in a given string in the order of their first appearance.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8069, "level": 1, "question": "Write a python function to print distinct characters in a given string in the order of their first appearance.", "split": "train" }
from collections import Counter def find_top_k_frequent_elements(numbers, k): count = Counter(numbers) elements = list(count.keys()) sorted_elements = sorted(elements, key=lambda x: (-count[x], x)) return sorted_elements[:k]
simplelr_Taco
[ { "content": "Question:\nWe need a function that receives a list of integer numbers and finds the top-k most frequent elements in the list. The function should return a list of these elements sorted in descending order of their frequencies, and in case of a tie (elements having the same frequency), the elements...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8070, "level": 1, "question": "We need a function that receives a list of integer numbers and finds the top-k most frequent elements in the list. The function should return a list of these elements sorted in descending order of their frequencies, and in case of a tie (elements havin...
def maxProfit(prices): max_profit = 0 for i in range(1, len(prices)): if prices[i] > prices[i-1]: max_profit += prices[i] - prices[i-1] return max_profit
simplelr_Leetcode
[ { "content": "Question:\nImplement a function to calculate the maximum profit you can achieve given an integer array `prices`, where `prices[i]` is the price of a given stock on the ith day. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times), but you...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8071, "level": 1, "question": "Implement a function to calculate the maximum profit you can achieve given an integer array `prices`, where `prices[i]` is the price of a given stock on the ith day. You may complete as many transactions as you like (i.e., buy one and sell one share of...
def decode_string(s: str) -> str: stack = [] current_str = '' current_num = 0 for char in s: if char.isdigit(): current_num = current_num * 10 + int(char) elif char == '[': stack.append((current_str, current_num)) current_str = '' current_n...
simplelr_Data_Structure
[ { "content": "Question:\n### Decoded String Conversion\n\nYou are tasked with writing a function that decodes an encoded string into its expanded form. The encoding pattern used is `k[encoded_string]`, where the `encoded_string` inside the square brackets is repeated `k` times. Here, `k` is a positive integer.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8072, "level": 1, "question": "### Decoded String Conversion\n\nYou are tasked with writing a function that decodes an encoded string into its expanded form. The encoding pattern used is `k[encoded_string]`, where the `encoded_string` inside the square brackets is repeated `k` times...
def isPowerOfFour(binary_string): if binary_string.count('1') != 1: return False return (len(binary_string) - 1) % 2 == 0
simplelr_Taco
[ { "content": "Question:\nYou are given a string representing a binary number. The string contains only characters '0' and '1' and is guaranteed to be a valid binary number without any leading zeros. Your task is to determine if this binary number is a power of four. For example, the binary string '100' represen...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8073, "level": 1, "question": "You are given a string representing a binary number. The string contains only characters '0' and '1' and is guaranteed to be a valid binary number without any leading zeros. Your task is to determine if this binary number is a power of four. For exampl...
from collections import defaultdict def subarray_sum(nums, k): count_map = defaultdict(int) count_map[0] = 1 # Initialize with 0 to handle cases where subarray starts from index 0 current_sum = 0 res = 0 for num in nums: current_sum += num target = current_sum - k res += co...
simplelr_Apps
[ { "content": "Question:\n# Task\nYou are given an integer array `nums` and an integer `k`. Your task is to find the total number of continuous subarrays of `nums` whose sum equals to `k`.\n\n# Example\n\nFor `nums = [1, 1, 1]` and `k = 2`, the result should be `2`.\n```\nThe subarrays are [1, 1] and [1, 1]; the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8074, "level": 1, "question": "# Task\nYou are given an integer array `nums` and an integer `k`. Your task is to find the total number of continuous subarrays of `nums` whose sum equals to `k`.\n\n# Example\n\nFor `nums = [1, 1, 1]` and `k = 2`, the result should be `2`.\n```\nThe s...
import bisect def kthSmallest(matrix, k): if not matrix: return None m = len(matrix) n = len(matrix[0]) if m > 0 else 0 low = matrix[0][0] high = matrix[-1][-1] while low < high: mid = (low + high) // 2 count = 0 for row in matrix: count += ...
simplelr_Leetcode
[ { "content": "Question:\n**You are given a 2D integer array `matrix` of size `m x n` and an integer `k`. Return the `k-th` smallest element in the sorted order of all the elements in `matrix`. This array is sorted in non-decreasing row-wise and column-wise order.**\n\nExample:\nInput: `matrix = [\n [1, 5, 9]...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8075, "level": 1, "question": "**You are given a 2D integer array `matrix` of size `m x n` and an integer `k`. Return the `k-th` smallest element in the sorted order of all the elements in `matrix`. This array is sorted in non-decreasing row-wise and column-wise order.**\n\nExample:...
def sort_descending(numbers): if not numbers: raise ValueError("Input list is empty") if not all(type(x) in (int, float) for x in numbers): raise TypeError("Input list contains non-numeric values") return sorted(numbers, reverse=True)
simplelr_Filter
[ { "content": "Question:\nI have a list of numbers that I want to sort in descending order. I need to write a Python function that accomplishes this task.\n\n### Requirements\n- The input list should only contain numbers (either integers or floats).\n- The input list should not be empty.\n- The function should r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8076, "level": 1, "question": "I have a list of numbers that I want to sort in descending order. I need to write a Python function that accomplishes this task.\n\n### Requirements\n- The input list should only contain numbers (either integers or floats).\n- The input list should not...
def length_of_longest_substring(s): max_length = 0 start = 0 char_index = {} for end in range(len(s)): current_char = s[end] if current_char in char_index: if char_index[current_char] >= start: start = char_index[current_char] + 1 char_index[current_ch...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s` consisting of English letters, return the length of the **longest substring** without repeating characters. The substring should be **contiguous** and can contain letters from 'a' to 'z' in either lowercase or uppercase. The aim is to detect and extract this substring...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8077, "level": 1, "question": "Given a string `s` consisting of English letters, return the length of the **longest substring** without repeating characters. The substring should be **contiguous** and can contain letters from 'a' to 'z' in either lowercase or uppercase. The aim is t...
from typing import List def fibonacci_sequence(n: int) -> List[int]: result = [] a, b = 0, 1 for _ in range(n): result.append(a) a, b = b, a + b return result
simplelr_Codeforces
[ { "content": "Question:\nWrite a function which takes an integer `n` and returns a list of integers representing the first `n` numbers of the Fibonacci sequence.\n\nThe Fibonacci sequence is defined as follows:\n- The first number in the sequence is 0.\n- The second number is 1.\n- Each subsequent number is def...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8078, "level": 1, "question": "Write a function which takes an integer `n` and returns a list of integers representing the first `n` numbers of the Fibonacci sequence.\n\nThe Fibonacci sequence is defined as follows:\n- The first number in the sequence is 0.\n- The second number is ...
def generate_emails(names, domain): emails = [] for name in names: first, last = name.split() email = f"{first.lower()}.{last.lower()}@{domain.lower()}" emails.append(email) return emails
simplelr_Package
[ { "content": "Question:\nWrite a function `generate_emails` that creates email addresses based on a provided list of names and a specified domain. The function should return a list of email addresses generated using the format `firstname.lastname@domain`.\n\nHere are the requirements for the function:\n\n1. **F...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8079, "level": 1, "question": "Write a function `generate_emails` that creates email addresses based on a provided list of names and a specified domain. The function should return a list of email addresses generated using the format `firstname.lastname@domain`.\n\nHere are the requi...
def longest_consecutive(arr): if not arr: return 0 num_set = set(arr) max_length = 0 for num in num_set: if (num - 1) not in num_set: current_num = num current_length = 1 while (current_num + 1) in num_set: current_num += 1 ...
simplelr_Filter
[ { "content": "Question:\nWrite a function in Python that takes an array of integers and returns the length of the longest consecutive elements sequence. For example, given the array [100, 4, 200, 1, 3, 2], the longest consecutive elements sequence is [1, 2, 3, 4], and its length is 4. Your function should be ef...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8080, "level": 1, "question": "Write a function in Python that takes an array of integers and returns the length of the longest consecutive elements sequence. For example, given the array [100, 4, 200, 1, 3, 2], the longest consecutive elements sequence is [1, 2, 3, 4], and its leng...
def intersection(set1, set2): return set1.intersection(set2)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the intersection of two sets of numbers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8081, "level": 1, "question": "Write a function to find the intersection of two sets of numbers.", "split": "train" }
from collections import defaultdict def total_sales(records: list) -> dict: totals = defaultdict(int) for product_id, quantity_sold, price_per_unit in records: totals[product_id] += quantity_sold * price_per_unit return dict(totals)
simplelr_Algorithm
[ { "content": "Question:\n### Product Sales Tracker\n\nYou are given a list of sales records for various products. Each sale record is a tuple containing the product ID, quantity sold, and the price per unit. Your task is to analyze these records and return the total sales amount for each product ID.\n\n### Task...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8082, "level": 1, "question": "### Product Sales Tracker\n\nYou are given a list of sales records for various products. Each sale record is a tuple containing the product ID, quantity sold, and the price per unit. Your task is to analyze these records and return the total sales amou...
from heapq import heappop, heappush from collections import Counter def reorganize_string(s): count = Counter(s) n = len(s) max_freq = max(count.values(), default=0) if max_freq > (n + 1) // 2: return "" heap = [] for char in count: heappush(heap, (-count[char], char))...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` representing a sequence of characters, which includes lowercase alphabets and may contain duplicates. Implement a function that rearranges the characters in the string `s` such that no two adjacent characters are the same. If it is not possible to rearrange th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8083, "level": 1, "question": "You are given a string `s` representing a sequence of characters, which includes lowercase alphabets and may contain duplicates. Implement a function that rearranges the characters in the string `s` such that no two adjacent characters are the same. If...
def flatten_2d_array(array): result = [] for row in array: for element in row: result.append(element) return result # Example usage: print(flatten_2d_array([[1, 2, 3], [4, 5, 6]])) # Output: [1, 2, 3, 4, 5, 6]
simplelr_Filter
[ { "content": "Question:\nSuggest a code that takes a two-dimensional array as input and flattens it into a one-dimensional array.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8084, "level": 1, "question": "Suggest a code that takes a two-dimensional array as input and flattens it into a one-dimensional array.", "split": "train" }
def process_command(command: str): if not hasattr(process_command, 'dictionary'): process_command.dictionary = {} tokens = command.split() match tokens: case ["add", key, value]: process_command.dictionary[key] = value return f"Added key {key} with value {value}" ...
simplelr_Docs
[ { "content": "Question:\n**Python 3.10 Coding Assessment Question**\n\n### Objective\nThe objective of this assessment is to evaluate your ability to implement a function using Python 3.10's new pattern matching feature, as well as your ability to work with dictionaries and perform string manipulations.\n\n### ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8085, "level": 1, "question": "**Python 3.10 Coding Assessment Question**\n\n### Objective\nThe objective of this assessment is to evaluate your ability to implement a function using Python 3.10's new pattern matching feature, as well as your ability to work with dictionaries and pe...
def find_pairs_with_sum(arr, target_sum): seen = set() added_pairs = set() result = [] for num in arr: complement = target_sum - num if complement in seen: pair = tuple(sorted((complement, num))) if pair not in added_pairs: result.append(pair) ...
simplelr_Evol
[ { "content": "Question:\nCreate a function that accepts an array of integers and a target sum. The function should identify pairs of integers in the array that add up to the given target sum. If no such pairs are found, the function should return an empty list. The result should be a list of tuples, where each ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8086, "level": 1, "question": "Create a function that accepts an array of integers and a target sum. The function should identify pairs of integers in the array that add up to the given target sum. If no such pairs are found, the function should return an empty list. The result shou...
def sum_of_elements(numbers): return sum(numbers)
simplelr_Filter
[ { "content": "Question:\nCan you provide me with an example of a Python function that calculates the sum of all elements in a list of numbers?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8087, "level": 1, "question": "Can you provide me with an example of a Python function that calculates the sum of all elements in a list of numbers?", "split": "train" }
def kth_smallest(matrix, k): n = len(matrix) if n == 0 or n == 0: return None # Assuming the matrix is always valid as per constraints low = matrix[0][0] high = matrix[-1][-1] while low <= high: mid = (low + high) // 2 count = 0 for row in matrix: ...
simplelr_Algorithm
[ { "content": "Question:\n### Kth Smallest Element in a Sorted Matrix\n\n**Objective**: Write a function to find the Kth smallest element in a given `n x n` matrix where each of the rows and columns is sorted in ascending order. This problem tests your ability to implement efficient search algorithms in a struct...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8088, "level": 1, "question": "### Kth Smallest Element in a Sorted Matrix\n\n**Objective**: Write a function to find the Kth smallest element in a given `n x n` matrix where each of the rows and columns is sorted in ascending order. This problem tests your ability to implement effi...
from typing import List def sort_tickets(tickets: List[str]) -> List[str]: return sorted(tickets, key=lambda x: x.split(':')[0])
simplelr_Codeforces
[ { "content": "Question:\nYou've been hired to work on an automated customer support ticket sorting system. The system receives a list of tickets, where each ticket is represented as a string containing a subject line and a description separated by a colon. Your task is to implement a function that sorts the tic...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8089, "level": 1, "question": "You've been hired to work on an automated customer support ticket sorting system. The system receives a list of tickets, where each ticket is represented as a string containing a subject line and a description separated by a colon. Your task is to impl...
from typing import List, Tuple def analyze_scores(n: int, scores: List[int]) -> Tuple[int, List[int]]: return (n, scores)
simplelr_Codeforces
[ { "content": "Question:\nYou are given a list of integers representing the maximum scores of various rounds of a game. Each round is played until a specific score, and the scores are given in chronological order. The objective is to determine how many rounds were played and the maximum score achieved in each ro...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8090, "level": 1, "question": "You are given a list of integers representing the maximum scores of various rounds of a game. Each round is played until a specific score, and the scores are given in chronological order. The objective is to determine how many rounds were played and th...
from sklearn.kernel_approximation import RBFSampler from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score from typing import List def rbf_kernel_approximation(X_train: List[List[float]], y_train: List[int], X_validation: List[List[float]], y_validation:...
simplelr_Docs
[ { "content": "Question:\nYou are tasked with implementing a kernel approximation method using scikit-learn and testing its performance on a classification problem.\n\n### Requirements:\n\n1. **Function Implementation**:\n Implement a function `rbf_kernel_approximation` that approximates the RBF kernel using t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8091, "level": 1, "question": "You are tasked with implementing a kernel approximation method using scikit-learn and testing its performance on a classification problem.\n\n### Requirements:\n\n1. **Function Implementation**:\n Implement a function `rbf_kernel_approximation` that ...
import bisect def lengthOfLIS(nums): tails = [] for num in nums: index = bisect.bisect_left(tails, num) if index == len(tails): tails.append(num) else: tails[index] = num return len(tails)
simplelr_Evol
[ { "content": "Question:\nCreate a function that calculates the longest increasing subsequence that can be derived from a given list of integers. The subsequence does not need to be contiguous, but each element must be larger than the preceding one. The function should return the length of this subsequence. Ensu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8092, "level": 1, "question": "Create a function that calculates the longest increasing subsequence that can be derived from a given list of integers. The subsequence does not need to be contiguous, but each element must be larger than the preceding one. The function should return t...
def reverse_words(sentence): words = sentence.split() reversed_words = words[::-1] return ' '.join(reversed_words)
simplelr_Algorithm
[ { "content": "Question:\n### Reverse Words in a String\n\nYou are developing a text processing feature that helps users manipulate sentences. A common operation is reversing the order of words in a given string.\n\nWrite the `reverse_words` function that takes a single string parameter `sentence` and returns a ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8093, "level": 1, "question": "### Reverse Words in a String\n\nYou are developing a text processing feature that helps users manipulate sentences. A common operation is reversing the order of words in a given string.\n\nWrite the `reverse_words` function that takes a single string ...
def sort_letters_keep_numbers(s): s_list = list(s) letters = [c for c in s_list if c.isalpha()] letters_sorted = sorted(letters) letter_iter = iter(letters_sorted) result = [] for c in s_list: if c.isalpha(): result.append(next(letter_iter)) else: result.a...
simplelr_Evol
[ { "content": "Question:\nDevise a programming algorithm that takes a string composed of letters and numbers and sorts the letters alphabetically while keeping the numbers in their original positions.\nExample input: \"4h3e5l2l1o\"\nOutput: \"4e3h5l2l1o\"\nAnswer:\nLet's think step by step.\n", "role": "user...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8094, "level": 1, "question": "Devise a programming algorithm that takes a string composed of letters and numbers and sorts the letters alphabetically while keeping the numbers in their original positions.\nExample input: \"4h3e5l2l1o\"\nOutput: \"4e3h5l2l1o\"", "split": "train" }
def longest_common_subsequence(text1: str, text2: str) -> int: m, n = len(text1), len(text2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if text1[i - 1] == text2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: ...
simplelr_Algorithm
[ { "content": "Question:\n### Find the Longest Common Subsequence\n\n#### Context\nYou are part of a software development team building a text comparison tool. One of the features is to find similar segments between two texts to highlight commonalities. A key aspect of this feature is to identify the longest com...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8095, "level": 1, "question": "### Find the Longest Common Subsequence\n\n#### Context\nYou are part of a software development team building a text comparison tool. One of the features is to find similar segments between two texts to highlight commonalities. A key aspect of this fea...
from typing import List def count_days_higher_steps(steps: List[int]) -> int: count = 0 for i in range(1, len(steps)): if steps[i] > steps[i-1]: count += 1 return count
simplelr_Taco
[ { "content": "Question:\nGiven a list of integers representing the number of steps a hiker takes in each day of a hiking trip, write a function that returns the number of days in which the hiker climbed more steps than he did on the previous day. For example, if the input list is [2, 3, 1, 5, 4], the function s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8096, "level": 1, "question": "Given a list of integers representing the number of steps a hiker takes in each day of a hiking trip, write a function that returns the number of days in which the hiker climbed more steps than he did on the previous day. For example, if the input list...
def min_max_pair_sum(weights): n = len(weights) if n == 0 or n % 2 != 0: return -1 sorted_weights = sorted(weights) pair_sums = [] for i in range(n // 2): pair_sum = sorted_weights[i] + sorted_weights[n - 1 - i] pair_sums.append(pair_sum) return max(pair_sums)
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `weights` representing the weights of `n` items, you need to pair the items in such a way that the maximum sum of weights in any pair is minimized. Each item must be paired with exactly one other item. If there is an odd number of items, return `-1` as it is not p...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8097, "level": 1, "question": "Given an integer array `weights` representing the weights of `n` items, you need to pair the items in such a way that the maximum sum of weights in any pair is minimized. Each item must be paired with exactly one other item. If there is an odd number o...
import os from collections import defaultdict def find_suspicious_ip_addresses(file_path: str) -> list | None: # Validate input if not file_path or not isinstance(file_path, str): return None if not os.path.isfile(file_path): return None ip_count = defaultdict(int) try: wi...
simplelr_Algorithm
[ { "content": "Question:\n### File Management and Data Processing Coding Challenge\n\n**Context**:\nYou are tasked with analyzing a large log file from a web server to identify potential security issues. Each line in the log file contains a request made to the server, including the IP address of the client makin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8098, "level": 1, "question": "### File Management and Data Processing Coding Challenge\n\n**Context**:\nYou are tasked with analyzing a large log file from a web server to identify potential security issues. Each line in the log file contains a request made to the server, including...
def removeDuplicates(s): seen = set() result = [] for c in s: if c not in seen: seen.add(c) result.append(c) result.sort() return ''.join(result)
simplelr_Taco
[ { "content": "Question:\nGiven a string S of lowercase English letters, the task is to remove duplicates from the string such that each character appears only once and return the resultant string in lexicographical order.\n\nExample 1:\nInput:\nS = \"bcabc\"\nOutput: \"abc\"\nExplanation:\nThe string \"bcabc\" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 8099, "level": 1, "question": "Given a string S of lowercase English letters, the task is to remove duplicates from the string such that each character appears only once and return the resultant string in lexicographical order.\n\nExample 1:\nInput:\nS = \"bcabc\"\nOutput: \"abc\"\n...