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 find_unique_characters(s):
seen = set()
result = []
for char in s:
if char not in seen:
seen.add(char)
result.append(char)
return result | simplelr_Evol | [
{
"content": "Question:\nImplement a function `find_unique_characters` that takes a string as input and returns a list of unique characters in the order they first appear in the string. Each character should be included only once, and the function should be case-sensitive, meaning 'a' and 'A' are considered dif... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3300,
"level": 1,
"question": "Implement a function `find_unique_characters` that takes a string as input and returns a list of unique characters in the order they first appear in the string. Each character should be included only once, and the function should be case-sensitive, mea... |
def factorial(n):
if n < 0:
raise ValueError("Factorial is not defined for negative numbers")
elif n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120 | simplelr_Filter | [
{
"content": "Question:\nThis is a code snippet written in Python.\n\n```python\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n - 1)\n\nprint(factorial(5))\n```\n\nThis code defines a function called `factorial()` that calculates the factorial of a non-negative integer `n` us... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3301,
"level": 1,
"question": "This is a code snippet written in Python.\n\n```python\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n - 1)\n\nprint(factorial(5))\n```\n\nThis code defines a function called `factorial()` that calculates the factori... |
from collections import Counter
def countCharacters(words, chars):
chars_count = Counter(chars)
total_chars = len(chars)
result = 0
for word in words:
if len(word) > total_chars:
continue
word_count = Counter(word)
valid = True
for char, count in word_count.i... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of strings `words` and a list of characters `chars`, return _the length of all words that can be formed using characters from_ `chars` _without reusing characters from_ `chars`_. Each character in_ `chars` _can only be used once for each word._\nAnswer:\nLet's think step by... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3302,
"level": 1,
"question": "Given a list of strings `words` and a list of characters `chars`, return _the length of all words that can be formed using characters from_ `chars` _without reusing characters from_ `chars`_. Each character in_ `chars` _can only be used once for each w... |
def find_smallest_missing_positive(nums):
positives = {num for num in nums if num > 0}
if not positives:
return 1
m = len(positives)
if 1 not in positives:
return 1
for i in range(2, m + 1):
if i not in positives:
return i
return m + 1 | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array `nums` of size `n` consisting of **positive** integers. Your task is to determine the **smallest** number that is **missing** from the array. A number is considered **missing** if it is not present in the array and is **greater** than 0.\n\n*For example, given `nu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3303,
"level": 1,
"question": "You are given an array `nums` of size `n` consisting of **positive** integers. Your task is to determine the **smallest** number that is **missing** from the array. A number is considered **missing** if it is not present in the array and is **greater**... |
import os
def prepend_path(base_path, filenames):
base_abspath = os.path.abspath(base_path)
if os.path.isdir(base_path):
base_abspath += os.sep
new_filenames = []
for filename in filenames:
file_abspath = os.path.abspath(filename)
if file_abspath == base_abspath.rstrip(os.sep) o... | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that prepends a given path to a list of file names, only if the file names do not already start with that path. This function should handle both absolute and relative file paths. Additionally, ensure the function can handle a large list of files efficiently.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3304,
"level": 1,
"question": "Write a function in Python that prepends a given path to a list of file names, only if the file names do not already start with that path. This function should handle both absolute and relative file paths. Additionally, ensure the function can handle a... |
def reverse_string(s):
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse a given string in Python. Given the string \"Hello world!\", it should return \"!dlrow olleH\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3305,
"level": 1,
"question": "Write a function to reverse a given string in Python. Given the string \"Hello world!\", it should return \"!dlrow olleH\".",
"split": "train"
} |
import heapq
def k_largest_elements(arr, k):
# Convert the array into a max-heap by inverting the values
max_heap = [-x for x in arr]
heapq.heapify(max_heap)
# Extract the k largest elements
result = []
for _ in range(k):
current = heapq.heappop(max_heap)
result.append(-cur... | simplelr_Package | [
{
"content": "Question:\nWrite a Python function named `k_largest_elements(arr, k)` that finds the `k` largest elements in an array. The function should use a max-heap to identify the `k` largest elements efficiently.\n\nThe `k_largest_elements` function must perform the following steps:\n1. Convert the given a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3306,
"level": 1,
"question": "Write a Python function named `k_largest_elements(arr, k)` that finds the `k` largest elements in an array. The function should use a max-heap to identify the `k` largest elements efficiently.\n\nThe `k_largest_elements` function must perform the follo... |
import random
def check_even_odd():
number = random.randint(1, 10)
if number % 2 == 0:
return "Even"
else:
return "Odd"
# Test the function
print(check_even_odd()) | simplelr_Filter | [
{
"content": "Question:\nI need to write a Python function that will generate a random integer between 1 and 10, and then check if the number is even or odd. If the number is even, the function should return \"Even\", and if it's odd, return \"Odd\". Can you provide me with the code for this?\nAnswer:\nLet's th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3307,
"level": 1,
"question": "I need to write a Python function that will generate a random integer between 1 and 10, and then check if the number is even or odd. If the number is even, the function should return \"Even\", and if it's odd, return \"Odd\". Can you provide me with th... |
import pandas as pd
def filter_and_sort_cars(dataframe, price_range, minimum_mpg, ascending):
min_price, max_price = price_range
mask = dataframe['price'].between(min_price, max_price) & (dataframe['mpg'] >= minimum_mpg)
filtered_df = dataframe[mask]
sorted_df = filtered_df.sort_values(by='price', asce... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with developing a function that utilizes the `pandas` library to analyze a dataset containing information about different car models and their respective features. The goal of this task is to filter and sort the data based on specific criteria.\n\n### Function Name: `filt... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3308,
"level": 1,
"question": "You are tasked with developing a function that utilizes the `pandas` library to analyze a dataset containing information about different car models and their respective features. The goal of this task is to filter and sort the data based on specific cr... |
def shortest_subarray_with_sum(nums, k):
prefix_sum_map = {0: -1}
min_length = float('inf')
current_sum = 0
for i, num in enumerate(nums):
current_sum += num
target = current_sum - k
if target in prefix_sum_map:
length = i - prefix_sum_map[target]
if lengt... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums`, find the **shortest** subarray whose sum is **equal** to a given integer `k`. If such a subarray does not exist, return `-1`. Return the length of the shortest subarray.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3309,
"level": 1,
"question": "Given an array of integers `nums`, find the **shortest** subarray whose sum is **equal** to a given integer `k`. If such a subarray does not exist, return `-1`. Return the length of the shortest subarray.",
"split": "train"
} |
def balanceParentheses(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
else:
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Apps | [
{
"content": "Question:\nWrite a function `balanceParentheses(s)` that takes a string `s` consisting solely of opening and closing parentheses. The function should return true if the string represents a balanced sequence of parentheses (i.e., every opening parenthesis has a corresponding closing parenthesis in ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3310,
"level": 1,
"question": "Write a function `balanceParentheses(s)` that takes a string `s` consisting solely of opening and closing parentheses. The function should return true if the string represents a balanced sequence of parentheses (i.e., every opening parenthesis has a co... |
def can_form_special_string(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
has_vowel = any(c in vowels for c in s)
has_consonant = any(c not in vowels for c in s)
return has_vowel and has_consonant | simplelr_Apps | [
{
"content": "Question:\n## Task\nDina loves to play with strings. She often creates special strings by rearranging the characters of the given strings. A string is considered special if it has at least one vowel (a, e, i, o, u) and at least one consonant. Dina wants you to help her find out if a given string c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3311,
"level": 1,
"question": "## Task\nDina loves to play with strings. She often creates special strings by rearranging the characters of the given strings. A string is considered special if it has at least one vowel (a, e, i, o, u) and at least one consonant. Dina wants you to he... |
def max_profit_with_cooldown(prices: list[int]) -> int:
if not prices:
return 0
buy = -prices[0]
sell = 0
cool = 0
for i in range(1, len(prices)):
new_buy = max(buy, cool - prices[i])
new_sell = max(sell, buy + prices[i])
new_cool = max(sell, cool)
... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are part of a team developing a financial software system that deals with complex investment transactions. As part of the system, you need to implement a function that calculates the maximum possible profit from a list of stock prices given specific constraints.\n\n###... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3312,
"level": 1,
"question": "### Scenario\nYou are part of a team developing a financial software system that deals with complex investment transactions. As part of the system, you need to implement a function that calculates the maximum possible profit from a list of stock prices... |
def is_even_integer(number):
return isinstance(number, int) and number % 2 == 0 | simplelr_Filter | [
{
"content": "Question:\nI want to create a function in Python that checks if a provided number is an integer and if it is, to determine if it is an even number. Can you help me write this function?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3313,
"level": 1,
"question": "I want to create a function in Python that checks if a provided number is an integer and if it is, to determine if it is an even number. Can you help me write this function?",
"split": "train"
} |
import plistlib
def modify_plist(input_file: str, output_file: str, updates: dict, key_to_remove: str) -> None:
"""
Reads a plist file, updates its content by adding or modifying keys, removes a specified key if it exists, and writes the result to a new plist file.
Args:
input_file: Path to the in... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nTo assess your understanding of working with plist files using the `plistlib` module in Python, you are required to write a function that reads a given plist file, modifies its content based on specific criteria, and writes the updated content back to a new plist file.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3314,
"level": 1,
"question": "#### Objective:\nTo assess your understanding of working with plist files using the `plistlib` module in Python, you are required to write a function that reads a given plist file, modifies its content based on specific criteria, and writes the updated... |
def fibonacci_sequence(count: int) -> list[int]:
if type(count) is not int:
raise ValueError("Count must be an integer.")
if count < 1:
raise ValueError("Count must be a positive integer.")
if count == 1:
return [0]
elif count == 2:
return [0, 1]
else:
sequenc... | simplelr_Algorithm | [
{
"content": "Question:\n### Fibonacci Sequence Generator\n\nYou need to implement a function that generates the Fibonacci sequence up to a specified count of terms. The Fibonacci sequence is a series of numbers where the next number is found by adding up the two numbers before it, starting with 0 and 1.\n\n###... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3315,
"level": 1,
"question": "### Fibonacci Sequence Generator\n\nYou need to implement a function that generates the Fibonacci sequence up to a specified count of terms. The Fibonacci sequence is a series of numbers where the next number is found by adding up the two numbers befor... |
def calculate_expression(expression):
terms = expression.split('+')
total = 0
for term in terms:
if not term:
continue
factors = term.split('*')
product = 1
for factor in factors:
product *= int(factor)
total += product
return total | simplelr_Evol | [
{
"content": "Question:\nImplement a function in Python that reads a string containing a mathematical expression involving addition and multiplication. The function should calculate and return the result of the expression, ensuring that multiplication has higher precedence than addition. For example, given the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3316,
"level": 1,
"question": "Implement a function in Python that reads a string containing a mathematical expression involving addition and multiplication. The function should calculate and return the result of the expression, ensuring that multiplication has higher precedence tha... |
def min_replacements_to_valid_time(time: str) -> int:
current_h = time[0:2]
current_m = time[3:5]
min_changes = float('inf')
for hour in range(24):
h_str = f"{hour:02d}"
changes_h = 0
for i in range(2):
if current_h[i] == '?':
changes_h += 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are given a string `time` representing the time in the format \"HH:MM\", where HH is a two-digit hour that ranges from \"00\" to \"23\", and MM is a two-digit minute that ranges from \"00\" to \"59\". Your task is to determine the minimum number of replacement... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3317,
"level": 1,
"question": "### Problem Statement\nYou are given a string `time` representing the time in the format \"HH:MM\", where HH is a two-digit hour that ranges from \"00\" to \"23\", and MM is a two-digit minute that ranges from \"00\" to \"59\". Your task is to determin... |
from typing import List, Tuple
max_borrow_limit = {1: 14, 2: 30, 3: 7, 4: 21}
def is_borrow_within_limit(borrow_logs: List[Tuple[int, int]]) -> bool:
for book_id, days in borrow_logs:
if days > max_borrow_limit[book_id]:
return False
return True | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question\n\n**Scenario**:\n\nYou are assigned to build a part of a library management system that helps manage the borrowing of books. Each borrower can borrow multiple books, and each book has a maximum borrow period. The system needs to ensure that no borrower can exceed th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3318,
"level": 1,
"question": "### Coding Question\n\n**Scenario**:\n\nYou are assigned to build a part of a library management system that helps manage the borrowing of books. Each borrower can borrow multiple books, and each book has a maximum borrow period. The system needs to en... |
def find_duplicates(s: str) -> dict:
char_counts = {}
for char in s:
char_counts[char] = char_counts.get(char, 0) + 1
return {char: count for char, count in char_counts.items() if count > 1} | simplelr_Algorithm | [
{
"content": "Question:\n### Find Duplicate Characters\n\nWrite a function that identifies all duplicate characters in a given string. The function should return a dictionary where the keys are the duplicate characters, and the values are the counts of their occurrences.\n\n#### Your Task\n1. **Character Counti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3319,
"level": 1,
"question": "### Find Duplicate Characters\n\nWrite a function that identifies all duplicate characters in a given string. The function should return a dictionary where the keys are the duplicate characters, and the values are the counts of their occurrences.\n\n##... |
def merge_and_reverse(cities, countries):
return list(zip(cities, countries))[::-1] | simplelr_Filter | [
{
"content": "Question:\nGiven two lists, `cities` and `countries`, write a Python function that merges these two lists into a single list of tuples, where each tuple contains a city and its corresponding country. The function should reverse the order of elements in the final list of tuples. For example, if the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3320,
"level": 1,
"question": "Given two lists, `cities` and `countries`, write a Python function that merges these two lists into a single list of tuples, where each tuple contains a city and its corresponding country. The function should reverse the order of elements in the final ... |
def remove_duplicates_efficient(array: list) -> list:
seen = set()
result = []
for element in array:
key = (type(element), element)
if key not in seen:
seen.add(key)
result.append(element)
return result | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Efficient Duplicate Removal\n\nYou are given an array that may contain duplicates, and your task is to write a function that removes duplicates and returns a new array with unique elements. Your solution should aim to improve the time complexity to O(n).\n\n#### Function S... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3321,
"level": 1,
"question": "### Question: Efficient Duplicate Removal\n\nYou are given an array that may contain duplicates, and your task is to write a function that removes duplicates and returns a new array with unique elements. Your solution should aim to improve the time com... |
def find_first_missing_integer(nums):
num_set = set(nums)
i = 1
while True:
if i not in num_set:
return i
i += 1 | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to identify the first missing integer in a sequence of consecutive integers starting from 1. The integers might not be sorted and may contain duplicates.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3322,
"level": 1,
"question": "Write a function to identify the first missing integer in a sequence of consecutive integers starting from 1. The integers might not be sorted and may contain duplicates.",
"split": "train"
} |
def filter_tuples(tuple_list):
return {t[0]: t[1] for t in tuple_list if t[1] > 10} | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of tuples, where each tuple contains a string and a number. The function should return a dictionary where the string is the key and the number is the value, but only include those tuples where the number is greater than 10.\nAnswer:\nLet's think... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3323,
"level": 1,
"question": "Write a Python function that takes a list of tuples, where each tuple contains a string and a number. The function should return a dictionary where the string is the key and the number is the value, but only include those tuples where the number is gre... |
def decode_string(S):
res = []
i = 0
while i < len(S):
if S[i].isalpha():
char = S[i]
i += 1
if i < len(S) and S[i].isdigit():
count = int(S[i])
i += 1
else:
count = 1
res.append(char * count)... | simplelr_Taco | [
{
"content": "Question:\nLuna is playing a game called String Decoder. In this game, she is given an encoded string `S` that consists of lower case letters and digits. The encoding rule is quite simple: each digit in the string represents how many times the previous character should be repeated.\n\nFor example,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3324,
"level": 1,
"question": "Luna is playing a game called String Decoder. In this game, she is given an encoded string `S` that consists of lower case letters and digits. The encoding rule is quite simple: each digit in the string represents how many times the previous character ... |
def unique_characters(s):
lower_s = s.lower()
return len(lower_s) == len(set(lower_s)) | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function named `unique_characters` that takes a string as input and returns `True` if all characters in the string are unique (i.e., no character repeats), and `False` otherwise. Ignore case sensitivity by treating uppercase and lowercase letters as equivalent. \n\nFor ex... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3325,
"level": 1,
"question": "Write a Python function named `unique_characters` that takes a string as input and returns `True` if all characters in the string are unique (i.e., no character repeats), and `False` otherwise. Ignore case sensitivity by treating uppercase and lowercas... |
def task_allocation(tasks, citizens):
n_tasks = len(tasks)
assigned = [False] * n_tasks
result = []
for citizen in citizens:
skill, prefs = citizen
task_id = -1
for pref in prefs:
for idx, t in enumerate(tasks):
if not assigned[idx] and t == pref and s... | simplelr_Apps | [
{
"content": "Question:\nIn a society driven by efficiency, each citizen is assigned a task by the central computer based on the individual's skills and the current needs of the society. Each task has an associated difficulty level ranging from 1 to 10. Each citizen has a skill level also ranging from 1 to 10, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3326,
"level": 1,
"question": "In a society driven by efficiency, each citizen is assigned a task by the central computer based on the individual's skills and the current needs of the society. Each task has an associated difficulty level ranging from 1 to 10. Each citizen has a skil... |
def multiply_elements(x, y):
return [x * num for num in y] | simplelr_Filter | [
{
"content": "Question:\nPlease write a Python function that takes two arguments: an integer x and a list of integers y, and returns a list of integers that are the result of multiplying x with each element in y. Additionally, the function should use list comprehension to achieve this.\nAnswer:\nLet's think ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3327,
"level": 1,
"question": "Please write a Python function that takes two arguments: an integer x and a list of integers y, and returns a list of integers that are the result of multiplying x with each element in y. Additionally, the function should use list comprehension to achi... |
def is_valid_isbn10(s):
if len(s) != 10:
return False
for i in range(9):
if not s[i].isdigit():
return False
if s[9] not in {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X'}:
return False
total = 0
for i in range(10):
char = s[i]
if i == 9 an... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given string is a valid ISBN-10 number. An ISBN-10 number is a 10-digit number where the first 9 digits are digits (0-9) and the last digit is either a digit or an 'X' (which represents 10). The validation is done using a weighted sum method, where each di... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3328,
"level": 1,
"question": "Write a function to check if a given string is a valid ISBN-10 number. An ISBN-10 number is a 10-digit number where the first 9 digits are digits (0-9) and the last digit is either a digit or an 'X' (which represents 10). The validation is done using a... |
def add_binary(a, b):
"""
Adds two binary numbers represented as strings.
Args:
a: The first binary number as a string.
b: The second binary number as a string.
Returns:
The sum of the two binary numbers as a string.
"""
max_len = max(len(a), len(b))
a = a.zfill(max... | simplelr_Filter | [
{
"content": "Question:\nThis is the code I have:\n\n```python\ndef add_binary(a, b):\n \"\"\"\n Adds two binary numbers represented as strings.\n\n Args:\n a: The first binary number as a string.\n b: The second binary number as a string.\n\n Returns:\n The sum of the two binary numbers as a strin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3329,
"level": 1,
"question": "This is the code I have:\n\n```python\ndef add_binary(a, b):\n \"\"\"\n Adds two binary numbers represented as strings.\n\n Args:\n a: The first binary number as a string.\n b: The second binary number as a string.\n\n Returns:\n The sum o... |
def max_difference(nums):
"""
Returns the maximum difference between two elements in the list such that the larger element appears after the smaller one.
Parameters:
nums (list): A list of integers.
Returns:
int: The maximum difference as described. Returns 0 if no such pair exists.
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns the maximum difference between two elements in the list such that the larger element appears after the smaller one. If no such pair exists, return 0. The function should be efficient and handle large lists. Additionally, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3330,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns the maximum difference between two elements in the list such that the larger element appears after the smaller one. If no such pair exists, return 0. The function should be efficient and... |
def get_rating_trends(ratings: list[int]) -> tuple[int, int, int]:
increases = 0
decreases = 0
stable = 0
if len(ratings) < 2:
return (increases, decreases, stable)
for i in range(1, len(ratings)):
current = ratings[i]
prev = ratings[i-1]
if current > prev:
... | simplelr_Package | [
{
"content": "Question:\n**Context:**\n\nYou are developing a recommendation system for an online bookstore. To better understand the reading preferences of your users, you need to analyze the patterns in their book ratings. Assume all ratings are integers between 1 and 5.\n\n**Objective:**\n\nWrite a function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3331,
"level": 1,
"question": "**Context:**\n\nYou are developing a recommendation system for an online bookstore. To better understand the reading preferences of your users, you need to analyze the patterns in their book ratings. Assume all ratings are integers between 1 and 5.\n\n... |
def two_sum(nums, k):
seen = {}
for i in range(len(nums)):
num = nums[i]
complement = k - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return None | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to accept a list and a target sum `k`, and return the indices of the first two numbers such that they add up to a specific target sum `k`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3332,
"level": 1,
"question": "Write a python function to accept a list and a target sum `k`, and return the indices of the first two numbers such that they add up to a specific target sum `k`.",
"split": "train"
} |
def reverse_integer(n):
if n == 0:
return 0
sign = 1
if n < 0:
sign = -1
s = str(abs(n))
trailing_zeros = 0
for char in reversed(s):
if char == '0':
trailing_zeros += 1
else:
break
s_without_zero = s.rstrip('0')
reversed_s = s_witho... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse an integer without changing the position of the digits '0' at the end. For example, if the input is 100, the output should be 1. If the input is -100, the output should be -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3333,
"level": 1,
"question": "Write a python function to reverse an integer without changing the position of the digits '0' at the end. For example, if the input is 100, the output should be 1. If the input is -100, the output should be -1.",
"split": "train"
} |
def convert_to_24_hour_format(time_12hr: str) -> str:
"""
Convert the given 12-hour formatted time string to a 24-hour formatted time string.
Parameters:
time_12hr (str): A string representing the time in 12-hour format with an 'AM' or 'PM' suffix.
Returns:
str: The converted time in 2... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are tasked with implementing a function that parses, validates, and converts a given string representing a time in 12-hour format into a 24-hour format. The function should handle different components of the time string and ensure correct conversion.\n\n### ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3334,
"level": 1,
"question": "### Problem Statement\n\nYou are tasked with implementing a function that parses, validates, and converts a given string representing a time in 12-hour format into a 24-hour format. The function should handle different components of the time string and... |
def merge_unique_sorted(list1: list[int], list2: list[int]) -> list[int]:
i = j = 0
merged = []
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
if not merged or list1[i] != merged[-1]:
merged.append(list1[i])
i += 1
else:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question: Merge Two Sorted Lists into One Without Duplicates\n\nYou have been provided with two non-decreasingly sorted lists of integers `list1` and `list2`. Write a function `merge_unique_sorted(list1: list[int], list2: list[int]) -> list[int]` that merges these ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3335,
"level": 1,
"question": "### Coding Assessment Question: Merge Two Sorted Lists into One Without Duplicates\n\nYou have been provided with two non-decreasingly sorted lists of integers `list1` and `list2`. Write a function `merge_unique_sorted(list1: list[int], list2: list[int... |
from collections import Counter
def remove_elements_over_ten_times(lst):
counts = Counter(lst)
exclude = {num for num, count in counts.items() if count > 10}
return [num for num in lst if num not in exclude] | simplelr_Filter | [
{
"content": "Question:\nCode a solution to remove any element from given list if it appears more than 10 times. If multiple elements appear more than 10 times, remove all of them from the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3336,
"level": 1,
"question": "Code a solution to remove any element from given list if it appears more than 10 times. If multiple elements appear more than 10 times, remove all of them from the list.",
"split": "train"
} |
def num_digits(n: int) -> int:
if n == 0:
return 1
count = 0
n = abs(n)
while n != 0:
n = n // 10
count += 1
return count | simplelr_Data_Structure | [
{
"content": "Question:\nA postal service needs to track the number of digits in postal codes of various formats efficiently. They want to implement a function that determines the number of digits in each postal code to allocate the correct amount of space on forms and in databases.\n\nYour task is to write a P... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3337,
"level": 1,
"question": "A postal service needs to track the number of digits in postal codes of various formats efficiently. They want to implement a function that determines the number of digits in each postal code to allocate the correct amount of space on forms and in data... |
import string
def word_frequency_counter(text: str) -> dict:
frequency = {}
words = text.split()
for word in words:
stripped = word.strip(string.punctuation)
if stripped:
lower_word = stripped.lower()
frequency[lower_word] = frequency.get(lower_word, 0) + 1
retur... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with writing a function named `word_frequency_counter` that takes a single parameter: `text`, which is a string. The purpose of this function is to analyze the text and return a dictionary with unique words as keys and their corresponding frequencies as values. Words shou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3338,
"level": 1,
"question": "You are tasked with writing a function named `word_frequency_counter` that takes a single parameter: `text`, which is a string. The purpose of this function is to analyze the text and return a dictionary with unique words as keys and their correspondin... |
def maxProduct(nums: list[int]) -> int:
nums_sorted = sorted(nums)
return nums_sorted[-1] * nums_sorted[-2]
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers nums, you need to find the maximum product of two elements in an array. The task is to write a function that takes an array as input and returns the maximum product of any two distinct elements. You cannot use the same element twice.\n\nExample 1:\nInput: nums... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3339,
"level": 1,
"question": "Given an array of integers nums, you need to find the maximum product of two elements in an array. The task is to write a function that takes an array as input and returns the maximum product of any two distinct elements. You cannot use the same elemen... |
from collections import Counter
def remove_elements_appearing_more_than_ten_times(input_list):
counts = Counter(input_list)
return [x for x in input_list if counts[x] <= 10] | simplelr_Filter | [
{
"content": "Question:\nCode a solution to remove any element from a given list if it appears more than 10 times.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3340,
"level": 1,
"question": "Code a solution to remove any element from a given list if it appears more than 10 times.",
"split": "train"
} |
def string_to_int_array(s):
return [int(num) for num in s.split()] | simplelr_Filter | [
{
"content": "Question:\nI have a string of numbers, and would like to write a function to convert that string into an array of integers. How do I do that in python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3341,
"level": 1,
"question": "I have a string of numbers, and would like to write a function to convert that string into an array of integers. How do I do that in python?",
"split": "train"
} |
def max_subarray_sum(arr):
if not arr:
return 0 # Assuming the function should return 0 for an empty array
max_ending_here = max_so_far = arr[0]
for num in arr[1:]:
max_ending_here = max(num, max_ending_here + num)
max_so_far = max(max_so_far, max_ending_here)
ret... | simplelr_Evol | [
{
"content": "Question:\nGiven a list of integers, write a function that finds the subarray with the maximum sum and returns that sum. The integers in the list can be both positive and negative, and the list may contain up to 10^5 elements.\n\nExample:\nInput: `[-2,1,-3,4,-1,2,1,-5,4]`\nOutput: `6`\n\nExplanati... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3342,
"level": 1,
"question": "Given a list of integers, write a function that finds the subarray with the maximum sum and returns that sum. The integers in the list can be both positive and negative, and the list may contain up to 10^5 elements.\n\nExample:\nInput: `[-2,1,-3,4,-1,2... |
def longest_happy_prefix(s):
n = len(s)
if n == 0:
return ""
pi = [0] * n
k = 0
for i in range(1, n):
while k > 0 and s[k] != s[i]:
k = pi[k-1]
if s[k] == s[i]:
k += 1
pi[i] = k
max_prefix_length = pi[-1]
return s[:max_prefix_length] if... | simplelr_Leetcode | [
{
"content": "Question:\nA string `s` is said to be a \"happy prefix\" if it is both a prefix and a suffix (excluding the entire string). Given a string `s`, write a function to find the longest happy prefix of `s`. If no such prefix exists, return an empty string.\n\nExamples:\n\n- Input: `s = \"level\"`\n Ou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3343,
"level": 1,
"question": "A string `s` is said to be a \"happy prefix\" if it is both a prefix and a suffix (excluding the entire string). Given a string `s`, write a function to find the longest happy prefix of `s`. If no such prefix exists, return an empty string.\n\nExamples... |
def find_pairs(nums):
used = [False] * len(nums)
pairs = []
seen_pairs = set()
for i in range(len(nums)):
if used[i]:
continue
current = nums[i]
for j in range(i + 1, len(nums)):
if not used[j] and current + nums[j] == 0:
a, b = curren... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns a list of tuples, where each tuple contains two integers from the input list whose sum is zero. Each pair `(a, b)` must be unique in the sense that you cannot reuse the same elements from the input list for different pairs, and ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3344,
"level": 1,
"question": "Write a function that takes a list of integers and returns a list of tuples, where each tuple contains two integers from the input list whose sum is zero. Each pair `(a, b)` must be unique in the sense that you cannot reuse the same elements from the i... |
def can_accommodate_groups(rides, k):
if k == 0:
return True
total = sum(rides)
return total >= k | simplelr_Leetcode | [
{
"content": "Question:\nYou are tasked with the design of an amusement park ride that can accommodate multiple groups of people. You have access to multiple rides, each with a limited capacity. You are given an array `rides` where `rides[i]` represents the maximum capacity of the i-th ride. Additionally, you a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3345,
"level": 1,
"question": "You are tasked with the design of an amusement park ride that can accommodate multiple groups of people. You have access to multiple rides, each with a limited capacity. You are given an array `rides` where `rides[i]` represents the maximum capacity of... |
def longestConsecutive(nums):
if not nums:
return 0
s = set(nums)
max_len = 0
for num in s:
if (num - 1) not in s:
current_num = num
current_len = 1
while (current_num + 1) in s:
current_num += 1
current_len += 1
... | simplelr_Taco | [
{
"content": "Question:\nGiven an unsorted integer array `nums`, return the length of the longest sequence of consecutive integers that can be formed. This sequence must be formed by consecutive integers in any order. \n\nExample 1:\nInput: nums = [100, 4, 200, 1, 3, 2]\nOutput: 4\nExplanation: The longest cons... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3346,
"level": 1,
"question": "Given an unsorted integer array `nums`, return the length of the longest sequence of consecutive integers that can be formed. This sequence must be formed by consecutive integers in any order. \n\nExample 1:\nInput: nums = [100, 4, 200, 1, 3, 2]\nOutpu... |
def linear_search(lst, target):
for element in lst:
if element == target:
return True
return False | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in an integer N (where N is the number of items in the list). The function should return true if a given integer is found in the list, and false otherwise. You will need to implement this function using linear search.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3347,
"level": 1,
"question": "Create a function that takes in an integer N (where N is the number of items in the list). The function should return true if a given integer is found in the list, and false otherwise. You will need to implement this function using linear search.",
"... |
def safe_tensor_operations():
import torch
# Initialize tensor 'a' on the default CUDA stream
a = torch.rand(10000, device="cuda")
# Create a new CUDA stream
new_stream = torch.cuda.Stream()
# Use the new stream for the multiplication operation
with torch.cuda.stream(new_strea... | simplelr_Docs | [
{
"content": "Question:\n### Description\n\nYou are required to write a function `safe_tensor_operations` that performs a series of tensor manipulations while ensuring proper synchronization between CUDA streams to avoid data races.\n\n### Function Signature\n```python\ndef safe_tensor_operations():\n # Your... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3348,
"level": 1,
"question": "### Description\n\nYou are required to write a function `safe_tensor_operations` that performs a series of tensor manipulations while ensuring proper synchronization between CUDA streams to avoid data races.\n\n### Function Signature\n```python\ndef sa... |
def levenshtein_distance(s1, s2):
n = len(s1)
m = len(s2)
if n == 0:
return m
if m == 0:
return n
# Create a matrix with (n+1) rows and (m+1) columns
matrix = [[0] * (m + 1) for _ in range(n + 1)]
# Initialize the first row and column
for i in range(n + 1):... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code to compare two strings using the Levenshtein distance?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3349,
"level": 1,
"question": "Can you provide a Python code to compare two strings using the Levenshtein distance?",
"split": "train"
} |
def findPalindromicSubstrings(s):
n = len(s)
if n == 0:
return []
dp = [[False] * n for _ in range(n)]
result = []
# Handle single character substrings
for i in range(n):
dp[i][i] = True
result.append(s[i])
# Handle substrings of length >= 2
for len... | simplelr_Taco | [
{
"content": "Question:\nGiven a string, find all the substrings that are palindromic. A substring is a consecutive sequence of characters within a string. A palindrome is a string that reads the same forwards and backwards, e.g., \"racecar\", \"madam\". \n\nExample 1:\nInput: \ns = \"abba\"\nOutput: \n[\"a\", ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3350,
"level": 1,
"question": "Given a string, find all the substrings that are palindromic. A substring is a consecutive sequence of characters within a string. A palindrome is a string that reads the same forwards and backwards, e.g., \"racecar\", \"madam\". \n\nExample 1:\nInput:... |
def hello_world():
print("Hello, World!") | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to print \"Hello, World!\" to the console.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3351,
"level": 1,
"question": "Write a function to print \"Hello, World!\" to the console.",
"split": "train"
} |
def compress_string(S):
if not S:
return ""
result = []
current_char = S[0]
count = 1
for char in S[1:]:
if char == current_char:
count += 1
else:
if count == 1:
result.append(current_char)
else:
result.appen... | simplelr_Taco | [
{
"content": "Question:\nGiven a string S of length n, the challenge is to compress the string such that identical consecutive characters are replaced by a single instance of the character followed by the count of its consecutive instances. If the count is 1, it should be omitted. For instance, the string \"aaa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3352,
"level": 1,
"question": "Given a string S of length n, the challenge is to compress the string such that identical consecutive characters are replaced by a single instance of the character followed by the count of its consecutive instances. If the count is 1, it should be omit... |
def min_sessions(tasks, sessionTime):
tasks.sort(reverse=True)
sessions = []
for task in tasks:
placed = False
for i in range(len(sessions)):
if sessions[i] >= task:
sessions[i] -= task
placed = True
break
if not placed:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of positive integers `tasks`, where each integer represents the processing time of a single task, and an integer `sessionTime` which represents the maximum duration of a work session. You want to find the **minimum number of work sessions** required to finish all th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3353,
"level": 1,
"question": "You are given a list of positive integers `tasks`, where each integer represents the processing time of a single task, and an integer `sessionTime` which represents the maximum duration of a work session. You want to find the **minimum number of work s... |
def is_valid_parentheses(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
else:
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to determine if a string is a valid parentheses string (VPS).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3354,
"level": 1,
"question": "Write a python function to determine if a string is a valid parentheses string (VPS).",
"split": "train"
} |
def count_words_in_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
words = content.split()
return len(words)
except FileNotFoundError:
return f"The file '{filename}' was not found."
# Example usage
filename = 'example.txt' # repl... | simplelr_Filter | [
{
"content": "Question:\nCreate a program in Python that reads a text file and prints the number of words in it.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3355,
"level": 1,
"question": "Create a program in Python that reads a text file and prints the number of words in it.",
"split": "train"
} |
def factorial(n):
if type(n) is not int:
return None
if n < 0:
return None
result = 1
for i in range(2, n + 1):
result *= i
return result | simplelr_Filter | [
{
"content": "Question:\nRewrite the following piece of code to handle an input which is a negative number, and also modify it to return the factorial value instead of printing it. If the input is a negative number or a non-integer, the function should return None.\nAnswer:\nLet's think step by step.\n",
"r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3356,
"level": 1,
"question": "Rewrite the following piece of code to handle an input which is a negative number, and also modify it to return the factorial value instead of printing it. If the input is a negative number or a non-integer, the function should return None.",
"split"... |
import itertools
def unique_subsets(input_list):
unique_elements = set(input_list)
elements = sorted(unique_elements)
subsets = []
for k in range(len(elements) + 1):
subsets.extend(itertools.combinations(elements, k))
subsets = [set(subset) for subset in subsets]
return subsets | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find all the unique subsets of a given set.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3357,
"level": 1,
"question": "Write a python function to find all the unique subsets of a given set.",
"split": "train"
} |
def largest_odd(a, b, c):
numbers = [a, b, c]
odds = [x for x in numbers if x % 2 != 0]
return max(odds) if odds else None | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes three integers as input and returns the largest odd number out of the three. If there is no odd number, it should return None.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3358,
"level": 1,
"question": "Create a function that takes three integers as input and returns the largest odd number out of the three. If there is no odd number, it should return None.",
"split": "train"
} |
from datetime import timedelta
def timedelta_to_hours(td: timedelta) -> float:
return td.total_seconds() / 3600 | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a timedelta object as input and returns its equivalent in hours. The function should convert the days part of the timedelta to hours and add it to the hours part of the timedelta to return the total hours.\nAnswer:\nLet's think step by step.\n",
"r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3359,
"level": 1,
"question": "Write a Python function that takes a timedelta object as input and returns its equivalent in hours. The function should convert the days part of the timedelta to hours and add it to the hours part of the timedelta to return the total hours.",
"split"... |
def arraySum(nums):
return sum(nums)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `arraySum(nums)` that takes a list of integers `nums` and returns the sum of all the elements. However, if the list is empty, the function should return 0.\n\nFor example, `arraySum([1, 2, 3, 4])` should return `10`, and `arraySum([])` should return `0`.\n\nGood luck :)... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3360,
"level": 1,
"question": "Write a function `arraySum(nums)` that takes a list of integers `nums` and returns the sum of all the elements. However, if the list is empty, the function should return 0.\n\nFor example, `arraySum([1, 2, 3, 4])` should return `10`, and `arraySum([])`... |
from typing import List
def find_missing_number(arr: List[int]) -> int:
n = len(arr) + 1
expected_sum = n * (n + 1) // 2
actual_sum = sum(arr)
return expected_sum - actual_sum
| simplelr_Taco | [
{
"content": "Question:\n## Find the Missing Integer\n\nYou are given an array of unique integers ranging from 1 to \\(N\\) with one element missing. The size of the array is \\(N-1\\). Write a function that finds the missing integer in linear time. \n\nYour function should return the missing integer.\n\n### Ex... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3361,
"level": 1,
"question": "## Find the Missing Integer\n\nYou are given an array of unique integers ranging from 1 to \\(N\\) with one element missing. The size of the array is \\(N-1\\). Write a function that finds the missing integer in linear time. \n\nYour function should re... |
def bubble_sort(lst):
n = len(lst)
for i in range(n - 1):
swapped = False
for j in range(0, n - i - 1):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
swapped = True
if not swapped:
break
return lst | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to sort a list of integers in ascending order using the bubble sort algorithm in Python. What is the time complexity of this algorithm?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3362,
"level": 1,
"question": "Write a function to sort a list of integers in ascending order using the bubble sort algorithm in Python. What is the time complexity of this algorithm?",
"split": "train"
} |
def check_anagram(s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2) | simplelr_Data_Structure | [
{
"content": "Question:\n### Context\n\nYou are tasked with ensuring that two given strings are anagrams of each other for a word game. An anagram is a word or phrase that can be rearranged to form another word or phrase using all the original letters exactly once. Given the constraints of the game, the strings... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3363,
"level": 1,
"question": "### Context\n\nYou are tasked with ensuring that two given strings are anagrams of each other for a word game. An anagram is a word or phrase that can be rearranged to form another word or phrase using all the original letters exactly once. Given the c... |
def max_adjacent_product(arr):
max_product = arr[0] * arr[1]
for i in range(1, len(arr) - 1):
product = arr[i] * arr[i + 1]
if product > max_product:
max_product = product
return max_product
| simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers, find the pair of adjacent elements that has the largest product and return that product.\n\n**Example:**\n\nFor the input array `[3, 6, -2, -5, 7, 3]`, the output should be `21`.\n\n**Explanation:** The pair of elements with the largest product is `(7, 3)`.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3364,
"level": 1,
"question": "Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.\n\n**Example:**\n\nFor the input array `[3, 6, -2, -5, 7, 3]`, the output should be `21`.\n\n**Explanation:** The pair of elements with... |
def find_majority_element(arr):
count = 0
candidate = None
for num in arr:
if count == 0:
candidate = num
count = 1
else:
if num == candidate:
count += 1
else:
count -= 1
return candidate
| simplelr_Taco | [
{
"content": "Question:\nImplement a function `find_majority_element` that takes an array of integers and returns the majority element, which is the element that appears more than n/2 times in the array (where n is the length of the array). You can assume that the array is non-empty and the majority element alw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3365,
"level": 1,
"question": "Implement a function `find_majority_element` that takes an array of integers and returns the majority element, which is the element that appears more than n/2 times in the array (where n is the length of the array). You can assume that the array is non... |
def intersect_lists(list1, list2):
# Create a lookup dictionary from list2 for O(1) membership checks
lookup = {}
for element in list2:
lookup[element] = True
# Initialize the result list and a tracker for added elements
result = []
added = {}
# Iterate through each element... | simplelr_Filter | [
{
"content": "Question:\nDesign a program to find the intersecting elements of two lists. However, you are not allowed to use the built-in set() function or any other built-in function that directly solves the problem. Instead, you should implement your own algorithm to find the intersecting elements.\nAnswer:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3366,
"level": 1,
"question": "Design a program to find the intersecting elements of two lists. However, you are not allowed to use the built-in set() function or any other built-in function that directly solves the problem. Instead, you should implement your own algorithm to find t... |
def multiply_by_index(arr):
return [value * index for index, value in enumerate(arr)] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers and returns an array with each element multiplied by its corresponding index.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3367,
"level": 1,
"question": "Create a function that takes an array of integers and returns an array with each element multiplied by its corresponding index.",
"split": "train"
} |
from collections import Counter
def count_occurrences(arr):
return dict(Counter(arr)) | simplelr_Filter | [
{
"content": "Question:\nI have an array of max 100 integers. I need to find the number of occurrences of each number in the array.\n\nExample Input:\n```python\n[1, 2, 3, 2, 1, 1, 4]\n```\nExample Output:\n```python\n{1: 3, 2: 2, 3: 1, 4: 1}\n```\nCan you provide a code solution in Python?\nAnswer:\nLet's thi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3368,
"level": 1,
"question": "I have an array of max 100 integers. I need to find the number of occurrences of each number in the array.\n\nExample Input:\n```python\n[1, 2, 3, 2, 1, 1, 4]\n```\nExample Output:\n```python\n{1: 3, 2: 2, 3: 1, 4: 1}\n```\nCan you provide a code solu... |
def min_insertions_to_valid(s):
balance = 0
insertions = 0
for c in s:
if c == '(':
balance += 1
else:
balance -= 1
if balance < 0:
insertions += 1
balance = 0
return insertions + balance | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a string bracket sequence that consists of characters '(' and ')'. We call a bracket sequence valid if it is possible to make the sequence empty by repeatedly deleting the substrings \"()\" from it.\n\nWrite a function `min_insertions_to_valid` that takes a string `s` and ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3369,
"level": 1,
"question": "You are given a string bracket sequence that consists of characters '(' and ')'. We call a bracket sequence valid if it is possible to make the sequence empty by repeatedly deleting the substrings \"()\" from it.\n\nWrite a function `min_insertions_to_... |
def bank_transactions(initial_balance, transactions):
current_balance = initial_balance
total_deposits = 0.0
total_withdrawals = 0.0
errors = []
for transaction in transactions:
action, amount = transaction
if action == 'deposit':
current_balance += amount
... | simplelr_Package | [
{
"content": "Question:\nYou are asked to implement a function that simulates a simple banking system transaction process. The function will handle deposits and withdrawals, maintaining a record of the current balance. You must ensure that each withdrawal does not exceed the available balance and that the user ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3370,
"level": 1,
"question": "You are asked to implement a function that simulates a simple banking system transaction process. The function will handle deposits and withdrawals, maintaining a record of the current balance. You must ensure that each withdrawal does not exceed the a... |
def mode(lst):
if not lst:
return None
freq = {}
for num in lst:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
max_count = max(freq.values())
candidates = [num for num, count in freq.items() if count == max_count]
return min(candidates) | simplelr_Evol | [
{
"content": "Question:\nDesign a function that calculates the mode of a list of integers. The mode is the integer that appears most frequently. If there are multiple modes, return the smallest one. Ensure your function handles both positive and negative integers as well as empty input lists gracefully.\n\nExam... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3371,
"level": 1,
"question": "Design a function that calculates the mode of a list of integers. The mode is the integer that appears most frequently. If there are multiple modes, return the smallest one. Ensure your function handles both positive and negative integers as well as em... |
def is_strobogrammatic(n: str) -> bool:
mapping = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
# Check if all characters are valid
for c in n:
if c not in mapping:
return False
length = len(n)
# Handle single character case
if length == 1:
return ... | simplelr_Data_Structure | [
{
"content": "Question:\nStrobogrammatic Number Check\n\n**Scenario**:\nYou are working on a digital display system in which certain sequences should look the same even if viewed upside down. To solve this, we need to determine if a given numeric string is strobogrammatic. \n\n**Problem Statement**:\nWrite a fu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3372,
"level": 1,
"question": "Strobogrammatic Number Check\n\n**Scenario**:\nYou are working on a digital display system in which certain sequences should look the same even if viewed upside down. To solve this, we need to determine if a given numeric string is strobogrammatic. \n\... |
from typing import Tuple
def binary_adder(a: Tuple[int, int], b: Tuple[int, int]) -> Tuple[int, int, int]:
"""
Implement a 2-bit binary adder.
:param a: The first 2-bit binary number (each bit 0 or 1).
:param b: The second 2-bit binary number (each bit 0 or 1).
:return: A tuple representing the su... | simplelr_Algorithm | [
{
"content": "Question:\nYou are assigned to write a Python function that implements a simple 2-bit binary adder. The function should take two 2-bit binary numbers (each represented as a tuple of two integers, which can be 0 or 1) and return a tuple representing the 2-bit sum and a carry-out bit. The inputs sho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3373,
"level": 1,
"question": "You are assigned to write a Python function that implements a simple 2-bit binary adder. The function should take two 2-bit binary numbers (each represented as a tuple of two integers, which can be 0 or 1) and return a tuple representing the 2-bit sum ... |
def is_balanced(s: str) -> bool:
stack = []
matching = {")": "(", "}": "{", "]": "["}
for char in s:
if char in matching.values():
stack.append(char)
elif char in matching.keys():
if not stack:
return False
top = stack.pop()
if ... | simplelr_Apps | [
{
"content": "Question:\nWrite a function def is_balanced(s: str) -> bool: that checks if a given string `s` containing only characters '(', ')', '{', '}', '[' and ']', has balanced brackets. Balanced brackets mean that every opening bracket has a corresponding closing bracket of the same type and the pairs of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3374,
"level": 1,
"question": "Write a function def is_balanced(s: str) -> bool: that checks if a given string `s` containing only characters '(', ')', '{', '}', '[' and ']', has balanced brackets. Balanced brackets mean that every opening bracket has a corresponding closing bracket... |
def max_concurrent_events(events: list) -> int:
points = []
for s, e in events:
points.append((s, 1)) # +1 for start of the event
points.append((e, 0)) # -1 for end of the event
# Sort the points. If times are equal, end events (0) come before start events (1)
points.sort()
curre... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are tasked with developing a utility in a software application that schedules events based on their start and end times. To prevent scheduling conflicts, you need to count the maximum number of concurrent events occurring at any point in time.\n\n### Task\nImplement a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3375,
"level": 1,
"question": "### Scenario\nYou are tasked with developing a utility in a software application that schedules events based on their start and end times. To prevent scheduling conflicts, you need to count the maximum number of concurrent events occurring at any point... |
def find_missing_letter(arr):
# Input validation
if not isinstance(arr, list) or len(arr) < 2:
return None
# Check if all elements are single-character strings and are letters
for c in arr:
if not isinstance(c, str) or len(c) != 1 or not c.isalpha():
return None
... | simplelr_Taco | [
{
"content": "Question:\nYour task is to **Find the Missing Letter**. This is a simple yet intriguing puzzle where you need to identify a missing character in a sequence of letters.\n\n### What needs to be done?\n\nGiven an array of consecutive (increasing) letters, find the missing letter in the array.\n\n### ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3376,
"level": 1,
"question": "Your task is to **Find the Missing Letter**. This is a simple yet intriguing puzzle where you need to identify a missing character in a sequence of letters.\n\n### What needs to be done?\n\nGiven an array of consecutive (increasing) letters, find the m... |
def hello_world():
print("Hello, World!")
return "Hello, World!" | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to print \"Hello, World!\" to the console. This function should also return the string \"Hello, World!\" from the function.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3377,
"level": 1,
"question": "Write a python function to print \"Hello, World!\" to the console. This function should also return the string \"Hello, World!\" from the function.",
"split": "train"
} |
def intToRoman(num):
val = [
(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'),
(1, 'I')
]
roman_numeral = ''
for (i, r) in val:
while num >= i:
roman_numeral += ... | simplelr_Package | [
{
"content": "Question:\nYou are asked to create a function in Python that converts an integer to its equivalent representation in Roman numerals. Roman numerals are represented by combinations of the following symbols:\n\n```\nSymbol Value\nI 1\nV 5\nX 10\nL 50... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3378,
"level": 1,
"question": "You are asked to create a function in Python that converts an integer to its equivalent representation in Roman numerals. Roman numerals are represented by combinations of the following symbols:\n\n```\nSymbol Value\nI 1\nV ... |
def count_unique_chars(s, queries):
result = []
for li, ri in queries:
substring = s[li:ri+1]
unique_count = len(set(substring))
result.append(unique_count)
return result | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a string s consisting of lowercase English letters, and an integer array queries where queries[i] = (li, ri) indicates a substring from index li to ri (inclusive). You are required to process each query by counting the number of unique characters in the specified substring... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3379,
"level": 1,
"question": "You are given a string s consisting of lowercase English letters, and an integer array queries where queries[i] = (li, ri) indicates a substring from index li to ri (inclusive). You are required to process each query by counting the number of unique ch... |
def sum_consecutive_elements(lst):
return [lst[i] + lst[i+1] for i in range(len(lst)-1)]
# Example usage:
numbers = [1, 2, 3, 4, 5]
new_list = sum_consecutive_elements(numbers)
print(new_list) # Output: [3, 5, 7, 9] | simplelr_Filter | [
{
"content": "Question:\nI have a list of numbers, and I want to create a new list where each element is the sum of two consecutive elements from the original list. How can I do this efficiently in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3380,
"level": 1,
"question": "I have a list of numbers, and I want to create a new list where each element is the sum of two consecutive elements from the original list. How can I do this efficiently in Python?",
"split": "train"
} |
def rearrange_array(arr, pivot):
less_than = []
equal = []
greater = []
for x in arr:
if x < pivot:
less_than.append(x)
elif x == pivot:
equal.append(x)
else:
greater.append(x)
return less_than + equal + greater | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `arr` and a pivot integer `pivot`. Rearrange the elements of `arr` so that all elements less than `pivot` appear before all elements equal to `pivot`, and those should appear before all elements greater than `pivot`. After rearranging, the relative order o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3381,
"level": 1,
"question": "You are given an integer array `arr` and a pivot integer `pivot`. Rearrange the elements of `arr` so that all elements less than `pivot` appear before all elements equal to `pivot`, and those should appear before all elements greater than `pivot`. Afte... |
def longest_common_subsequence(str1, str2):
m = len(str1)
n = len(str2)
# Create a table to store lengths of longest common subsequence.
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i-1] == str2[j-1]:
... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function `longest_common_subsequence(str1, str2)` that finds the length of the longest common subsequence between two input strings, `str1` and `str2`. A common subsequence is defined as a sequence that appears in both strings in the same order but not necessarily consecu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3382,
"level": 1,
"question": "Write a Python function `longest_common_subsequence(str1, str2)` that finds the length of the longest common subsequence between two input strings, `str1` and `str2`. A common subsequence is defined as a sequence that appears in both strings in the sam... |
import pandas as pd
def process_sales_data(file_path):
# Step 1: Load the Data
df = pd.read_csv(file_path)
# Step 2: Data Cleaning
# Fill missing Revenue values with the mean revenue of the respective Store and Department
df['Revenue'] = df.groupby(['Store', 'Department'])['Revenue'].transform... | simplelr_Docs | [
{
"content": "Question:\n### Pandas DataFrame Coding Assessment\n\n#### Objective\nDemonstrate your skills in handling `pandas` DataFrames by performing multiple operations, including data cleaning, transformation, aggregation, and visualization.\n\n#### Task\nWrite a Python function `process_sales_data` that t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3383,
"level": 1,
"question": "### Pandas DataFrame Coding Assessment\n\n#### Objective\nDemonstrate your skills in handling `pandas` DataFrames by performing multiple operations, including data cleaning, transformation, aggregation, and visualization.\n\n#### Task\nWrite a Python f... |
def maxWaterContainer(heights):
if len(heights) < 2:
return 0
left = 0
right = len(heights) - 1
max_water = 0
while left < right:
current_height = min(heights[left], heights[right])
current_area = current_height * (right - left)
if current_area > max_water:
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of non-negative integers representing the heights of columns where the width of each column is `1`. The goal is to find two columns such that together with the horizontal line they form a container which holds the most water. You need to return the maximum amount ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3384,
"level": 1,
"question": "You are given an array of non-negative integers representing the heights of columns where the width of each column is `1`. The goal is to find two columns such that together with the horizontal line they form a container which holds the most water. You... |
from typing import List
def most_purchased_item(transactions: List[str], exclude_list: List[str]) -> str:
freq = {}
first_occurrence = {}
for index, item in enumerate(transactions):
if item in exclude_list:
continue
if item not in freq:
freq[item] = 0
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nYour company is working on an e-commerce application, and one of the requirements is to find the most purchased item in a list of transactions. However, some of the items might be excluded from this list based on specific criteria. Given ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3385,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario\nYour company is working on an e-commerce application, and one of the requirements is to find the most purchased item in a list of transactions. However, some of the items might be excluded from this list... |
def remove_and_minimize(S, ch):
indices = [i for i, c in enumerate(S) if c == ch]
if not indices:
return S
min_str = None
for i in indices:
new_str = S[:i] + S[i+1:]
if min_str is None or new_str < min_str:
min_str = new_str
return min_str if min_str is not None e... | simplelr_Taco | [
{
"content": "Question:\nGiven a string `S` and a character `ch`, write a function that returns the smallest possible lexicographical string by removing exactly one occurrence of the character `ch` from `S`. If the character `ch` doesn't exist in the string, return the original string.\n\n**Example 1:**\n\n```\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3386,
"level": 1,
"question": "Given a string `S` and a character `ch`, write a function that returns the smallest possible lexicographical string by removing exactly one occurrence of the character `ch` from `S`. If the character `ch` doesn't exist in the string, return the origina... |
def is_palindrome(s):
# 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_Prefill | [
{
"content": "Question:\nWrite a python function to check whether a given string is a valid palindrome considering the condition that non-alphanumeric characters should be ignored, spaces should be ignored, and the case of the string should be ignored.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3387,
"level": 1,
"question": "Write a python function to check whether a given string is a valid palindrome considering the condition that non-alphanumeric characters should be ignored, spaces should be ignored, and the case of the string should be ignored.",
"split": "train"
} |
def rotate_array(arr, k):
n = len(arr)
if n == 0 or k == 0:
return
k = k % n
if k == 0:
return
# Reverse the entire array
left, right = 0, n - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
# Reve... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario:\nYour company’s internal software occasionally needs to cycle through a list of tasks represented as an array. Each time a new task execution cycle starts, the starting point changes based on some seed value 'k.' You have been tasked to write an efficient function to rotat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3388,
"level": 1,
"question": "### Scenario:\nYour company’s internal software occasionally needs to cycle through a list of tasks represented as an array. Each time a new task execution cycle starts, the starting point changes based on some seed value 'k.' You have been tasked to w... |
def atbash_cipher(s: str) -> str:
result = []
for c in s:
if c.isalpha():
if c.isupper():
new_char = chr(ord('Z') - (ord(c) - ord('A')))
result.append(new_char)
else:
new_char = chr(ord('z') - (ord(c) - ord('a')))
re... | simplelr_Data_Structure | [
{
"content": "Question:\n### Context\nYou are a cryptographer analyzing historical cipher techniques. Your goal is to implement a classical substitution cipher: the Atbash cipher. This cipher is a simple encryption method used to encode or decode strings by reversing the position of each letter in the alphabet.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3389,
"level": 1,
"question": "### Context\nYou are a cryptographer analyzing historical cipher techniques. Your goal is to implement a classical substitution cipher: the Atbash cipher. This cipher is a simple encryption method used to encode or decode strings by reversing the posit... |
def diagonal_difference(matrix):
size = len(matrix)
primary_sum = 0
secondary_sum = 0
for i in range(size):
primary_sum += matrix[i][i]
secondary_sum += matrix[i][size - 1 - i]
return abs(primary_sum - secondary_sum) | simplelr_Filter | [
{
"content": "Question:\nI want to write a code to find out the diagonal difference of a square matrix. The absolute difference between the sums of its diagonals. For example, for the following matrix:\n\n1 2 3\n4 5 6\n7 8 9\n\nThe diagonal difference is |(1+5+9)-(2+5+8)| = 0. \n\nThe goal is to write code that... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3390,
"level": 1,
"question": "I want to write a code to find out the diagonal difference of a square matrix. The absolute difference between the sums of its diagonals. For example, for the following matrix:\n\n1 2 3\n4 5 6\n7 8 9\n\nThe diagonal difference is |(1+5+9)-(2+5+8)| = 0.... |
from typing import List
def find_majority_element(arr: List[int]) -> int:
if not arr:
return -1
candidate = arr[0]
count = 1
for num in arr[1:]:
if num == candidate:
count += 1
else:
count -= 1
if count == 0:
candidat... | simplelr_Algorithm | [
{
"content": "Question:\n### Majority Element: Array Analysis Function\n\n**Context**:\nYou are working on a data analysis tool that involves finding the majority element in a list of integers. A majority element is an element that appears more than `n // 2` times in the list, where `n` is the length of the lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3391,
"level": 1,
"question": "### Majority Element: Array Analysis Function\n\n**Context**:\nYou are working on a data analysis tool that involves finding the majority element in a list of integers. A majority element is an element that appears more than `n // 2` times in the list,... |
def words_to_lengths(s):
words = s.split()
return [len(word) for word in words] | simplelr_Filter | [
{
"content": "Question:\nCan you write a Python function that converts a given string into a list of words, and then replaces each word with its length? For example, the string \"hello world\" should be converted to [5, 5].\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3392,
"level": 1,
"question": "Can you write a Python function that converts a given string into a list of words, and then replaces each word with its length? For example, the string \"hello world\" should be converted to [5, 5].",
"split": "train"
} |
def is_permutation(s1, s2):
return sorted(s1) == sorted(s2) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings `s1` and `s2`. You need to check if `s2` is a permutation of `s1`. A permutation of a string is another string that contains the same characters, only the order of characters can be different. Return `true` if `s2` is a permutation of `s1`, otherwise return `fa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3393,
"level": 1,
"question": "You are given two strings `s1` and `s2`. You need to check if `s2` is a permutation of `s1`. A permutation of a string is another string that contains the same characters, only the order of characters can be different. Return `true` if `s2` is a permut... |
from typing import List, Tuple
def merge_event_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if not intervals:
return []
# Sort intervals based on their start time
sorted_intervals = sorted(intervals, key=lambda x: x[0])
merged = []
current_start, current_end = ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\n\n#### Context:\nYou are responsible for managing a scheduling system where multiple events are defined by their starting and ending times. Events might overlap, and you need to merge them into non-overlapping intervals for better visualization and conflict management.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3394,
"level": 1,
"question": "### Question\n\n#### Context:\nYou are responsible for managing a scheduling system where multiple events are defined by their starting and ending times. Events might overlap, and you need to merge them into non-overlapping intervals for better visuali... |
def hamming_weight(n):
return bin(n).count('1') | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the Hamming Weight (number of 1 bits) of a given integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3395,
"level": 1,
"question": "Write a function to find the Hamming Weight (number of 1 bits) of a given integer.",
"split": "train"
} |
from typing import List
def rotate(array: List[int], k: int) -> List[int]:
n = len(array)
if n == 0 or k == 0:
return list(array)
k = k % n
if k == 0:
return list(array)
return array[-k:] + array[:-k] | simplelr_Data_Structure | [
{
"content": "Question:\n### Array Rotation Challenge\n\nImplement a function to rotate an array to the right by a given number of steps using the optimal algorithms provided in the description. You must consider edge cases and strive for efficient solutions both in terms of time and space complexity.\n\n#### F... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3396,
"level": 1,
"question": "### Array Rotation Challenge\n\nImplement a function to rotate an array to the right by a given number of steps using the optimal algorithms provided in the description. You must consider edge cases and strive for efficient solutions both in terms of t... |
def sum_list(nums):
if not nums:
return 0
else:
return nums[0] + sum_list(nums[1:])
# Example usage:
numbers = [1, 2, 3, 4, 5]
print(sum_list(numbers)) # Output: 15 | simplelr_Filter | [
{
"content": "Question:\nI've been tasked with writing a Python script to get the sum of numbers in a list using recursion. \n\nI can do this I think, but how do I get started? \n\nMy script should:\n1. define a function to accept a list of numbers\n2. use recursion to sum the numbers\n3. return the total \n\nH... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3397,
"level": 1,
"question": "I've been tasked with writing a Python script to get the sum of numbers in a list using recursion. \n\nI can do this I think, but how do I get started? \n\nMy script should:\n1. define a function to accept a list of numbers\n2. use recursion to sum the... |
import csv
def process_csv(input_filename, output_filename):
with open(input_filename, 'r') as infile:
reader = csv.DictReader(infile)
with open(output_filename, 'w', newline='') as outfile:
writer = csv.DictWriter(outfile, fieldnames=['Item', 'Quantity'])
writer.writeheader... | simplelr_Filter | [
{
"content": "Question:\nI need to create a Python function that reads a CSV file, processes the data, and writes the results to a new CSV file. The CSV file contains two columns: 'Item' and 'Quantity'. The function should filter items with a quantity greater than 10, multiply the quantity by 2, and then write ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3398,
"level": 1,
"question": "I need to create a Python function that reads a CSV file, processes the data, and writes the results to a new CSV file. The CSV file contains two columns: 'Item' and 'Quantity'. The function should filter items with a quantity greater than 10, multiply... |
from typing import List
def sieve_of_eratosthenes(n: int) -> List[int]:
if n < 2:
return []
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
p = 2
while p * p <= n:
if sieve[p]:
for i in range(p * p, n + 1, p):
sieve[i] = False
p += 1
prim... | simplelr_Algorithm | [
{
"content": "Question:\n### Prime Number Sieve Coding Assessment\n\nYou are tasked to implement the Sieve of Eratosthenes algorithm to find all prime numbers up to a given number `n`. Your function `sieve_of_eratosthenes()` should return the list of prime numbers up to and including `n`.\n\n#### Function Signa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3399,
"level": 1,
"question": "### Prime Number Sieve Coding Assessment\n\nYou are tasked to implement the Sieve of Eratosthenes algorithm to find all prime numbers up to a given number `n`. Your function `sieve_of_eratosthenes()` should return the list of prime numbers up to and in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.