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 is_palindrome(s: str) -> bool: # Clean the string by keeping only alphanumeric characters and converting to lowercase cleaned = ''.join([char.lower() for char in s if char.isalnum()]) # Check if the cleaned string is a palindrome return cleaned == cleaned[::-1]
simplelr_Taco
[ { "content": "Question:\nDetermine if a given string s is a valid palindrome considering only alphanumeric characters and ignoring cases. \n\nFor this problem, we define a valid palindrome as a string that reads the same forwards and backwards after converting all upper case letters into lower case letters and ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3100, "level": 1, "question": "Determine if a given string s is a valid palindrome considering only alphanumeric characters and ignoring cases. \n\nFor this problem, we define a valid palindrome as a string that reads the same forwards and backwards after converting all upper case l...
def sort_names_by_scores(students): sorted_students = sorted(students, key=lambda x: (x['score'], tuple(-ord(c) for c in x['name']))) return [student['name'] for student in sorted_students]
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of dictionaries as input, each containing 'name' and 'score' keys, and outputs a sorted list of names based on their scores. The function should sort the names in ascending order of scores, and if two scores are the same, the names should be sor...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3101, "level": 1, "question": "Write a Python function that takes a list of dictionaries as input, each containing 'name' and 'score' keys, and outputs a sorted list of names based on their scores. The function should sort the names in ascending order of scores, and if two scores ar...
from collections import defaultdict def can_enroll(prerequisites: list[tuple[str, str]], target_course: str) -> bool: # Extract all unique courses courses = set() for course, prereq in prerequisites: courses.add(course) courses.add(prereq) # Check if target_course is in the graph ...
simplelr_Algorithm
[ { "content": "Question:\n## Task: [Question 2]: **Course Prerequisite Checker**\n\nIn a university course registration system, each course has a set of pre-requisite courses that need to be completed before enrolling in that particular course. These prerequisites form a directed acyclic graph (DAG), where each ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3102, "level": 1, "question": "## Task: [Question 2]: **Course Prerequisite Checker**\n\nIn a university course registration system, each course has a set of pre-requisite courses that need to be completed before enrolling in that particular course. These prerequisites form a direct...
from typing import List def generate_permutations(elements: List[int]) -> List[List[int]]: if len(elements) == 0: return [[]] result = [] for i in range(len(elements)): current = elements[i] rest = elements[:i] + elements[i+1:] for p in generate_permutations(rest): ...
simplelr_Data_Structure
[ { "content": "Question:\n### Permutations Problem\n\nYou are given a list of distinct integers. Your task is to generate all possible permutations for this list. Permutations are the different ways in which a set of items can be ordered. Implement a function that efficiently generates these permutations.\n\n**F...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3103, "level": 1, "question": "### Permutations Problem\n\nYou are given a list of distinct integers. Your task is to generate all possible permutations for this list. Permutations are the different ways in which a set of items can be ordered. Implement a function that efficiently g...
def repeat_characters(s): return ''.join([c * 3 for c in s])
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes a string as input and returns a new string where each character in the original string is repeated three times.\n\nFor example:\n```\nInput: \"abc\"\nOutput: \"aaabbbccc\"\n\nInput: \"hello\"\nOutput: \"hhheeelllllooo\"\n```\nAnswer:\nLet's think step by step...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3104, "level": 1, "question": "Write a function that takes a string as input and returns a new string where each character in the original string is repeated three times.\n\nFor example:\n```\nInput: \"abc\"\nOutput: \"aaabbbccc\"\n\nInput: \"hello\"\nOutput: \"hhheeelllllooo\"\n```...
def length_of_longest_substring(s): char_index = {} max_length = 0 left = 0 for right in range(len(s)): char = s[right] if char in char_index and char_index[char] >= left: left = char_index[char] + 1 char_index[char] = right current_length = right - left + 1 ...
simplelr_Evol
[ { "content": "Question:\nWrite a function in Python to find the length of the longest substring without repeating characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3105, "level": 1, "question": "Write a function in Python to find the length of the longest substring without repeating characters.", "split": "train" }
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def analyze_grades(file_path: str) -> None: """ Analyzes student grades by performing grouping, aggregation, filtering, and visualization. Parameters: file_path (str): The path to the grades CSV file. Returns: None:...
simplelr_Docs
[ { "content": "Question:\n### **GroupBy Operations and Visualization in Pandas**\n\nYou are provided with a dataset in the form of a CSV file named `grades.csv`. The file contains student grades and has the following columns:\n- `student_id`: (int) Unique identifier for each student.\n- `subject`: (str) Subject ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3106, "level": 1, "question": "### **GroupBy Operations and Visualization in Pandas**\n\nYou are provided with a dataset in the form of a CSV file named `grades.csv`. The file contains student grades and has the following columns:\n- `student_id`: (int) Unique identifier for each st...
def max_subarray_product(nums): if not nums: return 0 # Handle empty list case, though the problem likely ensures a non-empty list. current_max = 1 max_product = 0 for num in nums: current_max = max(num, current_max * num) if current_max > max_product: max_product = ...
simplelr_Leetcode
[ { "content": "Question:\nYou have a list of non-negative integers `nums`. You are allowed to choose any non-empty subarray (contiguous elements) and perform the following operation once:\n\n* Multiply all the elements of the subarray.\n\nFind the maximum possible product you can achieve from any subarray of t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3107, "level": 1, "question": "You have a list of non-negative integers `nums`. You are allowed to choose any non-empty subarray (contiguous elements) and perform the following operation once:\n\n* Multiply all the elements of the subarray.\n\nFind the maximum possible product you...
def remove_first_occurrence(lst, num): result = [] removed = False for element in lst: if element == num and not removed: removed = True else: result.append(element) return result
simplelr_Filter
[ { "content": "Question:\nA function takes a list of integers as input, removes the first occurrence of a specified integer, and returns the modified list. Your goal is to complete this function.\n\n```python\ndef remove_first_occurrence(lst, num):\n # Your code here\n```\n\n**Example Use Cases:**\n\n* `remov...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3108, "level": 1, "question": "A function takes a list of integers as input, removes the first occurrence of a specified integer, and returns the modified list. Your goal is to complete this function.\n\n```python\ndef remove_first_occurrence(lst, num):\n # Your code here\n```\n\...
def triangularTerm(n): return n * (n + 1) // 2
simplelr_Taco
[ { "content": "Question:\nMansi enjoys solving pattern recognition problems. She came across a triangular number series which she needs help with. The nth term in the triangular series is defined as the sum of the first n natural numbers.\n\nTriangular number series:\nn nth term\n1 1\n2 3\n3 6\n4 10\n5...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3109, "level": 1, "question": "Mansi enjoys solving pattern recognition problems. She came across a triangular number series which she needs help with. The nth term in the triangular series is defined as the sum of the first n natural numbers.\n\nTriangular number series:\nn nth t...
def find_consecutive_sentences_with_common_word(sentences): result = [] for i in range(len(sentences) - 1): sentence1 = sentences[i].split() sentence2 = sentences[i + 1].split() if set(sentence1) & set(sentence2): result.append((sentences[i], sentences[i+1])) return resul...
simplelr_Filter
[ { "content": "Question:\nIn this problem, you are given a list of strings. Each string is a sentence. Your goal is to find all the pairs of consecutive sentences that have at least one word in common. \n\nFor example, if your input is [\"Hello world\", \"world is nice\", \"nice day\"], the output will be [(\"He...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3110, "level": 1, "question": "In this problem, you are given a list of strings. Each string is a sentence. Your goal is to find all the pairs of consecutive sentences that have at least one word in common. \n\nFor example, if your input is [\"Hello world\", \"world is nice\", \"nic...
def remove_duplicates(duplicate_list): seen = {} # Iterate through the list in reverse to keep the last occurrence of each id for item in reversed(duplicate_list): item_id = item['id'] if item_id not in seen: seen[item_id] = item # Convert the dictionary values to a list and ...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to remove duplicate records from a list of dictionaries, where the key \"id\" is used to determine duplicates. If a duplicate is found, the newest entry (i.e., the entry that appears later in the list) should be kept.\nAnswer:\nLet's think step by step.\n", "...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3111, "level": 1, "question": "Write a python function to remove duplicate records from a list of dictionaries, where the key \"id\" is used to determine duplicates. If a duplicate is found, the newest entry (i.e., the entry that appears later in the list) should be kept.", "split...
def is_pattern_aabbcc(s): if len(s) % 2 != 0: return False for i in range(0, len(s), 2): if s[i] != s[i+1]: return False return True
simplelr_Prefill
[ { "content": "Question:\nWrite a function to check if a given string `s` matches the pattern `aabbcc...`, where `a`, `b`, `c`, etc. are any characters and each character appears exactly twice consecutively. The length of the string will not exceed 100.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3112, "level": 1, "question": "Write a function to check if a given string `s` matches the pattern `aabbcc...`, where `a`, `b`, `c`, etc. are any characters and each character appears exactly twice consecutively. The length of the string will not exceed 100.", "split": "train" }
import pandas as pd import numpy as np def analyze_csv(file_path: str) -> dict: df = pd.read_csv(file_path) numerical_df = df.select_dtypes(include=[np.number]) averages = numerical_df.mean() return averages.to_dict()
simplelr_Package
[ { "content": "Question:\n## Analyzing CSV Data with pandas\n\nIn this programming assignment, you need to create a function called `analyze_csv` that takes a single argument `file_path`, which is a string representing the path to a CSV file. This function should use the `pandas` library to load and analyze the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3113, "level": 1, "question": "## Analyzing CSV Data with pandas\n\nIn this programming assignment, you need to create a function called `analyze_csv` that takes a single argument `file_path`, which is a string representing the path to a CSV file. This function should use the `panda...
import aifc def modify_aiff(input_file: str, output_file: str) -> None: """ Reads an AIFF/AIFC file, modifies its frame rate and converts to mono (if stereo), and writes the modified data to a new AIFF-C file. Args: input_file (str): Path to the input AIFF/AIFC file. output_file (str): Pat...
simplelr_Docs
[ { "content": "Question:\n### Advanced Python Programming: AIFF File Manipulation\n\n**Objective:**\nYou are required to demonstrate your understanding of audio file manipulation using the `aifc` module in Python. Specifically, you will work with AIFF and AIFF-C files to read, modify, and save audio data.\n\n**P...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3114, "level": 1, "question": "### Advanced Python Programming: AIFF File Manipulation\n\n**Objective:**\nYou are required to demonstrate your understanding of audio file manipulation using the `aifc` module in Python. Specifically, you will work with AIFF and AIFF-C files to read, ...
def square_root(n: int, p: float = 0.001) -> float: """ Calculate the square root of n with precision p using Newton's method. :param n: The number to find the square root of (0 <= n <= 10^9) :param p: The precision factor (0 < p <= 0.1) :return: The square root of n with an error less than or ...
simplelr_Data_Structure
[ { "content": "Question:\n### Square Root Calculation Using Newton's Method\n\n#### Problem Statement\nGiven a positive integer **N** and a precision factor **P**, you need to write a function that computes and returns the square root of **N** such that the maximum absolute error of your result from the actual s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3115, "level": 1, "question": "### Square Root Calculation Using Newton's Method\n\n#### Problem Statement\nGiven a positive integer **N** and a precision factor **P**, you need to write a function that computes and returns the square root of **N** such that the maximum absolute err...
import csv def merge_csv_files(input_files, output_file, key_column): output_header = [key_column] added_columns = set(output_header) merged_data = {} for file in input_files: try: with open(file, 'r') as f: sample = f.read(1024) try: ...
simplelr_Docs
[ { "content": "Question:\n### **Advanced CSV Handling with Python's `csv` Module**\n\n#### **Objective:**\nWrite a Python function that processes multiple CSV files to merge their data based on a common key and outputs the merged data into a new CSV file. This task will assess your understanding of reading, writ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3116, "level": 1, "question": "### **Advanced CSV Handling with Python's `csv` Module**\n\n#### **Objective:**\nWrite a Python function that processes multiple CSV files to merge their data based on a common key and outputs the merged data into a new CSV file. This task will assess ...
def count_increase_days(temperatures): count = 0 for i in range(1, len(temperatures)): if temperatures[i] > temperatures[i-1]: count += 1 return count
simplelr_Evol
[ { "content": "Question:\nImplement a function that takes a list of integers representing daily temperatures over a month. The function should return the number of days where the temperature was higher than the previous day. \ntemperatures = [70, 72, 68, 73, 75, 71, 69, 74, 76, 77]\nAnswer:\nLet's think step by ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3117, "level": 1, "question": "Implement a function that takes a list of integers representing daily temperatures over a month. The function should return the number of days where the temperature was higher than the previous day. \ntemperatures = [70, 72, 68, 73, 75, 71, 69, 74, 76,...
def longest_unique_substring(s): char_map = {} left = 0 max_len = 0 start = 0 for right in range(len(s)): char = s[right] if char in char_map and char_map[char] >= left: left = char_map[char] + 1 char_map[char] = right current_len = right - left + 1 ...
simplelr_Apps
[ { "content": "Question:\nSarah is creating a list of unique passwords for her new website. She wants each password to be highly secure, meaning it should not contain any repeated characters. Given a string, she needs a program that will determine the length of the longest substring without repeating characters....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3118, "level": 1, "question": "Sarah is creating a list of unique passwords for her new website. She wants each password to be highly secure, meaning it should not contain any repeated characters. Given a string, she needs a program that will determine the length of the longest subs...
def binary_search(sorted_list, target): low = 0 high = len(sorted_list) - 1 while low <= high: mid = (low + high) // 2 if sorted_list[mid] == target: return mid elif sorted_list[mid] > target: high = mid - 1 else: low = mid + 1 return -...
simplelr_Filter
[ { "content": "Question:\nImplement a binary search algorithm in Python to find the index of a given element in a sorted list. If the element is not found, return -1. Optimize the code for efficiency and readability.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3119, "level": 1, "question": "Implement a binary search algorithm in Python to find the index of a given element in a sorted list. If the element is not found, return -1. Optimize the code for efficiency and readability.", "split": "train" }
from collections import defaultdict from typing import Sequence def find_subarrays_with_sum(arr: Sequence[int], target_sum: int) -> int: sum_counts = defaultdict(int) sum_counts[0] = 1 current_sum = 0 count = 0 for num in arr: current_sum += num # Check how many times (current_sum -...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\n2. **Function to Implement**:\n Write a function `find_subarrays_with_sum(arr: Sequence[int], target_sum: int) -> int` that takes two parameters:\n * `arr` (sequence of integers): An array of integers.\n * `target_sum` (integer): The target sum value.\n\n#...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3120, "level": 1, "question": "### Problem Statement\n\n2. **Function to Implement**:\n Write a function `find_subarrays_with_sum(arr: Sequence[int], target_sum: int) -> int` that takes two parameters:\n * `arr` (sequence of integers): An array of integers.\n * `target_sum` (i...
def three_sum_closest(nums, target): nums.sort() n = len(nums) closest_sum = 0 min_diff = float('inf') for i in range(n - 2): left = i + 1 right = n - 1 while left < right: current_sum = nums[i] + nums[left] + nums[right] current_diff = abs(current_sum...
simplelr_Apps
[ { "content": "Question:\nYou are given an integer array `nums` and an integer target. You need to determine if there are three integers in `nums` such that the sum is closest to the target. Return the sum of the three integers. You may assume that each input would have exactly one solution.\n\nExample 1:\n\nInp...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3121, "level": 1, "question": "You are given an integer array `nums` and an integer target. You need to determine if there are three integers in `nums` such that the sum is closest to the target. Return the sum of the three integers. You may assume that each input would have exactly...
def find_companies(companies): return [company for company in companies if len(company) > 5]
simplelr_Filter
[ { "content": "Question:\nYou've been tasked with writing a function `find_companies` that takes a list of strings as input, where each string represents a company name, and returns the names of companies that have more than 5 characters in their name.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3122, "level": 1, "question": "You've been tasked with writing a function `find_companies` that takes a list of strings as input, where each string represents a company name, and returns the names of companies that have more than 5 characters in their name.", "split": "train" }
def remove_and_reverse_non_alphanumeric(s): return [char for char in s if char.isalnum()][::-1]
simplelr_Filter
[ { "content": "Question:\nWrite a function in Python that removes all non-alphanumeric characters from a given string and returns a list of the alphanumeric characters in reverse order. Additionally, the function should ignore case sensitivity while removing non-alphanumeric characters.\nAnswer:\nLet's think ste...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3123, "level": 1, "question": "Write a function in Python that removes all non-alphanumeric characters from a given string and returns a list of the alphanumeric characters in reverse order. Additionally, the function should ignore case sensitivity while removing non-alphanumeric ch...
def caesar_cipher(text, shift, direction='right'): """ Encrypts a given string using the Caesar Cipher technique. Parameters: text (str): The original string to be encrypted. shift (int): The number of positions each character in the string should be shifted. direction (str): The direction of t...
simplelr_Package
[ { "content": "Question:\n**Data Encryption using Caesar Cipher**\n\nWrite a Python function `caesar_cipher` that encrypts a given string using the Caesar Cipher technique with a specified shift value. The Caesar Cipher is a type of substitution cipher where each letter in the plaintext is shifted a certain numb...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3124, "level": 1, "question": "**Data Encryption using Caesar Cipher**\n\nWrite a Python function `caesar_cipher` that encrypts a given string using the Caesar Cipher technique with a specified shift value. The Caesar Cipher is a type of substitution cipher where each letter in the ...
def longest_consecutive_repeated_chars(s): if not s: return "" max_length = 1 current_length = 1 max_char = s[0] current_char = s[0] for char in s[1:]: if char == current_char: current_length += 1 else: if current_length > max_length: ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in a string and returns the longest string of consecutive repeated characters. For example, if the input string is \"aabbbccaa\", the function should return \"bbb\", as \"bbb\" has the maximum number of consecutive repeated characters.\nAnswer:\nLet's think ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3125, "level": 1, "question": "Create a function that takes in a string and returns the longest string of consecutive repeated characters. For example, if the input string is \"aabbbccaa\", the function should return \"bbb\", as \"bbb\" has the maximum number of consecutive repeated...
def sieve_of_eratosthenes(n): if n < 2: return [] sieve = [True] * n sieve[0] = sieve[1] = False for i in range(2, int(n ** 0.5) + 1): if sieve[i]: for j in range(i * i, n, i): sieve[j] = False primes = [i for i, is_prime in enumerate(sieve) if is_prime] ...
simplelr_Filter
[ { "content": "Question:\nHere's a simple task for you: given an integer n ≥ 2, generate an array of all prime numbers less than n. \n\nCan you write a code to accomplish this?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3126, "level": 1, "question": "Here's a simple task for you: given an integer n ≥ 2, generate an array of all prime numbers less than n. \n\nCan you write a code to accomplish this?", "split": "train" }
from typing import List def single_number(nums: List[int]) -> int: res = 0 for num in nums: res ^= num return res
simplelr_Data_Structure
[ { "content": "Question:\n**Task**:\n\nYou are given a list of integers `nums` where every element appears twice except for one. Your task is to find the single one.\n\n**Function Signature**:\n```python\ndef single_number(nums: List[int]) -> int:\n \"\"\"\n This function finds and returns the single uniqu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3127, "level": 1, "question": "**Task**:\n\nYou are given a list of integers `nums` where every element appears twice except for one. Your task is to find the single one.\n\n**Function Signature**:\n```python\ndef single_number(nums: List[int]) -> int:\n \"\"\"\n This function...
def enhanced_comb_sort(arr: list) -> list: if len(arr) <= 1: return arr gap = len(arr) - 1 while gap > 1: swap_count = 0 for i in range(len(arr) - gap): if arr[i] > arr[i + gap]: arr[i], arr[i + gap] = arr[i + gap], arr[i] swap_count += 1 ...
simplelr_Data_Structure
[ { "content": "Question:\nCustom Comb Sort Enhancement\n\n**Objective**:\nEnhance the provided Comb Sort algorithm to handle an additional constraint and optimize its performance for a specific data pattern.\n\n**Scenario**:\nIn a system where you frequently need to sort lists of varying lengths, most of the lis...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3128, "level": 1, "question": "Custom Comb Sort Enhancement\n\n**Objective**:\nEnhance the provided Comb Sort algorithm to handle an additional constraint and optimize its performance for a specific data pattern.\n\n**Scenario**:\nIn a system where you frequently need to sort lists ...
def three_sum(nums): nums.sort() res = [] n = len(nums) for i in range(n - 2): # Skip duplicate i if i > 0 and nums[i] == nums[i - 1]: continue left = i + 1 right = n - 1 while left < right: current_sum = nums[i] + nums[left] + nums[right] ...
simplelr_Apps
[ { "content": "Question:\n# Task\nGiven an array of integers, find all unique triplets in the array which gives the sum of zero.\n\n# Example\n\nFor `nums = [-1, 0, 1, 2, -1, -4]`, the output should be `[[ -1, -1, 2 ], [ -1, 0, 1 ]]`\n\nFor `nums = [0, 1, 1]`, the output should be `[]`\n\nFor `nums = [ 0, 0, 0 ]...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3129, "level": 1, "question": "# Task\nGiven an array of integers, find all unique triplets in the array which gives the sum of zero.\n\n# Example\n\nFor `nums = [-1, 0, 1, 2, -1, -4]`, the output should be `[[ -1, -1, 2 ], [ -1, 0, 1 ]]`\n\nFor `nums = [0, 1, 1]`, the output should...
def is_valid_move(board, position): """ Checks if a move is valid on a tic-tac-toe board. Args: board: A list representing the tic-tac-toe board. position: An integer representing the desired position on the board. Returns: True if the move is valid, False otherwise. ...
simplelr_Filter
[ { "content": "Question:\nThis code snippet defines a function called `is_valid_move()` in Python that takes two arguments:\n\n* `board`: Represents the current state of the tic-tac-toe board.\n\n* `position`: Represents the position on the board where the player wants to move.\n\nThe function checks if the give...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3130, "level": 1, "question": "This code snippet defines a function called `is_valid_move()` in Python that takes two arguments:\n\n* `board`: Represents the current state of the tic-tac-toe board.\n\n* `position`: Represents the position on the board where the player wants to move....
def stoogesort(arr, l, h): if l >= h: return # Swap if the first element is smaller than the last if arr[l] > arr[h]: arr[l], arr[h] = arr[h], arr[l] # If segment size is greater than 2, recursively sort if h - l + 1 > 2: stoogesort(arr, l, h-1) stoogesort(arr, l+1, h...
simplelr_Data_Structure
[ { "content": "Question:\n### Scenario:\nYou are required to implement a recursive sorting algorithm called Stooge Sort, which demonstrates the basic principles of recursion and sorting. Stooge Sort works by sorting the array in three main steps: swapping elements, recursively sorting portions of the array, and ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3131, "level": 1, "question": "### Scenario:\nYou are required to implement a recursive sorting algorithm called Stooge Sort, which demonstrates the basic principles of recursion and sorting. Stooge Sort works by sorting the array in three main steps: swapping elements, recursively ...
def list_to_dict(lst): result = {} for s in lst: result[s] = len(s) return result
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that converts a given list of strings into a dictionary, where each string in the list becomes a key, and the value is the length of that string. The function should also handle an empty list by returning an empty dictionary.\nAnswer:\nLet's think step by step.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3132, "level": 1, "question": "Write a Python function that converts a given list of strings into a dictionary, where each string in the list becomes a key, and the value is the length of that string. The function should also handle an empty list by returning an empty dictionary.", ...
def generate_primes(n): if n == 0: return [] upper = 10 # Initial upper bound estimate while True: sieve = [True] * (upper + 1) sieve[0] = sieve[1] = False for i in range(2, int(upper ** 0.5) + 1): if sieve[i]: sieve[i*i : upper+1 : i] = [False] *...
simplelr_Evol
[ { "content": "Question:\nWrite a function that takes an integer `n` and returns a list of the first `n` prime numbers. Use the Sieve of Eratosthenes algorithm to generate the prime numbers efficiently. \n\nFor example, given `n = 5`, the function should return `[2, 3, 5, 7, 11]`.\n\n```python\ndef generate_prim...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3133, "level": 1, "question": "Write a function that takes an integer `n` and returns a list of the first `n` prime numbers. Use the Sieve of Eratosthenes algorithm to generate the prime numbers efficiently. \n\nFor example, given `n = 5`, the function should return `[2, 3, 5, 7, 11...
def list_of_tuples_to_dict(people): return {name: age for name, age in people}
simplelr_Filter
[ { "content": "Question:\nCan you provide a simple example of a Python function that converts a list of tuples, where each tuple contains a name and an age, to a dictionary with names as keys and ages as values?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3134, "level": 1, "question": "Can you provide a simple example of a Python function that converts a list of tuples, where each tuple contains a name and an age, to a dictionary with names as keys and ages as values?", "split": "train" }
def word_count(s): words = s.split() word_counts = {} for word in words: lower_word = word.lower() if lower_word in word_counts: word_counts[lower_word] += 1 else: word_counts[lower_word] = 1 return word_counts
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a string as input and returns a dictionary where the keys are the unique words in the string and the values are the number of times each word appears in the string. Consider words to be separated by spaces and ignore case sensitivity.\nAnswer:\nLet's t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3135, "level": 1, "question": "Write a Python function that takes a string as input and returns a dictionary where the keys are the unique words in the string and the values are the number of times each word appears in the string. Consider words to be separated by spaces and ignore ...
def access_reserved_key(d, k): return d.get(k) if isinstance(d, dict) else None
simplelr_Filter
[ { "content": "Question:\nIn a certain programming language, \"parent\" is a keyword that cannot be used as a variable name. In fact, we just learned that all keywords in this programming language are reserved and cannot be used as variable names. So if we have an object with a key named \"parent\", we have to u...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3136, "level": 1, "question": "In a certain programming language, \"parent\" is a keyword that cannot be used as a variable name. In fact, we just learned that all keywords in this programming language are reserved and cannot be used as variable names. So if we have an object with a...
def decision_tree_iris(): """ This function implements the following steps: 1. Loads the Iris dataset. 2. Trains a Decision Tree classifier. 3. Visualizes the Decision Tree. 4. Evaluates the model using cross-validation. 5. Prunes the Decision Tree using minimal cost-complexity pruning. ...
simplelr_Docs
[ { "content": "Question:\n### Decision Tree Implementation and Visualization using scikit-learn\n\n#### Problem Statement:\nYou are provided with the Iris dataset, a classic dataset in machine learning. Your task is to implement a Decision Tree classifier using `scikit-learn`. You need to train the model, visual...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3137, "level": 1, "question": "### Decision Tree Implementation and Visualization using scikit-learn\n\n#### Problem Statement:\nYou are provided with the Iris dataset, a classic dataset in machine learning. Your task is to implement a Decision Tree classifier using `scikit-learn`. ...
def isHarmonious(n, k, sequence): if n == 1: return True for i in range(n - 1): if (sequence[i] + sequence[i + 1]) % k != 0: return False return True
simplelr_Code_Contests
[ { "content": "Question:\nIn a remote village, there is a legend about a mythical sequence called the \"Harmonious Sequence.\" A Harmonious Sequence of length n is an array of integers where the sum of every pair of consecutive integers is divisible by a given integer k.\n\nYou, as an aspiring coder, are tasked ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3138, "level": 1, "question": "In a remote village, there is a legend about a mythical sequence called the \"Harmonious Sequence.\" A Harmonious Sequence of length n is an array of integers where the sum of every pair of consecutive integers is divisible by a given integer k.\n\nYou...
import torch def rank_columns(tensor): """ This function takes a 2D tensor as input and returns a new tensor where the values in each column are replaced by their ranks within that column. The ranks are 1-based, meaning the smallest value gets rank 1, the second smallest rank 2, etc. In case of ties, ident...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a 2D tensor as input and returns a new tensor where the values in each column are replaced by their rank within that column. The function should work with PyTorch, a popular tensor library. The ranks should be 1-based, meaning the smallest value in eac...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3139, "level": 1, "question": "Write a Python function that takes a 2D tensor as input and returns a new tensor where the values in each column are replaced by their rank within that column. The function should work with PyTorch, a popular tensor library. The ranks should be 1-based...
def unique_paths_with_obstacles(grid): n = len(grid) m = len(grid[0]) if n > 0 else 0 if grid[0][0] == 'X': return 0 dp = [[0 for _ in range(m)] for _ in range(n)] dp[0][0] = 1 for i in range(n): for j in range(m): if i == 0 and j == 0: continue ...
simplelr_Apps
[ { "content": "Question:\nGiven an n x m matrix where each cell is either empty (represented by '.') or contains an obstacle (represented by 'X'), determine the number of different paths from the top-left corner (0,0) to the bottom-right corner (n-1, m-1) such that you can only move down or right at any point in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3140, "level": 1, "question": "Given an n x m matrix where each cell is either empty (represented by '.') or contains an obstacle (represented by 'X'), determine the number of different paths from the top-left corner (0,0) to the bottom-right corner (n-1, m-1) such that you can only...
import random def generate_random_integer(start, end): # Ensure start is less than or equal to end if start > end: start, end = end, start return random.randint(start, end) # Example usage: print(generate_random_integer(1, 10)) # Generates a random integer between 1 and 10, inclusive
simplelr_Filter
[ { "content": "Question:\nI need help with a problem I'm having. I'm writing a program that needs to generate random numbers within a specific range.\n\nSpecifically, I need to generate a random integer between two given integers, both inclusive.\n\nCan you provide me with a code snippet that demonstrates how to...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3141, "level": 1, "question": "I need help with a problem I'm having. I'm writing a program that needs to generate random numbers within a specific range.\n\nSpecifically, I need to generate a random integer between two given integers, both inclusive.\n\nCan you provide me with a co...
import matplotlib.pyplot as plt import seaborn as sns import matplotlib.gridspec as gridspec def plot_penguins_kde(): # Load the penguins dataset df = sns.load_dataset('penguins') # Create a figure with a gridspec layout fig = plt.figure(figsize=(10, 10)) fig.suptitle('KDE Plot of Penguins Dat...
simplelr_Docs
[ { "content": "Question:\n#### Objective:\nCreate a comprehensive KDE plot using Seaborn that demonstrates your mastery of both fundamental and advanced functionalities of the `sns.kdeplot` function.\n\n#### Task:\n1. **Dataset**:\n - Use the `penguins` dataset included with Seaborn. Load it using `sns.load_da...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3142, "level": 1, "question": "#### Objective:\nCreate a comprehensive KDE plot using Seaborn that demonstrates your mastery of both fundamental and advanced functionalities of the `sns.kdeplot` function.\n\n#### Task:\n1. **Dataset**:\n - Use the `penguins` dataset included with ...
def countBinarySubstrings(s: str) -> int: if not s: return 0 # Generate run-length encoding runs = [] current_char = s[0] count = 1 for c in s[1:]: if c == current_char: count += 1 else: runs.append((current_char, count)) current_char ...
simplelr_Codeforces
[ { "content": "Question:\nWrite a function that takes a string as input and returns an integer. The input string will only contain binary digits ('0' or '1'). The function should calculate the number of substrings that have equal numbers of consecutive '0's and '1's.\n\nFor example, for the input \"00110011\", t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3143, "level": 1, "question": "Write a function that takes a string as input and returns an integer. The input string will only contain binary digits ('0' or '1'). The function should calculate the number of substrings that have equal numbers of consecutive '0's and '1's.\n\nFor exa...
from collections import deque def shortest_path(grid, start, target): if not grid or not grid[0]: return -1 rows = len(grid) cols = len(grid[0]) if start == target: return 0 start_row, start_col = start target_row, target_col = target visited = [[False for _ in range(cols)] ...
simplelr_Taco
[ { "content": "Question:\n## Robot Navigation Challenge - Shortest Path Algorithm\n\n## About this Challenge\n\nIn this challenge, we will explore a robot navigation problem in a grid-like environment. The robot can move in four directions: up, down, left, and right. The objective is to find the shortest path fr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3144, "level": 1, "question": "## Robot Navigation Challenge - Shortest Path Algorithm\n\n## About this Challenge\n\nIn this challenge, we will explore a robot navigation problem in a grid-like environment. The robot can move in four directions: up, down, left, and right. The object...
def rotate_array(arr: list, steps: int) -> list: """ Rotates the array to the right by the given number of steps. Parameters: arr (list): The input array to be rotated. steps (int): The number of steps to rotate the array. Returns: list: The rotated array. Raises: TypeErr...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement: Array Rotation with Bounds Checking\n\nYou are required to implement a function `rotate_array` that rotates an array to the right by a specified number of steps. The function should handle cases where the number of steps is negative or exceeds the length of the ar...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3145, "level": 1, "question": "### Problem Statement: Array Rotation with Bounds Checking\n\nYou are required to implement a function `rotate_array` that rotates an array to the right by a specified number of steps. The function should handle cases where the number of steps is negat...
def average_sale_per_week(sales): if not sales: return -1 return sum(sales) / len(sales)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes the weekly sales data for a company as a list of sales figures and calculates the average sale per week. If the data is not available (i.e., the list is empty), return -1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3146, "level": 1, "question": "Create a function that takes the weekly sales data for a company as a list of sales figures and calculates the average sale per week. If the data is not available (i.e., the list is empty), return -1.", "split": "train" }
import uuid def analyze_uuid(uuid_input): u = uuid.UUID(uuid_input) bytes_representation = u.bytes # Extract each field using the bytes time_low = int.from_bytes(bytes_representation[0:4], byteorder='big') time_mid = int.from_bytes(bytes_representation[4:6], byteorder='big') time_hi_version = i...
simplelr_Docs
[ { "content": "Question:\n**UUID Manipulation and Analysis**\n\n**Objective:**\n\nYour task is to write a Python function that will generate a specific type of UUID, analyze its attributes, and perform operations based on those attributes.\n\n**Description:**\n\n1. Implement a function `analyze_uuid(uuid_input)`...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3147, "level": 1, "question": "**UUID Manipulation and Analysis**\n\n**Objective:**\n\nYour task is to write a Python function that will generate a specific type of UUID, analyze its attributes, and perform operations based on those attributes.\n\n**Description:**\n\n1. Implement a ...
def is_prime(n: int) -> bool: if n <= 1: return False if n == 2: return True if n % 2 == 0: return False max_divisor = int(n ** 0.5) + 1 for i in range(3, max_divisor, 2): if n % i == 0: return False return True
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question: Prime Number Identifier\n\n**Context**:\n\nIn computer science and cryptography, prime numbers play a crucial role. A prime number is a natural number greater than 1 that is not the product of two smaller natural numbers. Your task is to implement a funct...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3148, "level": 1, "question": "### Coding Assessment Question: Prime Number Identifier\n\n**Context**:\n\nIn computer science and cryptography, prime numbers play a crucial role. A prime number is a natural number greater than 1 that is not the product of two smaller natural numbers...
import pandas as pd def summarize_sales(data: pd.DataFrame) -> pd.DataFrame: """ Summarizes the total sales per category. Args: - data (pd.DataFrame): A pandas DataFrame with columns ['Category', 'Product', 'Sales']. Returns: - pd.DataFrame: A pandas DataFrame with columns ['Category', 'Total...
simplelr_Docs
[ { "content": "Question:\n### Pandas Copy-on-Write Assessment\n\n#### Background\nStarting with pandas version 3.0, the Copy-on-Write (CoW) mechanism ensures that DataFrame and Series operations do not lead to unintended side effects by preventing shared data mutations. This change mitigates unpredictable behavi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3149, "level": 1, "question": "### Pandas Copy-on-Write Assessment\n\n#### Background\nStarting with pandas version 3.0, the Copy-on-Write (CoW) mechanism ensures that DataFrame and Series operations do not lead to unintended side effects by preventing shared data mutations. This ch...
def transpose(matrix): return list(map(list, zip(*matrix)))
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the transpose of a matrix.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3150, "level": 1, "question": "Write a python function to find the transpose of a matrix.", "split": "train" }
def isPalindrome(s): processed = ''.join(filter(str.isalnum, s)).lower() return processed == processed[::-1]
simplelr_Taco
[ { "content": "Question:\n## Palindrome Check - Simple But Useful\n\n## Background Story\n\nYou are a software engineer working for a startup that has developed a new social media app. In this app, users can send messages to each other. However, your team decided to add a fun feature that checks if a user's mess...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3151, "level": 1, "question": "## Palindrome Check - Simple But Useful\n\n## Background Story\n\nYou are a software engineer working for a startup that has developed a new social media app. In this app, users can send messages to each other. However, your team decided to add a fun f...
def final_sum(nums): return sum(nums)
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `nums` representing the scores of `n` students, your task is to determine the resultant array after a series of operations. In each operation, you must: \n\n1. Select an adjacent pair of elements, remove them from the array, and replace them with their sum.\n2...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3152, "level": 1, "question": "Given an array of integers `nums` representing the scores of `n` students, your task is to determine the resultant array after a series of operations. In each operation, you must: \n\n1. Select an adjacent pair of elements, remove them from the array, ...
def moveValueToEnd(arr, val): write_pointer = 0 for i in range(len(arr)): if arr[i] != val: arr[write_pointer], arr[i] = arr[i], arr[write_pointer] write_pointer += 1 return arr
simplelr_Taco
[ { "content": "Question:\nYou are given an array of integers, and your task is to modify it in-place so that all instances of a specified value appear at the end of the array, while preserving the order of the other elements.\n\nFor example, consider the array [3, 1, 2, 3, 4, 3] and the specified value 3. The ou...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3153, "level": 1, "question": "You are given an array of integers, and your task is to modify it in-place so that all instances of a specified value appear at the end of the array, while preserving the order of the other elements.\n\nFor example, consider the array [3, 1, 2, 3, 4, 3...
import math def circle_area(radius): if radius <= 0: raise ValueError("Radius must be a positive number.") area = math.pi * (radius ** 2) return area
simplelr_Prefill
[ { "content": "Question:\nWrite a function to calculate the area of a circle given its radius. The function should handle the case where the radius is not a positive number by raising an exception.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3154, "level": 1, "question": "Write a function to calculate the area of a circle given its radius. The function should handle the case where the radius is not a positive number by raising an exception.", "split": "train" }
def find_nth_digit(n: int) -> int: d = 1 count = 9 start = 1 while n > d * count: n -= d * count d += 1 count *= 10 start *= 10 number = start + (n - 1) // d digit_index = (n - 1) % d return int(str(number)[digit_index])
simplelr_Data_Structure
[ { "content": "Question:\nIn many programming challenges, determining specific digits at certain positions within a large sequence of concatenated numbers can be crucial. Your task is to implement a function that efficiently finds the nth digit in the infinite integer sequence \"123456789101112...\".\n\n**Functi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3155, "level": 1, "question": "In many programming challenges, determining specific digits at certain positions within a large sequence of concatenated numbers can be crucial. Your task is to implement a function that efficiently finds the nth digit in the infinite integer sequence ...
def majorityElement(nums): count = 0 candidate = None for num in nums: if count == 0: candidate = num count = 1 elif num == candidate: count += 1 else: count -= 1 return candidate
simplelr_Filter
[ { "content": "Question:\nleetcode 169. Majority Element python3 solution\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3156, "level": 1, "question": "leetcode 169. Majority Element python3 solution", "split": "train" }
def find_unsorted_subarray(nums): sorted_nums = sorted(nums) n = len(nums) left = 0 while left < n and nums[left] == sorted_nums[left]: left += 1 if left == n: return 0 right = n - 1 while right >= 0 and nums[right] == sorted_nums[right]: right -= 1 return right -...
simplelr_Apps
[ { "content": "Question:\nGiven a list of integers nums, find the length of the shortest subarray, that when sorted, makes the entire list sorted in non-decreasing order.\n\nReturn the length of the shortest subarray.\n\nExample 1:\n\nInput: nums = [2, 6, 4, 8, 10, 9, 15]\nOutput: 5\nExplanation: Sorting the sub...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3157, "level": 1, "question": "Given a list of integers nums, find the length of the shortest subarray, that when sorted, makes the entire list sorted in non-decreasing order.\n\nReturn the length of the shortest subarray.\n\nExample 1:\n\nInput: nums = [2, 6, 4, 8, 10, 9, 15]\nOutp...
def single_number(a): res = 0 for num in a: res ^= num return res
simplelr_Taco
[ { "content": "Question:\n# Task\n You are given a list of integers where every integer appears twice, except for one. Find the integer that appears only once.\n\n# Example\n\n For `a = [4, 1, 2, 1, 2]`, the result should be `4`\n ```\nYou have 5 integers: \n [4, 1, 2, 1, 2]\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3158, "level": 1, "question": "# Task\n You are given a list of integers where every integer appears twice, except for one. Find the integer that appears only once.\n\n# Example\n\n For `a = [4, 1, 2, 1, 2]`, the result should be `4`\n ```\nYou have 5 integers: \n ...
from datetime import date def day_of_week(s): year, month, day = map(int, s.split('-')) d = date(year, month, day) days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] return days_of_week[d.weekday()]
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` representing a date in the format \"YYYY-MM-DD\". You need to calculate the day of the week for the given date. The input date is always a valid date between the years 1971 and 2100 (inclusive). Implement a function that returns the day of the week for the giv...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3159, "level": 1, "question": "You are given a string `s` representing a date in the format \"YYYY-MM-DD\". You need to calculate the day of the week for the given date. The input date is always a valid date between the years 1971 and 2100 (inclusive). Implement a function that retu...
def group_and_sort_by_first_occurrence(lst): groups = {} for num in lst: if num not in groups: groups[num] = [] groups[num].append(num) result = [] for group in groups.values(): result += group return result
simplelr_Apps
[ { "content": "Question:\nGiven a list of integers, group all the identical elements together and return the sorted list based on the first occurrence of each number.\n\nExample 1:\n\nInput:\n[4, 5, 6, 4, 6, 6, 7, 4, 7, 4]\n\nOutput:\n[4, 4, 4, 4, 5, 6, 6, 6, 7, 7]\n\nExplanation:\n- The number 4 appears first a...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3160, "level": 1, "question": "Given a list of integers, group all the identical elements together and return the sorted list based on the first occurrence of each number.\n\nExample 1:\n\nInput:\n[4, 5, 6, 4, 6, 6, 7, 4, 7, 4]\n\nOutput:\n[4, 4, 4, 4, 5, 6, 6, 6, 7, 7]\n\nExplanati...
def can_partition(nums): total = sum(nums) if total % 2 != 0: return False target = total // 2 dp = [False] * (target + 1) dp[0] = True for num in nums: for j in range(target, num - 1, -1): if dp[j - num]: dp[j] = True if dp[target]: ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of `n` integers. You need to partition the list into two subsets such that the sum of the elements in both subsets is equal. Return `true` if you can achieve this partition, or `false` otherwise.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3161, "level": 1, "question": "You are given a list of `n` integers. You need to partition the list into two subsets such that the sum of the elements in both subsets is equal. Return `true` if you can achieve this partition, or `false` otherwise.", "split": "train" }
import pandas as pd def process_sales_data(file_path: str) -> pd.DataFrame: # Read the CSV file into a DataFrame df = pd.read_csv(file_path) # Calculate the mean of UnitsSold excluding NaN values units_mean = df['UnitsSold'].mean() # Fill missing UnitsSold with the mean df['UnitsSold'...
simplelr_Docs
[ { "content": "Question:\n**Handling Missing Values in Pandas**\n\nYou are provided with a CSV file containing sales data. The file has the following columns:\n\n- `Date`: The date of the sales (format: YYYY-MM-DD).\n- `Product`: The name of the product.\n- `UnitsSold`: The number of units sold.\n- `Revenue`: Th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3162, "level": 1, "question": "**Handling Missing Values in Pandas**\n\nYou are provided with a CSV file containing sales data. The file has the following columns:\n\n- `Date`: The date of the sales (format: YYYY-MM-DD).\n- `Product`: The name of the product.\n- `UnitsSold`: The num...
def pascal_triangle(n): if n == 0: return [[1]] triangle = [[1]] for i in range(1, n + 1): previous_row = triangle[-1] new_row = [1] for j in range(1, i): new_element = previous_row[j - 1] + previous_row[j] new_row.append(new_element) new_row.a...
simplelr_Package
[ { "content": "Question:\nIn this problem, you will write a function called `pascal_triangle` that generates the first `n` rows of Pascal’s triangle. Pascal’s triangle is a triangular array of the binomial coefficients. The entries in each row are the coefficients of the binomial expansion of \\((x + y)^n\\), an...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3163, "level": 1, "question": "In this problem, you will write a function called `pascal_triangle` that generates the first `n` rows of Pascal’s triangle. Pascal’s triangle is a triangular array of the binomial coefficients. The entries in each row are the coefficients of the binomi...
def maxUniqueSubarray(nums, k): from collections import defaultdict freq = defaultdict(int) left = 0 current_unique = 0 max_unique = 0 for right in range(len(nums)): add_num = nums[right] # Check if the number is entering the window for the first time if freq[add_num] =...
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers `nums` and an integer `k`, return the maximum number of unique integers among all contiguous subarrays of length `k`.\n\nExample 1:\nInput:\nnums = [1, 2, 1, 2, 3, 4, 5], k = 3\nOutput:\n3\nExplanation:\nThe subarrays of length 3 are:\n[1, 2, 1] - 2 unique num...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3164, "level": 1, "question": "Given an array of integers `nums` and an integer `k`, return the maximum number of unique integers among all contiguous subarrays of length `k`.\n\nExample 1:\nInput:\nnums = [1, 2, 1, 2, 3, 4, 5], k = 3\nOutput:\n3\nExplanation:\nThe subarrays of leng...
def is_permutation(s1, s2): if len(s1) != len(s2): return False # Initialize two arrays to count occurrences of each character count1 = [0] * 256 count2 = [0] * 256 # Populate the count arrays for c in s1: count1[ord(c)] += 1 for c in s2: count2[ord(c)] += 1...
simplelr_Filter
[ { "content": "Question:\nThis is a question from Cracking the Coding Interview:\n\nGiven two strings, write a method to decide if\none is a permutation of the other.\n\n**Example:**\nInput: string1 = \"abc\", string2 = \"cba\"\nOutput: True\n\n**Follow up:** can you solve it in O(n) time complexity?\nAnswer:\nL...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3165, "level": 1, "question": "This is a question from Cracking the Coding Interview:\n\nGiven two strings, write a method to decide if\none is a permutation of the other.\n\n**Example:**\nInput: string1 = \"abc\", string2 = \"cba\"\nOutput: True\n\n**Follow up:** can you solve it i...
def canAttendMeetings(meeting_intervals): if not meeting_intervals: return True sorted_intervals = sorted(meeting_intervals) for i in range(1, len(sorted_intervals)): if sorted_intervals[i][0] < sorted_intervals[i-1][1]: return False return True
simplelr_Taco
[ { "content": "Question:\n## Meeting Room Scheduling\n\n## Overview\n\nYou are tasked with creating a function that helps manage the scheduling of a single meeting room. Given a list of meeting time intervals, your function should determine if a person could attend all meetings without any overlaps. Each meeting...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3166, "level": 1, "question": "## Meeting Room Scheduling\n\n## Overview\n\nYou are tasked with creating a function that helps manage the scheduling of a single meeting room. Given a list of meeting time intervals, your function should determine if a person could attend all meetings...
def find_target_positions(lst, target, n): result = [] for idx, num in enumerate(lst): if num == target: result.append((idx, num)) return result[:n]
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in three arguments: a list of integers, a target integer, and a number of results to return. The function should return a list of tuples that represent the positions and values of the target integer within the list. If the target is not found, the function s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3167, "level": 1, "question": "Create a function that takes in three arguments: a list of integers, a target integer, and a number of results to return. The function should return a list of tuples that represent the positions and values of the target integer within the list. If the ...
def check_divisibility(a, b): a_divisible_by_3 = a % 3 == 0 a_divisible_by_5 = a % 5 == 0 b_divisible_by_3 = b % 3 == 0 b_divisible_by_5 = b % 5 == 0 if a_divisible_by_3 and a_divisible_by_5 and b_divisible_by_3 and b_divisible_by_5: return "Divisible by both 3 and 5" elif a_divisible_b...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes two numbers as input and returns whether they are divisible by 3 and 5. If both conditions are met, return \"Divisible by both 3 and 5\". If only 3 is met, return \"Divisible by 3\". If only 5 is met, return \"Divisible by 5\". If neither condition is met, r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3168, "level": 1, "question": "Create a function that takes two numbers as input and returns whether they are divisible by 3 and 5. If both conditions are met, return \"Divisible by both 3 and 5\". If only 3 is met, return \"Divisible by 3\". If only 5 is met, return \"Divisible by ...
def min_operations(source: str, target: str) -> int: m = len(source) n = len(target) dp = [[0] * (n + 1) for _ in range(m + 1)] # Initialize the base cases for i in range(m + 1): dp[i][0] = i for j in range(n + 1): dp[0][j] = j for i in range(1, m + 1): for ...
simplelr_Algorithm
[ { "content": "Question:\n**Objective**: Write a function to determine the minimum number of moves required to transform one string into another using a given set of operations.\n\n**Function Signature**:\n```python\ndef min_operations(source: str, target: str) -> int:\n pass\n```\n\n**Input Format**:\n* `sou...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3169, "level": 1, "question": "**Objective**: Write a function to determine the minimum number of moves required to transform one string into another using a given set of operations.\n\n**Function Signature**:\n```python\ndef min_operations(source: str, target: str) -> int:\n pas...
def uniqueKLengthSubarrays(nums, k): n = len(nums) prefix = [0] * (n + 1) for i in range(1, n + 1): prefix[i] = prefix[i - 1] + nums[i - 1] mod = [x % k for x in prefix] count = 0 for i in range(n - k + 1): if mod[i] == mod[i + k]: count += 1 return count
simplelr_Taco
[ { "content": "Question:\nYou are given an array of non-negative integers `nums` and an integer `k`. A \"continuous subarray\" is defined as a contiguous portion of the array that can be obtained by deleting some (or none) of the elements from the beginning and the end of the array. You are required to find the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3170, "level": 1, "question": "You are given an array of non-negative integers `nums` and an integer `k`. A \"continuous subarray\" is defined as a contiguous portion of the array that can be obtained by deleting some (or none) of the elements from the beginning and the end of the a...
def process_items(items: list, required_key: str, filter_func: callable, replace_key: str, new_replace_key: str, transform_func: callable, sort_by_key: str) -> list: # Filter the items based on the required_key and filter_func filtered = [] for item in items: if required_key in item and filter_func(...
simplelr_Docs
[ { "content": "Question:\n**Question: Advanced Sequence and Mapping Manipulation**\n\nGiven a list of dictionaries, each dictionary representing information about an item, write a function `process_items` that performs the following tasks:\n1. **Filter**: Remove dictionaries that do not contain a specified key `...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3171, "level": 1, "question": "**Question: Advanced Sequence and Mapping Manipulation**\n\nGiven a list of dictionaries, each dictionary representing information about an item, write a function `process_items` that performs the following tasks:\n1. **Filter**: Remove dictionaries th...
import string def is_pangram(text): """Checks if a string is a pangram. Args: text: The string to check. Returns: True if the string is a pangram, False otherwise. """ text = text.lower() alphabet = set(string.ascii_lowercase) return alphabet.issubset(set(text))
simplelr_Filter
[ { "content": "Question:\nThis is a sample text:\n\n**\"The quick brown fox jumps over the lazy dog.\"**\n\nThis sentence is often used as a pangram, a sentence that contains every letter of the alphabet.\n\nCan you write a program in Python that determines if a given string is a pangram?\n\n**Here's what I have...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3172, "level": 1, "question": "This is a sample text:\n\n**\"The quick brown fox jumps over the lazy dog.\"**\n\nThis sentence is often used as a pangram, a sentence that contains every letter of the alphabet.\n\nCan you write a program in Python that determines if a given string is...
def matrixSum(matrix): return sum([element for row in matrix for element in row if element >= 0])
simplelr_Apps
[ { "content": "Question:\n## Task\n\nCreate a function `matrixSum` that takes a 2D list (a list of lists) of integers and returns the sum of all the non-negative integers in the matrix.\n\n### Process\n1. **Understanding the Structure:**\n - The input is a matrix represented as a list of lists where each subli...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3173, "level": 1, "question": "## Task\n\nCreate a function `matrixSum` that takes a 2D list (a list of lists) of integers and returns the sum of all the non-negative integers in the matrix.\n\n### Process\n1. **Understanding the Structure:**\n - The input is a matrix represented ...
def greatest_difference(lst): return max(lst) - min(lst)
simplelr_Apps
[ { "content": "Question:\n# Task\n Write a function that, given a list of integers `lst`, returns the greatest difference between any two integers in it.\n\n# Example\n\n For `lst = [1, 2, 3, 8, 9]`, the output should be `8` (difference between 9 and 1).\n\n For `lst = [5, 1, -10, 5, 10]`, the output should be `...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3174, "level": 1, "question": "# Task\n Write a function that, given a list of integers `lst`, returns the greatest difference between any two integers in it.\n\n# Example\n\n For `lst = [1, 2, 3, 8, 9]`, the output should be `8` (difference between 9 and 1).\n\n For `lst = [5, 1, -...
import numpy as np def collaborative_filtering(R, num_features, alpha, lambda_reg, num_epochs): """ Trains a collaborative filtering model using gradient descent to predict ratings. Parameters: R: numpy.ndarray -- User-item rating matrix (num_users, num_items) num_features: int -- Numb...
simplelr_Package
[ { "content": "Question:\nYour task is to implement a simple collaborative filtering-based recommendation system in Python to predict user ratings for unseen items. You need to use the mean squared error (MSE) as the cost function to optimize the parameters.\n\nWrite a function named `collaborative_filtering` wi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3175, "level": 1, "question": "Your task is to implement a simple collaborative filtering-based recommendation system in Python to predict user ratings for unseen items. You need to use the mean squared error (MSE) as the cost function to optimize the parameters.\n\nWrite a function...
def simulate_bank(customers, interest_rate, initial_year, years_to_simulate): result = {} for customer in customers: name = customer["name"] balance = customer["balance"] factor = (1 + interest_rate) ** years_to_simulate new_balance = balance * factor rounded_balance = ro...
simplelr_Filter
[ { "content": "Question:\nIn this problem, you will simulate a simple banking system. The bank has a list of its customers, along with their account balances. The bank also has an interest rate, which is applied to every customer's account at the end of each year. The interest is compounded annually. \n\nYou wil...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3176, "level": 1, "question": "In this problem, you will simulate a simple banking system. The bank has a list of its customers, along with their account balances. The bank also has an interest rate, which is applied to every customer's account at the end of each year. The interest ...
def find_gcd(a: int, b: int) -> int: if type(a) is not int or type(b) is not int: raise TypeError("Both inputs must be integers") while b != 0: a, b = b, a % b return abs(a)
simplelr_Algorithm
[ { "content": "Question:\n### Description:\nIn this task, you need to create a function that calculates the greatest common divisor (GCD) of two given integers using an efficient algorithm. The goal is to test your ability to implement classical algorithms and optimize them for performance. Ensure your solution ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3177, "level": 1, "question": "### Description:\nIn this task, you need to create a function that calculates the greatest common divisor (GCD) of two given integers using an efficient algorithm. The goal is to test your ability to implement classical algorithms and optimize them for...
def reverse_string_ignore_case(s): return s[::-1]
simplelr_Prefill
[ { "content": "Question:\nWrite a function to reverse a string in Python. However, the function should reverse the string while ignoring the case sensitivity. For example, given the string \"Hello, World!\", the function should return \"dlroW ,olleH\".\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3178, "level": 1, "question": "Write a function to reverse a string in Python. However, the function should reverse the string while ignoring the case sensitivity. For example, given the string \"Hello, World!\", the function should return \"dlroW ,olleH\".", "split": "train" }
def process_inputs(n, s, b): if b: return s * n else: return str(n) + s
simplelr_Prefill
[ { "content": "Question:\nCreate a function that receives an integer, a lowercase string, and a boolean value as inputs and returns a value depending on the boolean. If the boolean is True, the function should return the string repeated the number of times specified by the integer. If the boolean is False, the f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3179, "level": 1, "question": "Create a function that receives an integer, a lowercase string, and a boolean value as inputs and returns a value depending on the boolean. If the boolean is True, the function should return the string repeated the number of times specified by the inte...
def sieve_of_eratosthenes(n): if n < 2: return [] primes = [True] * (n + 1) primes[0], primes[1] = False, False # Explicitly set 0 and 1 as non-prime p = 2 while p ** 2 <= n: if primes[p]: for i in range(p ** 2, n + 1, p): primes[i] = False p += 1...
simplelr_Filter
[ { "content": "Question:\nHere is the code in Python to find all the prime numbers between 1 and n using the Sieve of Eratosthenes algorithm:\n\n```\ndef sieve_of_eratosthenes(n):\n primes = [True] * (n + 1)\n p = 2\n while p**2 <= n:\n if primes[p]:\n for i in range(p**2, n+1, p):\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3180, "level": 1, "question": "Here is the code in Python to find all the prime numbers between 1 and n using the Sieve of Eratosthenes algorithm:\n\n```\ndef sieve_of_eratosthenes(n):\n primes = [True] * (n + 1)\n p = 2\n while p**2 <= n:\n if primes[p]:\n ...
import sys import subprocess def ping_test(host, count=4, timeout=1): """ Ping a host and return True if reachable, False otherwise. """ # Determine the OS to set appropriate ping command if sys.platform.lower().startswith('win'): ping_cmd = ['ping', '-n', str(count), host, '-w', str(timeou...
simplelr_Filter
[ { "content": "Question:\nHow can I write a Python function to perform a ping test on a given IP address or hostname?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3181, "level": 1, "question": "How can I write a Python function to perform a ping test on a given IP address or hostname?", "split": "train" }
def sortStack(stack): temp = [] while stack: x = stack.pop() while temp and temp[-1] > x: stack.append(temp.pop()) temp.append(x) # Reverse the temp stack to get the correct order reversed_temp = [] while temp: reversed_temp.append(temp.pop()) while re...
simplelr_Filter
[ { "content": "Question:\nHere's an algorithm to generate a sorted stack using a temporary stack.\nWe use two stacks S and T. Stack S holds the actual data and stack T is our temporary stack used for processing.\n\n1. While S is not empty\n a. Pop an item from stack S and push it to stack T.\n2. While T is no...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3182, "level": 1, "question": "Here's an algorithm to generate a sorted stack using a temporary stack.\nWe use two stacks S and T. Stack S holds the actual data and stack T is our temporary stack used for processing.\n\n1. While S is not empty\n a. Pop an item from stack S and pu...
def trap(heights): n = len(heights) if n == 0: return 0 left = [0] * n for i in range(1, n): left[i] = max(left[i-1], heights[i-1]) right = [0] * n for i in range(n-2, -1, -1): right[i] = max(heights[i+1], right[i+1]) res = 0 for i in range(n): ...
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers representing the heights of a series of bars, where the width of each bar is 1, write a function to calculate how much water it is able to trap after raining.\n\nExample:\n\nInput: heights = [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput: 6\nExplanation: The array [0,1,0,2...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3183, "level": 1, "question": "Given an array of integers representing the heights of a series of bars, where the width of each bar is 1, write a function to calculate how much water it is able to trap after raining.\n\nExample:\n\nInput: heights = [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput:...
def longest_substring_without_repeating_characters(s: str) -> int: char_index = {} left = 0 max_length = 0 for right in range(len(s)): char = s[right] if char in char_index: if char_index[char] >= left: left = char_index[char] + 1 char_index[char] = ri...
simplelr_Evol
[ { "content": "Question:\n**Problem Statement:**\n\nWrite a function `longest_substring_without_repeating_characters(s: str) -> int` that takes a string `s` as input and returns the length of the longest substring without repeating characters.\n\n**Input:**\n- A single string `s` which consists of lowercase Engl...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3184, "level": 1, "question": "**Problem Statement:**\n\nWrite a function `longest_substring_without_repeating_characters(s: str) -> int` that takes a string `s` as input and returns the length of the longest substring without repeating characters.\n\n**Input:**\n- A single string `...
def common_elements(list_a, list_b): return list(set(list_a) & set(list_b))
simplelr_Filter
[ { "content": "Question:\nIs there a way to write a function (in Python) that takes in two lists and returns the elements that are common to both lists, without a loop?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3185, "level": 1, "question": "Is there a way to write a function (in Python) that takes in two lists and returns the elements that are common to both lists, without a loop?", "split": "train" }
from typing import List def process_order(store_inventory: List[int], order: List[int]) -> bool: # Check if the order can be fulfilled for i in range(len(order)): if store_inventory[i] < order[i]: return False # Update the store inventory for i in range(len(order)): store_in...
simplelr_Apps
[ { "content": "Question:\nA large multinational corporation has recently implemented a new automated order system for their retail stores. The system needs to ensure efficient processing of orders while confirming that the inventory levels are accurately maintained.\n\nEach store has an inventory represented as ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3186, "level": 1, "question": "A large multinational corporation has recently implemented a new automated order system for their retail stores. The system needs to ensure efficient processing of orders while confirming that the inventory levels are accurately maintained.\n\nEach sto...
def find_and_replace(file_path, old_text, new_text): if not isinstance(file_path, str): raise TypeError('File path must be a string') if not isinstance(old_text, str): raise TypeError('Old text must be a string') if not isinstance(new_text, str): raise TypeError('New text must be a s...
simplelr_Filter
[ { "content": "Question:\ndef find_and_replace(file_path, old_text, new_text):\n if not isinstance(file_path, str):\n raise TypeError('File path must be a string')\n if not isinstance(old_text, str):\n raise TypeError('Old text must be a string')\n if not isinstance(new_text, str):\n ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3187, "level": 1, "question": "def find_and_replace(file_path, old_text, new_text):\n if not isinstance(file_path, str):\n raise TypeError('File path must be a string')\n if not isinstance(old_text, str):\n raise TypeError('Old text must be a string')\n if not...
from typing import List, Dict def consolidate_inventory(inventories: List[str]) -> Dict[str, int]: inventory = {} for item_str in inventories: parts = item_str.split(':') item = parts[0] quantity = int(parts[1]) if item in inventory: inventory[item] += quantity ...
simplelr_Evol
[ { "content": "Question:\nYou are given a list of strings representing items and their quantities in different inventories. Each string is formatted as \"item:quantity\". Your task is to write a function `consolidate_inventory` that consolidates these inventories into a single inventory, summing up the quantitie...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3188, "level": 1, "question": "You are given a list of strings representing items and their quantities in different inventories. Each string is formatted as \"item:quantity\". Your task is to write a function `consolidate_inventory` that consolidates these inventories into a single ...
def sum_to_string(a, b): return str(a + b)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that calculates the sum of two numbers, but instead of returning the result directly, it should return the result in a string format. Additionally, ensure that the function can handle negative numbers and floating-point numbers.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3189, "level": 1, "question": "Create a function that calculates the sum of two numbers, but instead of returning the result directly, it should return the result in a string format. Additionally, ensure that the function can handle negative numbers and floating-point numbers.", "...
def evaluateExpression(expression: str) -> float: expr = expression.replace(' ', '') return float(eval(expr))
simplelr_Apps
[ { "content": "Question:\nYou're writing a small utility to parse and evaluate mathematical expressions. Expressions can include the +, -, *, and / operators, parentheses, and any number of whitespace characters which should be ignored.\n\nWrite a function `evaluateExpression(expression: str) -> float` that take...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3190, "level": 1, "question": "You're writing a small utility to parse and evaluate mathematical expressions. Expressions can include the +, -, *, and / operators, parentheses, and any number of whitespace characters which should be ignored.\n\nWrite a function `evaluateExpression(e...
def max_subarray_sum(arr): if not arr: return 0 # Handles empty array case, assuming 0 is an appropriate return value max_so_far = current_max = arr[0] for num in arr[1:]: current_max = max(num, current_max + num) if current_max > max_so_far: max_so_far = current_max ...
simplelr_Filter
[ { "content": "Question:\nWrite a 5-step algorithm in Python to find the maximum subarray sum for a given array. The maximum subarray sum is defined as the largest possible sum that can be obtained by summing up the elements of a contiguous subarray within the given array.\nAnswer:\nLet's think step by step.\n",...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3191, "level": 1, "question": "Write a 5-step algorithm in Python to find the maximum subarray sum for a given array. The maximum subarray sum is defined as the largest possible sum that can be obtained by summing up the elements of a contiguous subarray within the given array.", ...
def enhanced_gnome_sort(arr): n = len(arr) index = 0 while index < n: if index == 0 or arr[index] >= arr[index - 1]: index += 1 else: arr[index], arr[index - 1] = arr[index - 1], arr[index] index -= 1 return arr # Test cases to verify the solution pri...
simplelr_Data_Structure
[ { "content": "Question:\n**Context**: Imagine you are a developer for a shipping company that needs to sort parcels based on their weights before loading them onto trucks. You have an extremely simple sorting algorithm, Gnome Sort, implemented. Due to resource constraints, you need to use this algorithm to sort...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3192, "level": 1, "question": "**Context**: Imagine you are a developer for a shipping company that needs to sort parcels based on their weights before loading them onto trucks. You have an extremely simple sorting algorithm, Gnome Sort, implemented. Due to resource constraints, you...
def combine_lists(list1, list2): result = [] seen = set() for item in list1: item_id = item['id'] if item_id not in seen: result.append(item) seen.add(item_id) for item in list2: item_id = item['id'] if item_id not in seen: result.appen...
simplelr_Filter
[ { "content": "Question:\nI have two lists of objects (list1, list2) and I want to create a new list (result) where all elements from both lists are included, without duplicates. \n\nThe objects in the lists have two attributes: 'id' and 'value'. Two objects are considered equal if their 'id' attribute is the sa...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3193, "level": 1, "question": "I have two lists of objects (list1, list2) and I want to create a new list (result) where all elements from both lists are included, without duplicates. \n\nThe objects in the lists have two attributes: 'id' and 'value'. Two objects are considered equa...
def advanced_stutter(stack): result = [] for x in stack: result.append(x) result.append(x) return result
simplelr_Data_Structure
[ { "content": "Question:\n### Stack Stutter - Advanced Duplication Task\n\n**Objective**: Write a Python function to duplicate each element in a stack while ensuring minimal auxiliary space usage.\n\n#### Function Prototype:\n```python\ndef advanced_stutter(stack):\n pass\n```\n\n#### Input:\n- The function r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3194, "level": 1, "question": "### Stack Stutter - Advanced Duplication Task\n\n**Objective**: Write a Python function to duplicate each element in a stack while ensuring minimal auxiliary space usage.\n\n#### Function Prototype:\n```python\ndef advanced_stutter(stack):\n pass\n`...
from typing import List def merge_sorted_subarrays(arr: List[int], start1: int, end1: int, start2: int, end2: int) -> None: # Extract the two subarrays sub1 = arr[start1:end1 + 1] sub2 = arr[start2:end2 + 1] # Initialize indices for the merge process i = j = 0 merged = [] # Merge ...
simplelr_Algorithm
[ { "content": "Question:\n### Question: Merge Sorted Subarrays\n\nYou are given two non-decreasingly sorted subarrays residing within a larger array. Your task is to implement a function `merge_sorted_subarrays(arr: List[int], start1: int, end1: int, start2: int, end2: int) -> None` that merges these two subarra...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3195, "level": 1, "question": "### Question: Merge Sorted Subarrays\n\nYou are given two non-decreasingly sorted subarrays residing within a larger array. Your task is to implement a function `merge_sorted_subarrays(arr: List[int], start1: int, end1: int, start2: int, end2: int) -> ...
from typing import List def rotate_list(nums: List[int], k: int) -> List[int]: n = len(nums) if n == 0: return [] effective_k = k % n if effective_k == 0: return nums.copy() return nums[-effective_k:] + nums[:-effective_k]
simplelr_Evol
[ { "content": "Question:\nDesign a function that takes a list of integers and an integer `k`, and returns a list with the elements rotated to the right by `k` positions. For example, given the list `[1, 2, 3, 4, 5, 6, 7]` and `k = 3`, the output should be `[5, 6, 7, 1, 2, 3, 4]`. Ensure that the implementation h...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3196, "level": 1, "question": "Design a function that takes a list of integers and an integer `k`, and returns a list with the elements rotated to the right by `k` positions. For example, given the list `[1, 2, 3, 4, 5, 6, 7]` and `k = 3`, the output should be `[5, 6, 7, 1, 2, 3, 4]...
def repeat_string(A: str, B: str) -> int: len_A = len(A) len_B = len(B) if len_B > len_A: k_min = (len_B + len_A - 1) // len_A # Equivalent to ceiling division max_repeats = k_min + 2 S = A * max_repeats for k in range(k_min, max_repeats + 1): candidate_leng...
simplelr_Data_Structure
[ { "content": "Question:\n**Repeated String Matcher**\n\nYou have been tasked with implementing a function to determine how many times a string A needs to be repeated so that another string B becomes a substring of the repeated string. If it's not possible, the function should return -1. This problem can help in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3197, "level": 1, "question": "**Repeated String Matcher**\n\nYou have been tasked with implementing a function to determine how many times a string A needs to be repeated so that another string B becomes a substring of the repeated string. If it's not possible, the function should ...
def longest_word(sentence): words = sentence.split() max_length = 0 max_word = '' for word in words: if len(word) > max_length: max_length = len(word) max_word = word return max_word
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to find the longest word in a given sentence. If there are multiple words of the same maximum length, return the one that appears first in the sentence. Assume the sentence contains only letters and spaces.\nAnswer:\nLet's think step by step.\n", "role": "use...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3198, "level": 1, "question": "Write a Python function to find the longest word in a given sentence. If there are multiple words of the same maximum length, return the one that appears first in the sentence. Assume the sentence contains only letters and spaces.", "split": "train" ...
def is_perfect_palindrome(s): processed = ''.join([c.lower() for c in s if c.isalnum()]) return processed == processed[::-1]
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to check if a given string is a perfect palindrome. A perfect palindrome is a string that reads the same backward as forward, ignoring case sensitivity and non-alphanumeric characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 3199, "level": 1, "question": "Write a Python function to check if a given string is a perfect palindrome. A perfect palindrome is a string that reads the same backward as forward, ignoring case sensitivity and non-alphanumeric characters.", "split": "train" }