target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
import torch
from torch.testing import assert_close, make_tensor, assert_allclose
def validate_tensor_operations():
# Step 1: Create tensors a and b
a = make_tensor((3, 3), device=torch.device('cpu'), dtype=torch.float)
b = make_tensor((3, 3), device=torch.device('cpu'), dtype=torch.float)
# Step ... | simplelr_Docs | [
{
"content": "Question:\n### PyTorch Coding Assessment\n\n**Objective:**\nImplement a function that creates a sequence of tensors, performs specific manipulations, and finally validates the results using PyTorch assert functions.\n\n**Task:**\nWrite a function `validate_tensor_operations()` that performs the fo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4500,
"level": 1,
"question": "### PyTorch Coding Assessment\n\n**Objective:**\nImplement a function that creates a sequence of tensors, performs specific manipulations, and finally validates the results using PyTorch assert functions.\n\n**Task:**\nWrite a function `validate_tensor... |
def find_strictly_increasing_elements(nums):
result = []
for i in range(len(nums)):
x = nums[i]
all_greater = True
for j in range(i + 1, len(nums)):
if nums[j] <= x:
all_greater = False
break
if all_greater:
result.append(x)... | simplelr_Filter | [
{
"content": "Question:\nYou can cut off the queue (Tail) of a list at any point to reduce its size and get rid of the last elements. In the case of an ordered list, reducing the size of the list implies losing the order completely, because the list can contain identical consecutive elements that would be in th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4501,
"level": 1,
"question": "You can cut off the queue (Tail) of a list at any point to reduce its size and get rid of the last elements. In the case of an ordered list, reducing the size of the list implies losing the order completely, because the list can contain identical conse... |
from collections import defaultdict, deque
def next_greater_element(nums1, nums2):
stack = []
next_arr = [-1] * len(nums1)
# Compute the next greater element for each position in nums1
for i in range(len(nums1)-1, -1, -1):
while stack and nums1[stack[-1]] <= nums1[i]:
stack.pop... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two non-negative integer arrays `nums1` and `nums2`, where `nums2` is a subset of `nums1`. For each element in `nums2`, find the next greater element in `nums1`. The next greater element of an element `x` in `nums1` is the first greater element to its right in `nums1`. If ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4502,
"level": 1,
"question": "You are given two non-negative integer arrays `nums1` and `nums2`, where `nums2` is a subset of `nums1`. For each element in `nums2`, find the next greater element in `nums1`. The next greater element of an element `x` in `nums1` is the first greater e... |
def combine_and_sort_lists(list1, list2):
# Convert both lists to sets to eliminate duplicates within each list
set1 = set(list1)
set2 = set(list2)
# Combine the sets to get all unique elements
combined_set = set1.union(set2)
# Convert the combined set to a sorted list
return sorted(combined... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in two lists of integers and returns a new list that combines the elements of both lists. If an element appears in both lists, it should appear only once in the resulting list. The resulting list should be sorted in ascending order.\nAnswer:\nLet's think ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4503,
"level": 1,
"question": "Create a function that takes in two lists of integers and returns a new list that combines the elements of both lists. If an element appears in both lists, it should appear only once in the resulting list. The resulting list should be sorted in ascendi... |
def evaluate_model():
import numpy as np
from sklearn.model_selection import validation_curve, learning_curve, ValidationCurveDisplay, LearningCurveDisplay
from sklearn.datasets import load_iris
from sklearn.svm import SVC
from sklearn.utils import shuffle
import matplotlib.pyplot as plt
... | simplelr_Docs | [
{
"content": "Question:\n### Question\n\nYou are given a dataset and tasked with evaluating a machine learning model. Specifically, you need to determine if the model is underfitting, overfitting, or generalizing well. To achieve this, you will generate and analyze validation and learning curves using scikit-le... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4504,
"level": 1,
"question": "### Question\n\nYou are given a dataset and tasked with evaluating a machine learning model. Specifically, you need to determine if the model is underfitting, overfitting, or generalizing well. To achieve this, you will generate and analyze validation ... |
def count_flips_to_convert(a: int, b: int) -> int:
return (a ^ b).bit_count() | simplelr_Data_Structure | [
{
"content": "Question:\n### Bit Flip Transformation\n\n**Scenario**:\nYou are working on a software project that involves optimizing data transformation. Part of the task requires you to determine how many bit changes are needed to transform one data representation into another. \n\n**Task**:\nWrite a function... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4505,
"level": 1,
"question": "### Bit Flip Transformation\n\n**Scenario**:\nYou are working on a software project that involves optimizing data transformation. Part of the task requires you to determine how many bit changes are needed to transform one data representation into anoth... |
def calculate_inventory_value(items: list) -> float:
total = 0.0
for item in items:
quantity = item['quantity']
price = item['price_per_unit']
# Check if quantity is a non-negative integer
if isinstance(quantity, int):
is_quantity_valid = quantity >= 0
... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario:\nAs a software developer, you are tasked with building an inventory management system for a warehouse. A crucial feature of this system is to compute the total value of all items in the inventory based on their individual quantity and price.\n\n### Problem Statement:\nWrit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4506,
"level": 1,
"question": "### Scenario:\nAs a software developer, you are tasked with building an inventory management system for a warehouse. A crucial feature of this system is to compute the total value of all items in the inventory based on their individual quantity and pri... |
import itertools
from typing import List, Tuple
def generate_combinations(list1: List[int], list2: List[int]) -> List[Tuple[int, int, int]]:
triplets = []
seen = set()
for a in list1:
for x, y in itertools.combinations(list2, 2):
if x == y:
continue
if a == x... | simplelr_Docs | [
{
"content": "Question:\n**Objective**: Demonstrate your ability to use the `itertools` module to create complex iterators and process sequences efficiently.\n\n**Problem Statement**:\n\nYou are given two lists of integers, `list1` and `list2`, of potentially different lengths. Write a Python function `generate... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4507,
"level": 1,
"question": "**Objective**: Demonstrate your ability to use the `itertools` module to create complex iterators and process sequences efficiently.\n\n**Problem Statement**:\n\nYou are given two lists of integers, `list1` and `list2`, of potentially different lengths... |
def is_palindrome(s):
s = ''.join([char for char in s if char.strip() != ''])
s = s.lower()
return s == s[::-1] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to check if a given string is a palindrome. The function should ignore whitespace and capitalization. For example, \"A man a plan a canal Panama\" is a palindrome, while \"Hello\" is not.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4508,
"level": 1,
"question": "Write a Python function to check if a given string is a palindrome. The function should ignore whitespace and capitalization. For example, \"A man a plan a canal Panama\" is a palindrome, while \"Hello\" is not.",
"split": "train"
} |
def search_books(books: list, criteria: dict) -> list:
"""
Searches for books in the library database based on given criteria and returns a list of books that match.
Args:
books (list): A list of dictionaries where each dictionary contains book information.
Each dictionary has... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n**Scenario**: You have been hired to develop a small utility to manage a database of library books. Each book has a title, author, publication year, genre, and availability status. Your task is to implement a search function that allows users to query t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4509,
"level": 1,
"question": "### Coding Assessment Question\n\n**Scenario**: You have been hired to develop a small utility to manage a database of library books. Each book has a title, author, publication year, genre, and availability status. Your task is to implement a search fu... |
def is_all_nested_lists(lst):
if not isinstance(lst, list):
return False
for element in lst:
if not isinstance(element, list):
return False
if not is_all_nested_lists(element):
return False
return True | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that checks whether all elements in a provided list are also lists, including nested ones. The function should be named `is_all_nested_lists`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4510,
"level": 1,
"question": "Create a Python function that checks whether all elements in a provided list are also lists, including nested ones. The function should be named `is_all_nested_lists`.",
"split": "train"
} |
from datetime import datetime
def find_day_of_week(date_str):
date_obj = datetime.strptime(date_str, '%d/%m/%Y')
return date_obj.strftime('%A')
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a string representing a date in the format 'DD/MM/YYYY' and returns the day of the week for that date.\n\n```\nFor example:\n\nfind_day_of_week('01/01/2021')\n=> 'Friday'\n\nfind_day_of_week('24/12/2022')\n=> 'Saturday'\n```\nAnswer:\nLet's think step by step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4511,
"level": 1,
"question": "Write a function that takes a string representing a date in the format 'DD/MM/YYYY' and returns the day of the week for that date.\n\n```\nFor example:\n\nfind_day_of_week('01/01/2021')\n=> 'Friday'\n\nfind_day_of_week('24/12/2022')\n=> 'Saturday'\n```... |
def split_even_odd(lst):
evens = []
odds = []
for num in lst:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return [evens, odds] | simplelr_Apps | [
{
"content": "Question:\nCreate a function that accepts a list of integers and returns a new list with two elements: the first element is a sublist of all the even numbers in the original list, and the second element is a sublist of all the odd numbers in the original list. Both sublists should be ordered in th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4512,
"level": 1,
"question": "Create a function that accepts a list of integers and returns a new list with two elements: the first element is a sublist of all the even numbers in the original list, and the second element is a sublist of all the odd numbers in the original list. Bo... |
def are_anagrams(s1, s2):
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two strings as input and returns true if they are anagrams, and false otherwise. An anagram is a word or phrase made by rearranging the letters of another, such as \"cinema\" and \"iceman\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4513,
"level": 1,
"question": "Create a function that takes two strings as input and returns true if they are anagrams, and false otherwise. An anagram is a word or phrase made by rearranging the letters of another, such as \"cinema\" and \"iceman\".",
"split": "train"
} |
def replace_with_zero(lst, threshold):
return [0 if x > threshold else x for x in lst] | simplelr_Filter | [
{
"content": "Question:\nI want to create a Python function to manipulate a list and return a modified version of it. The function should take a list of integers and replace all elements that are greater than a given threshold value with zero. How can I implement this function?\nAnswer:\nLet's think step by ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4514,
"level": 1,
"question": "I want to create a Python function to manipulate a list and return a modified version of it. The function should take a list of integers and replace all elements that are greater than a given threshold value with zero. How can I implement this function... |
import re
def normalize_text(text):
"""Normalize the input text following the specified steps."""
# 1. Convert to lowercase
text = text.lower()
# 2. Replace multiple spaces with a single space
text = re.sub(r'\s+', ' ', text)
# 3. Remove leading and trailing spaces
text = text.strip()
... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with developing a text normalization function for a more consistent and cleaner text processing pipeline. The function should handle a given string input by performing specific normalization steps.\n\nWrite a function named `normalize_text` that adheres to the following s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4515,
"level": 1,
"question": "You are tasked with developing a text normalization function for a more consistent and cleaner text processing pipeline. The function should handle a given string input by performing specific normalization steps.\n\nWrite a function named `normalize_te... |
def delete_reoccurring_characters(s: str) -> str:
seen = set()
result = []
for char in s:
if char not in seen:
result.append(char)
seen.add(char)
return ''.join(result) | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a string `s`. Your task is to write a function `delete_reoccurring_characters(s)` that removes all duplicate characters from the string while preserving the order of their first appearance.\n\n#### Function Signature\n```python\ndef delete_reoccurring_characters(s: str) ->... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4516,
"level": 1,
"question": "You are given a string `s`. Your task is to write a function `delete_reoccurring_characters(s)` that removes all duplicate characters from the string while preserving the order of their first appearance.\n\n#### Function Signature\n```python\ndef delet... |
from typing import List
def kth_smallest_with_duplicates(array: List[int], k: int) -> int:
"""
Finds the k-th smallest unique element in the given list.
:param array: The list of integers, which may contain duplicates.
:param k: The k-th position (1-indexed) to find the smallest unique element.
:r... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nSearching for the k-th smallest element in an unordered list is a common problem that has multiple solutions, including deterministic and randomized algorithms. However, certain special lists, such as those with duplicate elements or specific patterns, can benefit from tail... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4517,
"level": 1,
"question": "### Context\nSearching for the k-th smallest element in an unordered list is a common problem that has multiple solutions, including deterministic and randomized algorithms. However, certain special lists, such as those with duplicate elements or speci... |
def to_uppercase(s):
result = []
for c in s:
ascii_val = ord(c)
if 97 <= ascii_val <= 122:
converted = ascii_val - 32
result.append(chr(converted))
else:
result.append(c)
return ''.join(result) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert all lowercase letters in a string to uppercase without using any built-in string methods like upper(), islower(), etc.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4518,
"level": 1,
"question": "Write a python function to convert all lowercase letters in a string to uppercase without using any built-in string methods like upper(), islower(), etc.",
"split": "train"
} |
def smallest_multiple_of_2_and_n(n):
if n % 2 == 0:
return n
else:
return 2 * n | simplelr_Leetcode | [
{
"content": "Question:\nGiven a positive integer `n`, return _the smallest positive integer that is a multiple of both 2 and `n`_. The solution should work efficiently even for larger values of `n`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4519,
"level": 1,
"question": "Given a positive integer `n`, return _the smallest positive integer that is a multiple of both 2 and `n`_. The solution should work efficiently even for larger values of `n`.",
"split": "train"
} |
def filter_greater_than_threshold(numbers, threshold):
return [num for num in numbers if num <= threshold] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to filter out any values in a list that are greater than a specified threshold. The function should take in a list of numbers and a threshold value, and return a new list without the values exceeding the threshold.\nAnswer:\nLet's think step by step.\n",
"rol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4520,
"level": 1,
"question": "Write a Python function to filter out any values in a list that are greater than a specified threshold. The function should take in a list of numbers and a threshold value, and return a new list without the values exceeding the threshold.",
"split": ... |
import linecache
def extract_significant_lines(filename: str, keyword: str) -> dict:
result = {}
line_number = 1
while True:
line = linecache.getline(filename, line_number)
if not line:
break
if keyword.lower() in line.lower():
result[line_number] = line
... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nTo assess your ability to work with file I/O, caching mechanisms, and Python's `linecache` module.\n\n#### Problem Statement:\n\nYou are required to implement a Python function `extract_significant_lines`, which reads lines from a given source file and identifies \"sign... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4521,
"level": 1,
"question": "#### Objective:\nTo assess your ability to work with file I/O, caching mechanisms, and Python's `linecache` module.\n\n#### Problem Statement:\n\nYou are required to implement a Python function `extract_significant_lines`, which reads lines from a give... |
def has_duplicate_characters(s):
return len(set(s)) != len(s) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if a given string contains any duplicate characters. The string will only contain lowercase alphabetic characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4522,
"level": 1,
"question": "Create a function that checks if a given string contains any duplicate characters. The string will only contain lowercase alphabetic characters.",
"split": "train"
} |
def remove_duplicates(input_list):
seen = set()
unique_list = []
for item in input_list:
if item not in seen:
seen.add(item)
unique_list.append(item)
return unique_list | simplelr_Filter | [
{
"content": "Question:\nCan you explain how to implement a function to remove duplicates from a list in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4523,
"level": 1,
"question": "Can you explain how to implement a function to remove duplicates from a list in Python?",
"split": "train"
} |
def longest_repeated_substring(s):
n = len(s)
max_len = n // 2
for l in range(max_len, 0, -1):
for i in range(n - l + 1):
substr = s[i:i+l]
if substr in s[i + l:]:
return substr
return '' | simplelr_Evol | [
{
"content": "Question:\nDefine a function that takes a string as input and returns the longest substring that appears at least twice in the given string. If there are multiple substrings of the same length that appear more than once, return the one that occurs first. Consider only non-overlapping substrings fo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4524,
"level": 1,
"question": "Define a function that takes a string as input and returns the longest substring that appears at least twice in the given string. If there are multiple substrings of the same length that appear more than once, return the one that occurs first. Consider... |
def has_pair_with_sum(A, B, target):
set_B = set(B)
for a in A:
if (target - a) in set_B:
return True
return False | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two lists, list A and list B, and a target sum. The function should return true if there exists any pair (a, b) such that a belongs to list A, b belongs to list B, and a + b equals the target sum. Otherwise, return false.\nAnswer:\nLet's think step by step.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4525,
"level": 1,
"question": "Create a function that takes two lists, list A and list B, and a target sum. The function should return true if there exists any pair (a, b) such that a belongs to list A, b belongs to list B, and a + b equals the target sum. Otherwise, return false.",... |
def find_insert_position(timestamps: list, new_timestamp: int) -> int:
low = 0
high = len(timestamps)
while low < high:
mid = (low + high) // 2
if timestamps[mid] >= new_timestamp:
high = mid
else:
low = mid + 1
return low | simplelr_Data_Structure | [
{
"content": "Question:\n#### Context\nYou are a software developer working on an application that requires efficient insertion in a sorted list of events based on their timestamps. Inserting events in the correct position while maintaining order is crucial for subsequent operations, such as event processing an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4526,
"level": 1,
"question": "#### Context\nYou are a software developer working on an application that requires efficient insertion in a sorted list of events based on their timestamps. Inserting events in the correct position while maintaining order is crucial for subsequent oper... |
import requests
def is_url_reachable(url):
try:
response = requests.get(url, timeout=5)
return (True, response.status_code)
except requests.exceptions.RequestException:
return (False, None) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that checks if a given URL is reachable and returns a tuple containing a boolean indicating reachability and the HTTP status code. If the URL is not reachable, the function should return `False` and `None` for the status code. Use the `requests` library for makin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4527,
"level": 1,
"question": "Write a Python function that checks if a given URL is reachable and returns a tuple containing a boolean indicating reachability and the HTTP status code. If the URL is not reachable, the function should return `False` and `None` for the status code. U... |
def calculate_total(scores, bonus, threshold):
total_score = sum(scores)
if len(scores) > threshold:
total_score += bonus
return total_score
| simplelr_Taco | [
{
"content": "Question:\nA robotics competition is held annually where teams build robots to complete a series of tasks. Each task has a different level of difficulty and earns a corresponding score. \n\nGiven the following parameters:\n- An array of integers where each integer represents the score for completi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4528,
"level": 1,
"question": "A robotics competition is held annually where teams build robots to complete a series of tasks. Each task has a different level of difficulty and earns a corresponding score. \n\nGiven the following parameters:\n- An array of integers where each intege... |
def count_paths(n, m, blocked_cells):
blocked = set(blocked_cells)
# Check if start or end is blocked
if (1, 1) in blocked or (n, m) in blocked:
return 0
# Initialize DP table
dp = [[0] * (m + 1) for _ in range(n + 1)]
dp[1][1] = 1 # Starting point
for i in range(1, n... | simplelr_Taco | [
{
"content": "Question:\n# Task\n\nYou are given a rectangular grid of size `n x m`. Starting from the top left corner of the grid, you have to move to the bottom right corner. You can only move either right or down at any point in time.\n\nHowever, there are some blocked cells in the grid where you cannot step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4529,
"level": 1,
"question": "# Task\n\nYou are given a rectangular grid of size `n x m`. Starting from the top left corner of the grid, you have to move to the bottom right corner. You can only move either right or down at any point in time.\n\nHowever, there are some blocked cell... |
from typing import List
def merge_and_reverse(arr1: List[int], arr2: List[int]) -> List[int]:
merged = arr1 + arr2
return merged[::-1] | simplelr_Package | [
{
"content": "Question:\nCreate a function `merge_and_reverse(arr1, arr2)` that takes two lists of integers, merges them into one list, and returns the merged list in reversed order. The task involves understanding how to work with list operations, which includes merging lists and reversing them.\n\nHere are th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4530,
"level": 1,
"question": "Create a function `merge_and_reverse(arr1, arr2)` that takes two lists of integers, merges them into one list, and returns the merged list in reversed order. The task involves understanding how to work with list operations, which includes merging lists... |
def two_sum(nums, target):
left = 0
right = len(nums) - 1
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1
else:
right -= 1
return [] | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` and an integer `target`. The array `nums` is sorted in non-decreasing order and contains unique elements. Write a function that returns the indices of the two numbers in `nums` such that their sum is equal to `target`. Return the indices as a list o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4531,
"level": 1,
"question": "You are given an integer array `nums` and an integer `target`. The array `nums` is sorted in non-decreasing order and contains unique elements. Write a function that returns the indices of the two numbers in `nums` such that their sum is equal to `targ... |
from typing import List
def longest_sequence_of_ones(binary_array: List[int]) -> int:
"""
Determine the longest sequence of ones in a binary array.
Args:
binary_array (list): A list of binary integers (0s and 1s).
Returns:
int: The length of the longest sequence of ones.
"""
l... | simplelr_Filter | [
{
"content": "Question:\nCreate an algorithm to determine the longest sequence of ones in a binary array. This can be done in linear time by scanning the array from left to right. \n\nHere is some sample Python code to get you started:\n\n```python\ndef longest_sequence_of_ones(binary_array):\n \"\"\"\n D... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4532,
"level": 1,
"question": "Create an algorithm to determine the longest sequence of ones in a binary array. This can be done in linear time by scanning the array from left to right. \n\nHere is some sample Python code to get you started:\n\n```python\ndef longest_sequence_of_one... |
def encode_string(s):
if not s:
return ""
current_char = s[0]
count = 1
result = []
for char in s[1:]:
if char == current_char:
count += 1
else:
if count == 1:
result.append(current_char)
else:
result.append(... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` that consists of lowercase English letters. You need to encode this string by replacing each group of consecutive identical letters with the letter followed by the count of its repetition. If the count of a letter is `1`, it should be represented as just the l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4533,
"level": 1,
"question": "You are given a string `s` that consists of lowercase English letters. You need to encode this string by replacing each group of consecutive identical letters with the letter followed by the count of its repetition. If the count of a letter is `1`, it ... |
def generate_subarrays(array):
result = []
n = len(array)
for i in range(n):
for j in range(i, n):
subarray = array[i:j+1]
result.append(subarray)
return result | simplelr_Filter | [
{
"content": "Question:\nI'm trying to create a Python function that can generate all possible subarrays of a given array. A subarray is a contiguous part of an array. For example, for the array `[1, 2, 3]`, the subarrays are `[1]`, `[2]`, `[3]`, `[1, 2]`, `[2, 3]`, and `[1, 2, 3]`. How can I achieve this?\nAns... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4534,
"level": 1,
"question": "I'm trying to create a Python function that can generate all possible subarrays of a given array. A subarray is a contiguous part of an array. For example, for the array `[1, 2, 3]`, the subarrays are `[1]`, `[2]`, `[3]`, `[1, 2]`, `[2, 3]`, and `[1, 2... |
def unique_factors(n):
if n == 1:
return []
factors = set()
factors.add(1)
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
factors.add(i)
factors.add(n // i)
factors.discard(n)
return sorted(factors) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find and return a list of all unique factors of a given positive integer, excluding the number itself. Here, a factor is a number that divides the given number evenly (remainder is zero).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4535,
"level": 1,
"question": "Write a python function to find and return a list of all unique factors of a given positive integer, excluding the number itself. Here, a factor is a number that divides the given number evenly (remainder is zero).",
"split": "train"
} |
from typing import List, Dict, Union
def sort_students(students: List[Dict[str, Union[int, str]]]) -> List[Dict[str, Union[int, str]]]:
"""
Sorts a list of student dictionaries by score, age, and name.
Args:
students (List[Dict[str, Union[int, str]]]): The list of student records to be sorted.
... | simplelr_Algorithm | [
{
"content": "Question:\n### Sort List of Dictionaries by Multiple Keys\n\nYou need to write a function that sorts a list of dictionaries according to multiple specified keys. Each dictionary in the list represents a student's record with their `name`, `age`, and `score`. The sorting should prioritize the `scor... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4536,
"level": 1,
"question": "### Sort List of Dictionaries by Multiple Keys\n\nYou need to write a function that sorts a list of dictionaries according to multiple specified keys. Each dictionary in the list represents a student's record with their `name`, `age`, and `score`. The ... |
def sort_dict_by_value_and_key(d):
return dict(sorted(d.items(), key=lambda x: (-x[1], x[0]))) | simplelr_Filter | [
{
"content": "Question:\nYou are given a Python dictionary with string keys and integer values. Write a function to sort the dictionary based on values in descending order. If two values are the same, sort by key in ascending order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4537,
"level": 1,
"question": "You are given a Python dictionary with string keys and integer values. Write a function to sort the dictionary based on values in descending order. If two values are the same, sort by key in ascending order.",
"split": "train"
} |
def manhattan_distance(point1, point2):
"""
Calculate the Manhattan distance between two points in a 2D space.
Parameters:
point1 (tuple or list): The first point with coordinates (x1, y1).
point2 (tuple or list): The second point with coordinates (x2, y2).
Returns:
int or float: T... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code snippet that demonstrates how to calculate the Manhattan distance between two points in a 2D space?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4538,
"level": 1,
"question": "Can you provide a Python code snippet that demonstrates how to calculate the Manhattan distance between two points in a 2D space?",
"split": "train"
} |
def digit_to_word(n):
digit_words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
return ' '.join(digit_words[ord(c) - ord('0')] for c in str(abs(n))) | simplelr_Filter | [
{
"content": "Question:\nI'm looking for a solution to the following problem:\n\nWrite a function that takes an integer as input and returns a string representation of that integer with each digit replaced by its corresponding word representation. We will use the following word representations for digits: 0='ze... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4539,
"level": 1,
"question": "I'm looking for a solution to the following problem:\n\nWrite a function that takes an integer as input and returns a string representation of that integer with each digit replaced by its corresponding word representation. We will use the following wor... |
from collections import defaultdict
import bisect
def smallest_subsequence(s):
if not s:
return ""
# Precompute the indices for each character and their last occurrence
char_indices = defaultdict(list)
for idx, char in enumerate(s):
char_indices[char].append(idx)
last_occu... | simplelr_Taco | [
{
"content": "Question:\nGiven a string `str` representing a sequence of lowercase letters, the task is to determine the smallest subsequence that contains all the unique characters in `str`. This subsequence must maintain the order of the first occurrence of each character.\n\nWrite a function `smallest_subseq... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4540,
"level": 1,
"question": "Given a string `str` representing a sequence of lowercase letters, the task is to determine the smallest subsequence that contains all the unique characters in `str`. This subsequence must maintain the order of the first occurrence of each character.\n... |
def min_cost_unique_paths(grid):
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
if n == 0:
return 0
# Initialize DP table
dp = [[0 for _ in range(n)] for _ in range(m)]
dp[0][0] = grid[0][0]
# Fill the first row
for j in range(1, n):
dp[0][j] = d... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge: Sum of Unique Paths in a Grid\n\n#### Problem Statement\n\nYou are given a grid of size m x n. Each cell in the grid contains a non-negative integer representing the cost of stepping into that cell. Your task is to find the minimum sum of the unique paths that lead... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4541,
"level": 1,
"question": "### Coding Challenge: Sum of Unique Paths in a Grid\n\n#### Problem Statement\n\nYou are given a grid of size m x n. Each cell in the grid contains a non-negative integer representing the cost of stepping into that cell. Your task is to find the minimu... |
from typing import List
def longest_increasing_subsequence(nums: List[int]) -> int:
n = len(nums)
dp = [1] * n
for i in range(n):
for j in range(i):
if nums[j] < nums[i]:
if dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
return max(dp) if n > 0 else 0 | simplelr_Apps | [
{
"content": "Question:\nImplement a function to find the longest increasing subsequence (LIS) in a given array of integers. The function should return the length of the LIS. An increasing subsequence is a sequence of elements arranged in ascending order and it does not need to be contiguous in the array, but i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4542,
"level": 1,
"question": "Implement a function to find the longest increasing subsequence (LIS) in a given array of integers. The function should return the length of the LIS. An increasing subsequence is a sequence of elements arranged in ascending order and it does not need t... |
def filter_out_odd_numbers(numbers):
return [num for num in numbers if num % 2 == 0] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that filters out odd numbers from a list of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4543,
"level": 1,
"question": "Create a function that filters out odd numbers from a list of integers.",
"split": "train"
} |
from typing import List
def trap_water(height: List[int]) -> int:
if not height:
return 0
n = len(height)
if n == 0:
return 0
left_max = [0] * n
left_max[0] = height[0]
for i in range(1, n):
left_max[i] = max(left_max[i-1], height[i])
right_max = [0] * n
... | simplelr_Taco | [
{
"content": "Question:\nGiven a list of non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.\n\nWrite a function `trap_water(height: List[int]) -> int` that takes in a list of integers and returns the amount of trapped water.\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4544,
"level": 1,
"question": "Given a list of non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.\n\nWrite a function `trap_water(height: List[int]) -> int` that takes in a list of integers and retu... |
def text_editor(operations):
document = []
output = []
for op in operations:
parts = op.split()
if parts[0] == "INSERT":
document.append(parts[1])
elif parts[0] == "DELETE":
if document:
document.pop()
elif parts[0] == "PRINTKth":
... | simplelr_Leetcode | [
{
"content": "Question:\nImplement a text editor that can perform the following operations efficiently:\n\n1. **Insert** a character at the end of the document.\n2. **Delete** the last character of the document.\n3. **PrintKth** the k-th character of the document (for a 1-indexed query).\n\nYou should support t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4545,
"level": 1,
"question": "Implement a text editor that can perform the following operations efficiently:\n\n1. **Insert** a character at the end of the document.\n2. **Delete** the last character of the document.\n3. **PrintKth** the k-th character of the document (for a 1-inde... |
from typing import List
def find_min_sum_subarray(nums: List[int], k: int) -> List[int]:
current_sum = sum(nums[:k])
min_sum = current_sum
start = 0
n = len(nums)
for i in range(k, n):
current_sum = current_sum - nums[i - k] + nums[i]
if current_sum < min_sum:
min_s... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given an integer array `nums` and an integer `k`. Find a subarray of `nums` of length `k` that has the minimum sum. If there is a tie, return the first such subarray. \n\nWrite a function:\n```python\ndef find_min_sum_subarray(nums: List[int], k: int) -> List[int]:\n pass\n``... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4546,
"level": 1,
"question": "You are given an integer array `nums` and an integer `k`. Find a subarray of `nums` of length `k` that has the minimum sum. If there is a tie, return the first such subarray. \n\nWrite a function:\n```python\ndef find_min_sum_subarray(nums: List[int], ... |
from itertools import accumulate
def extract_sub_paths(path, separator='/'):
"""
Extract sub-paths of a given path separated by separator.
Args:
path (str): The path to be processed.
separator (str): The separator used in the path. Defaults to '/'.
Returns:
list: A list of sub... | simplelr_Filter | [
{
"content": "Question:\nI have this Python function to extract sub-path of a given path:\n```python\ndef extract_sub_paths(path, separator='/'):\n \"\"\"\n Extract sub-paths of a given path separated by separator.\n\n Args:\n path (str): The path to be processed.\n separator (str): The s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4547,
"level": 1,
"question": "I have this Python function to extract sub-path of a given path:\n```python\ndef extract_sub_paths(path, separator='/'):\n \"\"\"\n Extract sub-paths of a given path separated by separator.\n\n Args:\n path (str): The path to be process... |
def is_palindrome(s: str) -> bool:
left = 0
right = len(s) - 1
while left < right:
# Move left pointer to the next alphanumeric character
while left < right and not s[left].isalnum():
left += 1
# Move right pointer to the previous alphanumeric character
while... | simplelr_Algorithm | [
{
"content": "Question:\n#### Question:\n\nIn this task, you are required to implement a function that determines if a given string is a palindrome. A palindrome is a string that reads the same backwards as forwards, ignoring non-alphanumeric characters and case sensitivity. This exercise is intended to evaluat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4548,
"level": 1,
"question": "#### Question:\n\nIn this task, you are required to implement a function that determines if a given string is a palindrome. A palindrome is a string that reads the same backwards as forwards, ignoring non-alphanumeric characters and case sensitivity. T... |
def sum_positive_negative(numbers):
positive_sum = 0
negative_sum = 0
for num in numbers:
if num > 0:
positive_sum += num
elif num < 0:
negative_sum += num
return {'positive_sum': positive_sum, 'negative_sum': negative_sum} | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns the sum of all the positive numbers and the sum of all the negative numbers in a dictionary. The function should ignore zeros and should give the sums for positive and negative numbers separately. \n\nFor example, given the list... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4549,
"level": 1,
"question": "Write a function that takes a list of integers and returns the sum of all the positive numbers and the sum of all the negative numbers in a dictionary. The function should ignore zeros and should give the sums for positive and negative numbers separate... |
def max_profit(prices):
max_profit = 0
for i in range(len(prices) - 1):
if prices[i] < prices[i + 1]:
max_profit += prices[i + 1] - prices[i]
return max_profit | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the maximum profit we can achieve from selling and buying a stock multiple times.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4550,
"level": 1,
"question": "Write a function to find the maximum profit we can achieve from selling and buying a stock multiple times.",
"split": "train"
} |
def scrabble_word_value(word):
# Define the letter values
letter_values = {}
# 1 point letters
for letter in ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'S', 'T', 'R']:
letter_values[letter] = 1
# 2 points
for letter in ['D', 'G']:
letter_values[letter] = 2
# 3 points
for letter ... | simplelr_Apps | [
{
"content": "Question:\n## Task:\nWrite a function `scrabble_word_value` which accepts a word and calculates the Scrabble word score for that word based on the standard Scrabble letter values.\n\n### The letter values are:\nA, E, I, O, U, L, N, S, T, R: 1 point \nD, G: 2 points \nB, C, M, P: 3 points \nF, H... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4551,
"level": 1,
"question": "## Task:\nWrite a function `scrabble_word_value` which accepts a word and calculates the Scrabble word score for that word based on the standard Scrabble letter values.\n\n### The letter values are:\nA, E, I, O, U, L, N, S, T, R: 1 point \nD, G: 2 poi... |
def calculate_expression(a, b, c, d):
return a * b + c - d | simplelr_Filter | [
{
"content": "Question:\nA student is given a sequence of four numbers: a, b, c, and d. The student needs to calculate the value of the expression: a × b + c - d. The numbers in the sequence may be either positive or negative. Create a Python code to calculate the expression. Please use function-based programmi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4552,
"level": 1,
"question": "A student is given a sequence of four numbers: a, b, c, and d. The student needs to calculate the value of the expression: a × b + c - d. The numbers in the sequence may be either positive or negative. Create a Python code to calculate the expression. ... |
def evaluate_expression(expression: str, local_vars: dict, global_vars: dict) -> any:
try:
local_copy = local_vars.copy()
global_copy = global_vars.copy()
return eval(expression, global_copy, local_copy)
except (NameError, UnboundLocalError):
return "Error: Undefined variable"
... | simplelr_Docs | [
{
"content": "Question:\n**Understanding Scope and Exception Handling in Python**\n\nImplement a Python function called `evaluate_expression` that takes three arguments: \n- `expression`: a string containing a Python expression to be evaluated,\n- `local_vars`: a dictionary representing local variables to be us... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4553,
"level": 1,
"question": "**Understanding Scope and Exception Handling in Python**\n\nImplement a Python function called `evaluate_expression` that takes three arguments: \n- `expression`: a string containing a Python expression to be evaluated,\n- `local_vars`: a dictionary re... |
def remove_adjacent_pairs(s):
stack = []
for char in s:
if stack and stack[-1] == char:
stack.pop()
else:
stack.append(char)
return ''.join(stack) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase letters. You have to perform the following operation until you cannot anymore: Find the leftmost pair of adjacent letters that are the same and remove them from the string. After removing a pair, concatenate the remaining parts of the s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4554,
"level": 1,
"question": "You are given a string `s` consisting of lowercase letters. You have to perform the following operation until you cannot anymore: Find the leftmost pair of adjacent letters that are the same and remove them from the string. After removing a pair, conca... |
def find_first_and_second_max(arr):
unique = list(set(arr))
if len(unique) < 2:
if len(unique) == 0:
return (None, None)
else:
return (unique[0], None)
else:
sorted_unique = sorted(unique, reverse=True)
return (sorted_unique[0], sorted_unique[1]) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the first maximum and the second maximum number in an array. If the array has less than two unique elements, return `None` for the missing values.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4555,
"level": 1,
"question": "Write a python function to find the first maximum and the second maximum number in an array. If the array has less than two unique elements, return `None` for the missing values.",
"split": "train"
} |
def can_jump(nums):
max_reach = 0
current_end = 0
n = len(nums) - 1
for i in range(len(nums)):
if i > current_end:
return False
max_reach = max(max_reach, i + nums[i])
if max_reach >= n:
return True
if i == current_end:
current_end = ma... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums`, where each element represents the maximum number of steps you can jump forward from that position, determine if you can reach the last index. Assume that you are always initially positioned at the first index.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4556,
"level": 1,
"question": "Given an array of integers `nums`, where each element represents the maximum number of steps you can jump forward from that position, determine if you can reach the last index. Assume that you are always initially positioned at the first index.",
"sp... |
def evaluate_expression(expression: str) -> int:
tokens = expression.split()
result = int(tokens[0])
i = 1
while i < len(tokens):
operator = tokens[i]
operand = int(tokens[i + 1])
if operator == '+':
result += operand
elif operator == '*':
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nDesign a simplified compiler that can parse and evaluate mathematical expressions containing addition and multiplication operators. The input expressions will be given in standard infix notation with integer operands. No parentheses are allowed.\n\n### Requirement... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4557,
"level": 1,
"question": "### Problem Statement\nDesign a simplified compiler that can parse and evaluate mathematical expressions containing addition and multiplication operators. The input expressions will be given in standard infix notation with integer operands. No parenthe... |
def add_binary(a, b):
max_len = max(len(a), len(b))
a_padded = a.zfill(max_len)
b_padded = b.zfill(max_len)
carry = 0
result = []
for i in range(max_len - 1, -1, -1):
a_bit = int(a_padded[i])
b_bit = int(b_padded[i])
total = a_bit + b_bit + carry
result_bit =... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the sum of two binary strings and returns the result as a binary string. You can assume that the input strings are non-empty and contain only the characters '0' and '1'. The function should handle cases where the input strings might have different lengt... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4558,
"level": 1,
"question": "Create a function that calculates the sum of two binary strings and returns the result as a binary string. You can assume that the input strings are non-empty and contain only the characters '0' and '1'. The function should handle cases where the input... |
def sum_of_squares(numbers):
return sum(n ** 2 for n in numbers)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function called `sum_of_squares` that takes a list of integers and returns the sum of the squares of each integer in the list. For example, given the list `[1, 2, 3, 4]`, the function should return `1^2 + 2^2 + 3^2 + 4^2 = 30`.\nAnswer:\nLet's think step by step.\n",
"role":... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4559,
"level": 1,
"question": "Write a function called `sum_of_squares` that takes a list of integers and returns the sum of the squares of each integer in the list. For example, given the list `[1, 2, 3, 4]`, the function should return `1^2 + 2^2 + 3^2 + 4^2 = 30`.",
"split": "tr... |
from typing import List
def subarray_sum_equals_target(n: int, k: int, array: List[int], target: int) -> bool:
current_sum = sum(array[:k])
if current_sum == target:
return True
for i in range(k, n):
current_sum = current_sum - array[i - k] + array[i]
if current_sum == target:
... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a list of integers $$$a_1, a_2,…, a_n$$$ and an integer $$$k$$$. You need to determine if there exists a subarray of length exactly $$$k$$$ such that the sum of its elements is equal to a given integer $$$target$$$.\n\nWrite a function that takes two integers $$$n$$$ and $... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4560,
"level": 1,
"question": "You are given a list of integers $$$a_1, a_2,…, a_n$$$ and an integer $$$k$$$. You need to determine if there exists a subarray of length exactly $$$k$$$ such that the sum of its elements is equal to a given integer $$$target$$$.\n\nWrite a function th... |
def compress_string(input_string: str) -> str:
if len(input_string) == 0:
return ""
current_char = input_string[0]
count = 1
compressed = ""
for char in input_string[1:]:
if char == current_char:
count += 1
else:
compressed += current_char + ... | simplelr_Evol | [
{
"content": "Question:\nWrite a function `compress_string(input_string)` that takes a non-empty string of lowercase letters and returns its compressed version using a form of run-length encoding. In the compressed version, each group of consecutive identical letters in the string is replaced by a single instan... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4561,
"level": 1,
"question": "Write a function `compress_string(input_string)` that takes a non-empty string of lowercase letters and returns its compressed version using a form of run-length encoding. In the compressed version, each group of consecutive identical letters in the st... |
def wordWrap(text, limit):
words = text.split()
if not words:
return ''
max_word_length = max(len(word) for word in words)
if max_word_length > limit:
raise ValueError("A word is longer than the specified limit.")
lines = []
current_line = ''
for word in words:
i... | simplelr_Apps | [
{
"content": "Question:\nWrite a function `wordWrap` that takes a string `text` and an integer `limit` as its parameters. The function should return a new string where the original text is broken into lines of a maximum length specified by `limit`. Words should not be split between lines; if a word would exceed... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4562,
"level": 1,
"question": "Write a function `wordWrap` that takes a string `text` and an integer `limit` as its parameters. The function should return a new string where the original text is broken into lines of a maximum length specified by `limit`. Words should not be split be... |
def rotate_matrix_90_clockwise(matrix):
return [list(row[::-1]) for row in zip(*matrix)] | simplelr_Filter | [
{
"content": "Question:\nI have a matrix represented as a list of lists in Python, where each inner list has the same length. How can I efficiently rotate this matrix 90 degrees clockwise?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4563,
"level": 1,
"question": "I have a matrix represented as a list of lists in Python, where each inner list has the same length. How can I efficiently rotate this matrix 90 degrees clockwise?",
"split": "train"
} |
from typing import List
def generate_multiples(n: int, m: int) -> List[int]:
return [m * i for i in range(n, 0, -1)] | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nWrite a Python function `generate_multiples(n: int, m: int) -> List[int]` that generates a list of the first `n` multiples of a positive integer `m` in descending order.\n\n### Input\n* `n` (1 ≤ n ≤ 10^6): The number of multiples to generate.\n* `m` (1 ≤ m ≤ 10^... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4564,
"level": 1,
"question": "### Problem Statement\n\nWrite a Python function `generate_multiples(n: int, m: int) -> List[int]` that generates a list of the first `n` multiples of a positive integer `m` in descending order.\n\n### Input\n* `n` (1 ≤ n ≤ 10^6): The number of multipl... |
def longest_consecutive_sequence(arr):
s = set(arr)
visited = set()
max_len = 0
for num in arr:
if num not in visited and (num - 1) not in s:
current = num
current_len = 0
while current in s:
visited.add(current)
current_len += ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an unsorted array `arr` of integers, find the length of the longest sequence of consecutive elements. In other words, identify the length of the longest subarray where each element is one greater than the previous element. Elements in the sequence do not need to be contiguous in t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4565,
"level": 1,
"question": "Given an unsorted array `arr` of integers, find the length of the longest sequence of consecutive elements. In other words, identify the length of the longest subarray where each element is one greater than the previous element. Elements in the sequenc... |
def append_unique_and_sort(string_list, new_string):
# Create a copy of the original list to avoid modifying it
updated_list = string_list.copy()
if new_string not in updated_list:
updated_list.append(new_string)
updated_list.sort()
return updated_list | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that appends a string to a list of strings in a safe manner, ensuring that each string is unique and sorted in alphabetical order after the append operation?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4566,
"level": 1,
"question": "How can I create a Python function that appends a string to a list of strings in a safe manner, ensuring that each string is unique and sorted in alphabetical order after the append operation?",
"split": "train"
} |
def move_target_to_end(nums, target):
write_pointer = 0
for i in range(len(nums)):
if nums[i] != target:
nums[write_pointer], nums[i] = nums[i], nums[write_pointer]
write_pointer += 1
return nums | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers `nums` and an integer `target`. Write a function to **move all instances** of `target` to the **end** of the list in-place, while maintaining the **relative order** of the non-target elements. Return the modified list. Do not use any extra space for anot... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4567,
"level": 1,
"question": "You are given a list of integers `nums` and an integer `target`. Write a function to **move all instances** of `target` to the **end** of the list in-place, while maintaining the **relative order** of the non-target elements. Return the modified list. ... |
def moving_average(trades, window_size):
stock_data = {}
result = []
for trade in trades:
symbol, price = trade
if symbol not in stock_data:
stock_data[symbol] = []
stock_data[symbol].append(price)
current_prices = stock_data[symbol]
k = min(window_size, l... | simplelr_Code_Contests | [
{
"content": "Question:\nYou have been assigned the task of creating a stock ticker that processes stock trades in real-time. The system should be able to handle a sequence of stock trades and provide the moving average stock price over a specified window size. Implement a function that provides this functional... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4568,
"level": 1,
"question": "You have been assigned the task of creating a stock ticker that processes stock trades in real-time. The system should be able to handle a sequence of stock trades and provide the moving average stock price over a specified window size. Implement a fun... |
def reverse_if_palindrome(s):
if s == s[::-1]:
return s[::-1]
else:
return s | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and returns the string in reverse order, but only if the string is a palindrome. If the string is not a palindrome, return the string as is.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4569,
"level": 1,
"question": "Create a function that takes a string as input and returns the string in reverse order, but only if the string is a palindrome. If the string is not a palindrome, return the string as is.",
"split": "train"
} |
def is_isomorphic(s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
s1_map = {}
s2_map = {}
for c1, c2 in zip(s1, s2):
if c1 in s1_map:
if s1_map[c1] != c2:
return False
else:
if c2 in s2_map:
if s2_ma... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nTwo strings are said to be isomorphic if the characters in one string can be replaced to get the second string, without changing the order of characters. For example, \"egg\" and \"add\" are isomorphic because the 'e' is replaced with 'a' and 'g' is replaced with 'd'. Howev... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4570,
"level": 1,
"question": "### Context\nTwo strings are said to be isomorphic if the characters in one string can be replaced to get the second string, without changing the order of characters. For example, \"egg\" and \"add\" are isomorphic because the 'e' is replaced with 'a' ... |
def count_vowels(s):
count = 0
vowels = {'a', 'e', 'i', 'o', 'u'}
for char in s:
if char.isalpha():
if char.lower() in vowels:
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a string as an input and returns the total number of vowels (a,e,i,o,u) in the string, including both lowercase and uppercase vowels. The function should ignore punctuation and whitespace.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4571,
"level": 1,
"question": "Create a Python function that takes a string as an input and returns the total number of vowels (a,e,i,o,u) in the string, including both lowercase and uppercase vowels. The function should ignore punctuation and whitespace.",
"split": "train"
} |
def max_non_overlapping_tasks(startTimes, endTimes):
# Combine the start and end times into a list of tasks
tasks = list(zip(startTimes, endTimes))
# Sort the tasks based on their end times
tasks.sort(key=lambda x: x[1])
count = 0
last_end = 0 # Initialize to 0 or any value less than the earlie... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two arrays `startTimes` and `endTimes`, each of size `n`, where the `i-th` element indicates the starting and ending times of the `i-th` task respectively. A worker can only work on one task at a time. Your task is to determine the maximum number of non-overlapping tasks t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4572,
"level": 1,
"question": "You are given two arrays `startTimes` and `endTimes`, each of size `n`, where the `i-th` element indicates the starting and ending times of the `i-th` task respectively. A worker can only work on one task at a time. Your task is to determine the maximu... |
def list_people_above_30(people):
result = []
for person in people:
if person['age'] > 30:
line = f"{person['name']}, {person['age']}, {person['city']}"
result.append(line)
return '\n'.join(result) if result else "No one is above 30." | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a list of dictionaries as input, where each dictionary represents a person with their name, age, and city. The function should return a single string that lists all the people who are above 30 years old, formatted as \"Name, Age, City\". Each person's... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4573,
"level": 1,
"question": "Create a Python function that takes a list of dictionaries as input, where each dictionary represents a person with their name, age, and city. The function should return a single string that lists all the people who are above 30 years old, formatted as... |
from collections import deque
def minimum_time_to_complete_courses(n, prerequisites):
adj = [[] for _ in range(n)]
in_degree = [0] * n
for a, b in prerequisites:
adj[a].append(b)
in_degree[b] += 1
queue = deque()
for i in range(n):
if in_degree[i] == 0:
queue.a... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `n` courses labeled from `0` to `n-1` to be completed, along with a list of `prerequisites` where `prerequisites[i] = [a, b]` indicates that course `a` must be completed before course `b`. Assume there are no duplicate prerequisites and assume that prerequisites ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4574,
"level": 1,
"question": "You are given a list of `n` courses labeled from `0` to `n-1` to be completed, along with a list of `prerequisites` where `prerequisites[i] = [a, b]` indicates that course `a` must be completed before course `b`. Assume there are no duplicate prerequis... |
def rotate_array(arr, k):
if not arr:
return []
n = len(arr)
effective_k = k % n
if effective_k == 0:
return list(arr)
return arr[-effective_k:] + arr[:-effective_k] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to rotate an array to the right by a given number of positions.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4575,
"level": 1,
"question": "Write a function to rotate an array to the right by a given number of positions.",
"split": "train"
} |
def minStepsToOrigin(x, y):
return abs(x) + abs(y) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two integers `x` and `y`, representing the coordinates of a point on a 2D plane. Each time you can move the point one step to the left, right, up, or down. You must determine the minimum number of steps required to reach the origin (0, 0) from the point `(x, y)`. Write a f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4576,
"level": 1,
"question": "You are given two integers `x` and `y`, representing the coordinates of a point on a 2D plane. Each time you can move the point one step to the left, right, up, or down. You must determine the minimum number of steps required to reach the origin (0, 0)... |
import heapq
def find_kth_smallest_heap(numbers, k):
"""Finds the Kth smallest number in a list of numbers using a Min-Heap.
Args:
numbers: A list of integers.
k: An integer representing the Kth smallest number to find (1-indexed).
Returns:
The Kth smallest number in the list.
... | simplelr_Filter | [
{
"content": "Question:\nThe problem I am trying to solve is as follows:\n\nGiven a list of N numbers, find the Kth smallest number in the list.\n\nYou can assume the inputs are\n\n`N: An integer representing the amount of numbers in the list.`\n`numbers: A list of N integers.`\n\n`K: An integer representing wh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4577,
"level": 1,
"question": "The problem I am trying to solve is as follows:\n\nGiven a list of N numbers, find the Kth smallest number in the list.\n\nYou can assume the inputs are\n\n`N: An integer representing the amount of numbers in the list.`\n`numbers: A list of N integers.... |
def is_prime(number):
"""
Determines if a number is prime.
Args:
number: The number to check.
Returns:
True if the number is prime, False otherwise.
"""
# Check if the number is an integer
if number % 1 != 0:
return False
# Convert to integer to handle cases like 5.... | simplelr_Filter | [
{
"content": "Question:\nThe purpose of this assignment is to write a program that:\n- Takes a numerical input from the user\n- Determines if the input is a prime number.\n\nCan you help me with a program for this?\n\nPlease use Python and provide explanations.\n\n```python\ndef is_prime(number):\n \"\"\"\n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4578,
"level": 1,
"question": "The purpose of this assignment is to write a program that:\n- Takes a numerical input from the user\n- Determines if the input is a prime number.\n\nCan you help me with a program for this?\n\nPlease use Python and provide explanations.\n\n```python\nd... |
def reverse_words(s):
return s.split()[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that converts a given string to a list of words. The words in the resulting list should be in reverse order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4579,
"level": 1,
"question": "Create a function that converts a given string to a list of words. The words in the resulting list should be in reverse order.",
"split": "train"
} |
def find_towering_building(heights, h):
prev_max = float('-inf')
for i, height in enumerate(heights):
if height > h and prev_max <= h:
return i
prev_max = max(prev_max, height)
return -1 | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `heights` representing the heights of a series of buildings and an integer `h` representing a height threshold. A building is considered **towering** if its height is more than `h`, and all buildings to its left are shorter than `h`. Return th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4580,
"level": 1,
"question": "You are given a **0-indexed** integer array `heights` representing the heights of a series of buildings and an integer `h` representing a height threshold. A building is considered **towering** if its height is more than `h`, and all buildings to its l... |
def reverseWords(s):
words = s.split() # Split into list of words
reversed_words = words[::-1] # Reverse the list
return ' '.join(reversed_words) # Join with spaces | simplelr_Filter | [
{
"content": "Question:\nThis is a coding challenge that requires me to implement a function called `reverseWords` that takes a string as input and returns a new string with the words in reverse order. \n\nFor example:\n```\nreverseWords(\"hello world\") == \"world hello\"\n```\n\nHere's my code:\n\n```python\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4581,
"level": 1,
"question": "This is a coding challenge that requires me to implement a function called `reverseWords` that takes a string as input and returns a new string with the words in reverse order. \n\nFor example:\n```\nreverseWords(\"hello world\") == \"world hello\"\n``... |
def word_frequency(s):
word_freq = {}
for word in s.split():
word_freq[word] = word_freq.get(word, 0) + 1
return word_freq | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that calculates the frequency of each word in a given string. The function should return a dictionary where keys are words and values are their respective frequencies. The words in the input string are separated by spaces.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4582,
"level": 1,
"question": "Write a Python function that calculates the frequency of each word in a given string. The function should return a dictionary where keys are words and values are their respective frequencies. The words in the input string are separated by spaces.",
"... |
def product_except_self(nums):
n = len(nums)
if n == 0:
return []
prefix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]
suffix = [1] * n
for i in range(n-2, -1, -1):
suffix[i] = suffix[i+1] * nums[i+1]
result = [prefix[i] * suffix[i... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers `nums` and returns a new list where each element is the product of all elements in `nums` except the element at the current index. For example, if the input list is `[1, 2, 3, 4]`, the output should be `[24, 12, 8, 6]` because `1*2*3*4/(nu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4583,
"level": 1,
"question": "Create a function that takes a list of integers `nums` and returns a new list where each element is the product of all elements in `nums` except the element at the current index. For example, if the input list is `[1, 2, 3, 4]`, the output should be `[... |
from typing import List
def rearrangeArray(arr: List[int]) -> List[int]:
positive = [x for x in arr if x >= 0]
negative = [x for x in arr if x < 0]
min_len = min(len(positive), len(negative))
result = []
for i in range(min_len):
result.append(positive[i])
result.append(negative... | simplelr_Codeforces | [
{
"content": "Question:\nGiven an array of integers, rearrange the array in such a way that the numbers alternate between positive and negative. The number of positive and negative numbers need not be equal. If there are extra positive or negative numbers, they should be placed at the end of the array. The rela... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4584,
"level": 1,
"question": "Given an array of integers, rearrange the array in such a way that the numbers alternate between positive and negative. The number of positive and negative numbers need not be equal. If there are extra positive or negative numbers, they should be place... |
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
high = mid - 1
else:
low = mid + 1
return -1 | simplelr_Filter | [
{
"content": "Question:\nI'm trying to implement a binary search algorithm on a sorted array of integers. Can you provide a simple example of how it works?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4585,
"level": 1,
"question": "I'm trying to implement a binary search algorithm on a sorted array of integers. Can you provide a simple example of how it works?",
"split": "train"
} |
def partition_list(nums, k):
less = []
equal = []
greater = []
for num in nums:
if num < k:
less.append(num)
elif num == k:
equal.append(num)
else:
greater.append(num)
return less + equal + greater | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of `n` integers and an integer `k`, partition the list such that: \n- All elements less than `k` come before elements equal to `k`, which must come before elements greater than `k`. \n- Relative ordering of elements in each partition should be preserved. \n\nReturn the modi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4586,
"level": 1,
"question": "Given a list of `n` integers and an integer `k`, partition the list such that: \n- All elements less than `k` come before elements equal to `k`, which must come before elements greater than `k`. \n- Relative ordering of elements in each partition shoul... |
def double_stutter(stack):
"""
Given a stack, double_stutter replaces every value
in the stack with two occurrences of that value.
:param stack: List[int] - Stack is represented as a list where the last element is the top of the stack.
:return: None - The stack is modified in place.
"""
sta... | simplelr_Data_Structure | [
{
"content": "Question:\n### Double Stutter Function\nImplement a function that takes a stack and duplicates each element such that each element appears twice one after the other. You are to implement the below function:\n\n```python\ndef double_stutter(stack):\n \"\"\"\n Given a stack, double_stutter rep... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4587,
"level": 1,
"question": "### Double Stutter Function\nImplement a function that takes a stack and duplicates each element such that each element appears twice one after the other. You are to implement the below function:\n\n```python\ndef double_stutter(stack):\n \"\"\"\n ... |
def compress_list(lst):
if not lst:
return []
result = []
current_num = lst[0]
count = 1
for num in lst[1:]:
if num == current_num:
count += 1
else:
result.append((current_num, count))
current_num = num
count = 1
result.appe... | simplelr_Taco | [
{
"content": "Question:\nAlice is managing a data analysis project and needs to write a program that compresses a list of integers by replacing consecutive identical elements with a single instance of the element and the count of its repetitions. The goal is to minimize the storage space without losing the info... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4588,
"level": 1,
"question": "Alice is managing a data analysis project and needs to write a program that compresses a list of integers by replacing consecutive identical elements with a single instance of the element and the count of its repetitions. The goal is to minimize the st... |
def max_excitement(n, w, s):
total = sum(w)
return [total] * len(s)
| simplelr_Taco | [
{
"content": "Question:\nA family of cats have moved into a building, and they have discovered a circular corridor with `n` doorways. Every time the cats enter the corridor, they love to play by running through these doorways. At each doorway `i` (1 ≤ i ≤ n), there is a toy with a weight of `wi`. The cats prefe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4589,
"level": 1,
"question": "A family of cats have moved into a building, and they have discovered a circular corridor with `n` doorways. Every time the cats enter the corridor, they love to play by running through these doorways. At each doorway `i` (1 ≤ i ≤ n), there is a toy wi... |
def formatName(fullName):
parts = fullName.split()
last = parts[-1]
first = parts[0]
middles = parts[1:-1]
middle_initials = [m[0] for m in middles]
if not middle_initials:
return f"{last}, {first}"
else:
return f"{last}, {first} {' '.join(middle_initials)}"
| simplelr_Taco | [
{
"content": "Question:\nImplement a function that takes a string containing a full name (first name, middle names in an optional list, and last name) and returns a formatted string with the last name, a comma, the first name, and the initial of each middle name. Each part should be separated by a space. If the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4590,
"level": 1,
"question": "Implement a function that takes a string containing a full name (first name, middle names in an optional list, and last name) and returns a formatted string with the last name, a comma, the first name, and the initial of each middle name. Each part sho... |
def reverse_array(arr):
return arr[::-1]
# Example usage:
array = [1, 2, 3, 4, 5]
reversed_array = reverse_array(array)
print(reversed_array) # Output: [5, 4, 3, 2, 1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that reverses the order of an array of any length. Can you provide an example implementation in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4591,
"level": 1,
"question": "Create a function that reverses the order of an array of any length. Can you provide an example implementation in Python?",
"split": "train"
} |
def process_string(s):
stack = []
for char in s:
if char != '#':
stack.append(char)
else:
if stack:
stack.pop()
return ''.join(stack)
# Example usage:
# print(process_backspace("abc#d##c")) # Output: "ac"
# print(process_backspace("ab##c#d#")) # O... | simplelr_Code_Contests | [
{
"content": "Question:\nThe Kingdom of Backspace is renowned for its love of coding and correcting mistakes. To celebrate their national pastime, they have developed a special string operation that involves the backspace character ('#'). The operation allows them to simulate the backspace behavior by processin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4592,
"level": 1,
"question": "The Kingdom of Backspace is renowned for its love of coding and correcting mistakes. To celebrate their national pastime, they have developed a special string operation that involves the backspace character ('#'). The operation allows them to simulate ... |
from collections import deque, defaultdict
def min_swaps_to_sort(arr):
sorted_arr = sorted(arr)
pos = defaultdict(deque)
for i, num in enumerate(sorted_arr):
pos[num].append(i)
targets = []
for num in arr:
idx = pos[num].popleft()
targets.append(idx)
visited = [False] * ... | simplelr_Apps | [
{
"content": "Question:\nImplement a function to find the minimum number of swaps required to sort an array of integers in ascending order. Each swap exchanges the positions of two different elements in the array. \n\nExample 1:\nInput: arr = [4, 3, 2, 1]\nOutput: 2\nExplanation: Swap 4 and 1 to get [1, 3, 2, 4... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4593,
"level": 1,
"question": "Implement a function to find the minimum number of swaps required to sort an array of integers in ascending order. Each swap exchanges the positions of two different elements in the array. \n\nExample 1:\nInput: arr = [4, 3, 2, 1]\nOutput: 2\nExplanati... |
def hamming_weight(n: int) -> int:
"""
Counts the number of '1' bits in the binary representation of a given unsigned integer.
Parameters:
n (int): The integer to count set bits for.
Returns:
int: The number of '1' bits in the binary representation of the given integer.
"""
count = 0
... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Objective\nWrite a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).\n\n#### Context\nIn a communication system, you are tasked to develop a module that verifies the integrity of transmitted data using the Hamming ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4594,
"level": 1,
"question": "#### Objective\nWrite a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).\n\n#### Context\nIn a communication system, you are tasked to develop a module that verifies the integrity of ... |
def find_min_max(nums):
if not nums:
return None, None
return (min(nums), max(nums)) | simplelr_Filter | [
{
"content": "Question:\nI have a list of numbers in Python and I want to find the smallest and the largest values in the list. How can I accomplish this using a function?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4595,
"level": 1,
"question": "I have a list of numbers in Python and I want to find the smallest and the largest values in the list. How can I accomplish this using a function?",
"split": "train"
} |
def find_missing_number(arr):
n = len(arr) + 1
expected_sum = n * (n + 1) // 2
actual_sum = sum(arr)
return expected_sum - actual_sum | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the missing number in an array of integers ranging from 1 to n. The array is 0-indexed and contains unique numbers from 1 to n except one.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4596,
"level": 1,
"question": "Write a python function to find the missing number in an array of integers ranging from 1 to n. The array is 0-indexed and contains unique numbers from 1 to n except one.",
"split": "train"
} |
def fibonacci_word(n):
if not isinstance(n, int) or n < 0:
raise ValueError("n must be a non-negative integer")
if n == 0:
return "0"
elif n == 1:
return "1"
else:
a, b = "0", "1"
for i in range(2, n + 1):
c = b + a
a, b = b, c
retu... | simplelr_Filter | [
{
"content": "Question:\nDevise an algorithm in Python that accepts a number as an input and returns the corresponding value on the Fibonacci word sequence. The Fibonacci word sequence is defined as follows: F(0) is \"0\", F(1) is \"1\", and for n > 1, F(n) = F(n - 1) + F(n - 2), where the + operation denotes s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4597,
"level": 1,
"question": "Devise an algorithm in Python that accepts a number as an input and returns the corresponding value on the Fibonacci word sequence. The Fibonacci word sequence is defined as follows: F(0) is \"0\", F(1) is \"1\", and for n > 1, F(n) = F(n - 1) + F(n - ... |
from typing import List
def search(nums: List[int], target: int) -> int:
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif target < nums[mid]:
high = mid - 1
else:
low = mid + 1... | simplelr_Code_Contests | [
{
"content": "Question:\nGiven an integer array `nums` of length `N` containing distinct integers and a target integer `target`, write a function to search for the target in the array. Return the index if the target is found; otherwise, return -1.\n\nYou must write an algorithm with O(log N) runtime complexity.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4598,
"level": 1,
"question": "Given an integer array `nums` of length `N` containing distinct integers and a target integer `target`, write a function to search for the target in the array. Return the index if the target is found; otherwise, return -1.\n\nYou must write an algorith... |
import pkgutil
import importlib
def list_package_content(package_name: str) -> dict:
try:
package = importlib.import_module(package_name)
except ImportError:
return {}
if not hasattr(package, '__path__'):
return {}
submodules = []
subpackages = []
for path... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\nUtilize the `pkgutil` module to implement a function that lists and categorizes all modules, submodules, and subpackages available in the specified packages within `sys.path`.\n\n#### Description\nImplement a function `list_package_content(package_name: str) -> dict` tha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4599,
"level": 1,
"question": "#### Objective\nUtilize the `pkgutil` module to implement a function that lists and categorizes all modules, submodules, and subpackages available in the specified packages within `sys.path`.\n\n#### Description\nImplement a function `list_package_cont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.