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 re
def extract_first_sentence(s):
match = re.search(r'[.!?]', s)
if match:
end = match.start() + 1
sentence = s[:end].strip()
else:
sentence = s.strip()
return sentence | simplelr_Filter | [
{
"content": "Question:\nWrite a Python method `extract_first_sentence` that takes a string as input and returns the first sentence of the given string. A sentence is defined as a sequence of characters ending with a period ('.'), exclamation mark ('!'), or question mark ('?'). If the input does not contain a s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7000,
"level": 1,
"question": "Write a Python method `extract_first_sentence` that takes a string as input and returns the first sentence of the given string. A sentence is defined as a sequence of characters ending with a period ('.'), exclamation mark ('!'), or question mark ('?')... |
def calculate_total_time(recipe):
"""Calculates the total cooking time for a recipe.
Args:
recipe: A dictionary representing a recipe.
Returns:
The total cooking time in minutes.
"""
return recipe.get('prep_time', 0) + recipe.get('cook_time', 0) | simplelr_Filter | [
{
"content": "Question:\nI'm building a simple recipe app and need help with a function to calculate the total cooking time.\n\n**Here's what I have:**\n\n```python\ndef calculate_total_time(recipe):\n \"\"\"Calculates the total cooking time for a recipe.\n\n Args:\n recipe: A dictionary representing a rec... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7001,
"level": 1,
"question": "I'm building a simple recipe app and need help with a function to calculate the total cooking time.\n\n**Here's what I have:**\n\n```python\ndef calculate_total_time(recipe):\n \"\"\"Calculates the total cooking time for a recipe.\n\n Args:\n reci... |
def product_except_self(nums):
n = len(nums)
left = [0] * n
right = [0] * n
left[0] = 1
for i in range(1, n):
left[i] = left[i-1] * nums[i-1]
right[-1] = 1
for i in range(n-2, -1, -1):
right[i] = right[i+1] * nums[i+1]
return [left[i] * right[i] for i in ra... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a list of integers as input and returns a new list of integers where each element at index `i` is the product of all the numbers in the original list except the one at `i`.\n\nThe function should work in a way that does not use the division operation. \n\nYou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7002,
"level": 1,
"question": "Write a function that takes a list of integers as input and returns a new list of integers where each element at index `i` is the product of all the numbers in the original list except the one at `i`.\n\nThe function should work in a way that does not ... |
def decodeString(s):
result = ''
current_number = ''
for char in s:
if char.isdigit():
current_number += char
else:
if current_number:
count = int(current_number)
result += char * count
current_number = ''
return res... | simplelr_Taco | [
{
"content": "Question:\nYou need to write a function that will take an encoded string and return its decoded version. The encoding rule is simple: each run of digits 0-9 is followed by a corresponding character. The number indicates the number of times the character should be repeated in the decoded string.\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7003,
"level": 1,
"question": "You need to write a function that will take an encoded string and return its decoded version. The encoding rule is simple: each run of digits 0-9 is followed by a corresponding character. The number indicates the number of times the character should be... |
import heapq
from typing import List
def dijkstra(adj_matrix: List[List[int]], start: int) -> List[int]:
n = len(adj_matrix)
infinity = float('inf')
distances = [infinity] * n
distances[start] = 0
heap = []
heapq.heappush(heap, (0, start))
while heap:
current_dist, u = heapq.he... | simplelr_Algorithm | [
{
"content": "Question:\n## Dijkstra's Algorithm for Shortest Path\n\nImplement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a given directed weighted graph. The graph is represented using an adjacency matrix.\n\n### Function Signature\n```python\ndef dijkstra(adj_matr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7004,
"level": 1,
"question": "## Dijkstra's Algorithm for Shortest Path\n\nImplement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a given directed weighted graph. The graph is represented using an adjacency matrix.\n\n### Function Signatur... |
def filter_and_sort_even_numbers(numbers, cutoff):
even_above = [num for num in numbers if num % 2 == 0 and num > cutoff]
even_above.sort()
return even_above | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that returns the even numbers in a list, but only if they are greater than a certain value. The function should return these numbers sorted in ascending order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7005,
"level": 1,
"question": "Create a function that returns the even numbers in a list, but only if they are greater than a certain value. The function should return these numbers sorted in ascending order.",
"split": "train"
} |
def print_triangle(n):
"""Prints a right-angled triangle of height n using asterisks.
Args:
n (int): The height of the triangle. Each row i (starting from 1) contains i asterisks.
"""
for i in range(1, n + 1):
print('*' * i) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function named `print_triangle` that takes an integer `n` as an argument and prints a right-angled triangle of height `n` using asterisks (`*`). Each row of the triangle should contain a number of asterisks equal to its row number, starting from 1 up to `n`. Additionally... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7006,
"level": 1,
"question": "Create a Python function named `print_triangle` that takes an integer `n` as an argument and prints a right-angled triangle of height `n` using asterisks (`*`). Each row of the triangle should contain a number of asterisks equal to its row number, star... |
from itertools import compress
from functools import partial, reduce
from operator import mul, add
def process_sequence(sequence: list[int], n: int) -> int:
# Step 1: Filter the sequence using itertools
filtered = compress(sequence, (x % n == 0 for x in sequence))
# Step 2: Double each number using fu... | simplelr_Docs | [
{
"content": "Question:\n**Functional Programming Challenge in Python**\n\n**Objective**:\nDemonstrate your comprehension of the `itertools`, `functools`, and `operator` modules by implementing a function that processes a sequence of elements efficiently.\n\n**Problem Statement**:\nWrite a Python function `proc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7007,
"level": 1,
"question": "**Functional Programming Challenge in Python**\n\n**Objective**:\nDemonstrate your comprehension of the `itertools`, `functools`, and `operator` modules by implementing a function that processes a sequence of elements efficiently.\n\n**Problem Statemen... |
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result | simplelr_Filter | [
{
"content": "Question:\nI see that factorial of a number can be calculated by iterating through the range from 1 to a given number.\nThe problem is, I can write `return i` before I get to using it. Could you create a code snippet of the factorial operation without writeability concerns?\nAnswer:\nLet's think s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7008,
"level": 1,
"question": "I see that factorial of a number can be calculated by iterating through the range from 1 to a given number.\nThe problem is, I can write `return i` before I get to using it. Could you create a code snippet of the factorial operation without writeabilit... |
def count_frequency(num_list):
freq = {}
for num in num_list:
freq[num] = freq.get(num, 0) + 1
return freq | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function to process a list of integers and return a dictionary with the frequency of each integer in the list?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7009,
"level": 1,
"question": "Can you provide a Python function to process a list of integers and return a dictionary with the frequency of each integer in the list?",
"split": "train"
} |
def calculate_visits(log_file: str) -> dict:
visits = {}
try:
with open(log_file, 'r') as f:
for line in f:
parts = line.strip().split()
if len(parts) == 2:
user = parts[0]
visits[user] = visits.get(user, 0) + 1
exce... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario:\nYou have been hired to develop a Python application that helps track and analyze user activity on a website. One feature of the application is to process server log files and extract insightful statistics about user visits. Your task is to implement a function that reads ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7010,
"level": 1,
"question": "### Scenario:\nYou have been hired to develop a Python application that helps track and analyze user activity on a website. One feature of the application is to process server log files and extract insightful statistics about user visits. Your task is ... |
def find_missing_numbers(nums, n):
num_set = set(nums)
missing = []
for i in range(1, n + 1):
if i not in num_set:
missing.append(i)
return missing | simplelr_Package | [
{
"content": "Question:\nCreate a function named `find_missing_numbers` that takes in a list of integers ranging from 1 to n (inclusive) but with some numbers missing from the list. The function should return a list of the missing numbers in ascending order.\n\nYour function should have the following signature:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7011,
"level": 1,
"question": "Create a function named `find_missing_numbers` that takes in a list of integers ranging from 1 to n (inclusive) but with some numbers missing from the list. The function should return a list of the missing numbers in ascending order.\n\nYour function s... |
def josephus(n, m):
people = list(range(1, n+1))
index = 0
order = []
while people:
index = (index + m - 1) % len(people)
person = people.pop(index)
order.append(person)
return order
# Test cases
print(josephus(5, 2)) # Output: [2, 4, 1, 5, 3]
print(josephus(7, 3)) # Outpu... | simplelr_Filter | [
{
"content": "Question:\nHere is a problem I have been stuck on, I was hoping you could help me with it. \n\nWrite a program that can solve the \"Josephus problem.\" \n\nThe problem statement is: \n\nJosephus problem is defined by the following: n people are standing in a circle and, beginning with the first pe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7012,
"level": 1,
"question": "Here is a problem I have been stuck on, I was hoping you could help me with it. \n\nWrite a program that can solve the \"Josephus problem.\" \n\nThe problem statement is: \n\nJosephus problem is defined by the following: n people are standing in a circ... |
def is_first_char_uppercase(s):
if not s:
return False
return s[0].isupper() | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function that checks if the first character of a given string is an uppercase letter. If the string is empty, the function should return `False`. Use a simple and clear approach to achieve this task.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7013,
"level": 1,
"question": "Design a Python function that checks if the first character of a given string is an uppercase letter. If the string is empty, the function should return `False`. Use a simple and clear approach to achieve this task.",
"split": "train"
} |
def max_ice_cream(costs, coins):
costs.sort()
total = 0
count = 0
for cost in costs:
if total + cost > coins:
break
total += cost
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\n### Define a function `max_ice_cream` that takes two parameters: `costs` and `coins`. \n# The function should return the number of ice cream bars that can be bought with the given amount of money (`coins`).\n# The cost of each ice cream bar is given in the `costs` list.\nAnswer:\nLet's ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7014,
"level": 1,
"question": "### Define a function `max_ice_cream` that takes two parameters: `costs` and `coins`. \n# The function should return the number of ice cream bars that can be bought with the given amount of money (`coins`).\n# The cost of each ice cream bar is given in... |
def find_min_odd(numbers):
min_odd = None
for num in numbers:
if num % 2 != 0:
if min_odd is None or num < min_odd:
min_odd = num
return min_odd | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `find_min_odd` that takes a list of integers and returns the smallest odd number in the list. If there are no odd numbers in the list, the function should return `None`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7015,
"level": 1,
"question": "Write a Python function `find_min_odd` that takes a list of integers and returns the smallest odd number in the list. If there are no odd numbers in the list, the function should return `None`.",
"split": "train"
} |
def substring_frequencies(s):
freq_dict = {}
n = len(s)
for i in range(n):
for j in range(i + 1, n + 1):
substring = s[i:j]
if substring in freq_dict:
freq_dict[substring] += 1
else:
freq_dict[substring] = 1
return freq_dict | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to create a dictionary with all possible substrings from a given string as keys and their frequencies as values.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7016,
"level": 1,
"question": "Write a python function to create a dictionary with all possible substrings from a given string as keys and their frequencies as values.",
"split": "train"
} |
def sum_of_cubes(lst):
return sum(num ** 3 for num in lst) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list of integers and returns the sum of the cubes of all the integers in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7017,
"level": 1,
"question": "Create a function that takes in a list of integers and returns the sum of the cubes of all the integers in the list.",
"split": "train"
} |
def sum_even_fibonacci(N: int) -> int:
sum_even = 0
if N >= 0:
sum_even += 0
a, b = 0, 2
if b <= N:
sum_even += b
else:
return sum_even
while True:
next_even = 4 * b + a
if next_even > N:
break
sum_even += next_even
a, b = b, ne... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context:\nThe Fibonacci sequence is a series of numbers in which each number (Fibonacci number) is the sum of the two preceding ones, usually starting with `0` and `1`. That is:\n- F(0) = 0\n- F(1) = 1\n- For n ≥ 2, F(n) = F(n-1) + F(n-2)\n\n#### P... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7018,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context:\nThe Fibonacci sequence is a series of numbers in which each number (Fibonacci number) is the sum of the two preceding ones, usually starting with `0` and `1`. That is:\n- F(0) = 0\n- F(1) = 1\n- For n ≥ ... |
def calculate_position(time_scale, time_value):
return time_scale * time_value | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two parameters, a linear time-scale and a time value. The function should calculate the position of a point on a line at a specific time according to the time scale. The time scale is given as points per second and the time value is the current time in secon... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7019,
"level": 1,
"question": "Create a function that takes two parameters, a linear time-scale and a time value. The function should calculate the position of a point on a line at a specific time according to the time scale. The time scale is given as points per second and the time... |
def min_coins(amount: int, coins: list) -> int:
if amount == 0:
return 0
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for coin in coins:
if coin <= i:
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if dp[amount] != fl... | simplelr_Package | [
{
"content": "Question:\nThe function should output with:\n```python\ndef min_coins(amount: int, coins: list) -> int:\n```\n int: The minimum number of coins needed to make up the given amount. If it's not possible to make up the amount with the given denominations, return -1.\nAnswer:\nLet's think step by s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7020,
"level": 1,
"question": "The function should output with:\n```python\ndef min_coins(amount: int, coins: list) -> int:\n```\n int: The minimum number of coins needed to make up the given amount. If it's not possible to make up the amount with the given denominations, return ... |
def binary_search(sorted_list, target):
# Check if the list is sorted
for i in range(len(sorted_list)-1):
if sorted_list[i] > sorted_list[i+1]:
raise ValueError("List must be sorted in ascending order.")
low = 0
high = len(sorted_list) - 1
while low <= high:
mid... | simplelr_Filter | [
{
"content": "Question:\nI'd like to see code implementing a basic binary search algorithm in Python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7021,
"level": 1,
"question": "I'd like to see code implementing a basic binary search algorithm in Python.",
"split": "train"
} |
def get_buildings_with_city(cities):
all_buildings = []
for city in cities:
city_name = city['name']
for building in city['buildings']:
new_building = building.copy()
new_building['city'] = city_name
all_buildings.append(new_building)
return all_buildings | simplelr_Filter | [
{
"content": "Question:\nI have a list of cities, and for each city, I have another list of dictionaries, where each dictionary represents a building in the city. Here's an example:\n\n```\ncities = [\n {\n 'name': 'New York',\n 'buildings': [\n {'name': 'Empire State Building', 'hei... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7022,
"level": 1,
"question": "I have a list of cities, and for each city, I have another list of dictionaries, where each dictionary represents a building in the city. Here's an example:\n\n```\ncities = [\n {\n 'name': 'New York',\n 'buildings': [\n {'n... |
def longest_subsequence(nums):
dp = {}
max_len = 0
for x in nums:
prev_max = max(dp.get(x - 1, 0), dp.get(x + 1, 0))
current = prev_max + 1
if x in dp:
if current > dp[x]:
dp[x] = current
else:
dp[x] = current
if dp[x] > max_len... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums`, return the **length of the longest subsequence** such that the difference between adjacent elements is either exactly `1` or exactly `-1`. A subsequence is defined as a sequence derived from the array `nums` by deleting some or no elements without chan... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7023,
"level": 1,
"question": "Given an array of integers `nums`, return the **length of the longest subsequence** such that the difference between adjacent elements is either exactly `1` or exactly `-1`. A subsequence is defined as a sequence derived from the array `nums` by deleti... |
def convert_to_12_hour_format(time_str):
parts = time_str.split(':')
hours = int(parts[0]) % 24
minutes = int(parts[1])
seconds = int(parts[2])
if hours == 0:
period = "AM"
converted_hour = 12
elif 1 <= hours < 12:
period = "AM"
converted_hour = hours
elif ho... | simplelr_Filter | [
{
"content": "Question:\nDevelop a code to convert time from 24-hour format to 12-hour format, including the handling of minutes and seconds. In addition, your function should handle edge cases like \"00:00:00\" and \"24:00:00\". For an extra challenge, fix the error in the given partially implemented code snip... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7024,
"level": 1,
"question": "Develop a code to convert time from 24-hour format to 12-hour format, including the handling of minutes and seconds. In addition, your function should handle edge cases like \"00:00:00\" and \"24:00:00\". For an extra challenge, fix the error in the gi... |
def selection_sort(lst):
# Create a copy of the list to avoid modifying the original
sorted_list = lst.copy()
# Iterate through each position in the list
for i in range(len(sorted_list)):
# Find the minimum element in the unsorted part of the list starting from i
min_val = sorted_list[i]... | simplelr_Filter | [
{
"content": "Question:\nCan you explain how to create a Python function that takes a list of integers and returns a new list with the integers sorted in ascending order using the selection sort algorithm?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7025,
"level": 1,
"question": "Can you explain how to create a Python function that takes a list of integers and returns a new list with the integers sorted in ascending order using the selection sort algorithm?",
"split": "train"
} |
def sort_dict_values_desc(input_dict):
result = {}
for key, value in input_dict.items():
if len(value) < 3:
result[key] = value
else:
result[key] = sorted(value, reverse=True)
return result | simplelr_Evol | [
{
"content": "Question:\nCreate a Python function that takes a dictionary with string keys and list of integers as values, and returns a new dictionary with the same keys, where each integer list is sorted in descending order. If a list contains less than 3 integers, the function should leave that list unchange... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7026,
"level": 1,
"question": "Create a Python function that takes a dictionary with string keys and list of integers as values, and returns a new dictionary with the same keys, where each integer list is sorted in descending order. If a list contains less than 3 integers, the funct... |
def romanToInt(s):
roman_values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
prev_value = 0
for char in reversed(s):
current_value = roman_values[char]
if current_value < prev_value:
total -= current_value
else:
total += cu... | simplelr_Taco | [
{
"content": "Question:\nYou've been asked to write a function that converts Roman numerals to their corresponding integer values. \n\nRoman numerals are represented by seven different symbols: I, V, X, L, C, D, and M. \n\n| Symbol | Value |\n|--------|-------|\n| I | 1 |\n| V | 5 |\n| X ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7027,
"level": 1,
"question": "You've been asked to write a function that converts Roman numerals to their corresponding integer values. \n\nRoman numerals are represented by seven different symbols: I, V, X, L, C, D, and M. \n\n| Symbol | Value |\n|--------|-------|\n| I | 1 ... |
def min_add_to_make_valid(s):
count = 0
ans = 0
for c in s:
if c == '(':
count += 1
else:
count -= 1
if count < 0:
ans += 1
count = 0
ans += count
return ans | simplelr_Leetcode | [
{
"content": "Question:\nWe are given a string `s` consisting of only the characters '(' and ')'. We need to transform the string into a **valid** string by inserting the minimum number of parentheses. A string is considered valid if it is empty, contains only balanced parentheses, or can be written as `A` + `B... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7028,
"level": 1,
"question": "We are given a string `s` consisting of only the characters '(' and ')'. We need to transform the string into a **valid** string by inserting the minimum number of parentheses. A string is considered valid if it is empty, contains only balanced parenth... |
from typing import List
def gnome_sort(arr: List[int]) -> List[int]:
index = 0
n = len(arr)
while index < n:
if index + 1 < n and arr[index] > arr[index + 1]:
arr[index], arr[index + 1] = arr[index + 1], arr[index]
index = max(index - 1, 0)
else:
index +=... | simplelr_Data_Structure | [
{
"content": "Question:\n### Gnome Sort Problem\n\n#### Scenario\nYou're working as a software engineer for a company's data management team, and they have tasked you with writing a customized sorting algorithm to sort small but frequently changing datasets efficiently. Based on your expertise, you decided to u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7029,
"level": 1,
"question": "### Gnome Sort Problem\n\n#### Scenario\nYou're working as a software engineer for a company's data management team, and they have tasked you with writing a customized sorting algorithm to sort small but frequently changing datasets efficiently. Based ... |
def find_pairs_with_sum(nums, target):
result = set()
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
a = nums[i]
b = nums[j]
if a > b:
a, b = b, a
result.add((a, ... | simplelr_Apps | [
{
"content": "Question:\n=====Problem Statement=====\nIn this task, you need to write a function that receives a list of integers and an integer target sum. Your function should find all unique pairs of integers in the list that add up to the target sum, and return them as a list of tuples.\n\n=====Input Format... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7030,
"level": 1,
"question": "=====Problem Statement=====\nIn this task, you need to write a function that receives a list of integers and an integer target sum. Your function should find all unique pairs of integers in the list that add up to the target sum, and return them as a l... |
def bubble_sort(lst):
lst_copy = lst.copy()
for i in range(len(lst_copy)):
swapped = False
for j in range(len(lst_copy) - i - 1):
if lst_copy[j] > lst_copy[j + 1]:
lst_copy[j], lst_copy[j + 1] = lst_copy[j + 1], lst_copy[j]
swapped = True
if no... | simplelr_Filter | [
{
"content": "Question:\nCan you provide me with a Python code that sorts a list of numbers in ascending order using the bubble sort algorithm?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7031,
"level": 1,
"question": "Can you provide me with a Python code that sorts a list of numbers in ascending order using the bubble sort algorithm?",
"split": "train"
} |
from urllib.parse import unquote
def decode_url(encoded_str):
return unquote(encoded_str) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to decode a URL-encoded string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7032,
"level": 1,
"question": "Write a function to decode a URL-encoded string.",
"split": "train"
} |
def min_difference(heights, k):
if k == 0:
return 0
sorted_heights = sorted(heights)
min_diff = float('inf')
n = len(sorted_heights)
for i in range(n - k + 1):
current_diff = sorted_heights[i + k - 1] - sorted_heights[i]
if current_diff < min_diff:
min_diff = curr... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `heights` representing the heights of buildings and an integer `k` representing the maximum number of buildings you can paint. Each building can either be painted or left unpainted. Your goal is to paint exactly `k` buildings such that the difference b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7033,
"level": 1,
"question": "You are given an array of integers `heights` representing the heights of buildings and an integer `k` representing the maximum number of buildings you can paint. Each building can either be painted or left unpainted. Your goal is to paint exactly `k` b... |
def factorial_trailing_zeros(n):
"""
Calculate the number of trailing zeros in the factorial of n.
:param n: non-negative integer representing the number to calculate the factorial trailing zeros for.
:return: integer count of trailing zeros in n!
"""
count = 0
base = 5
while n >= b... | simplelr_Apps | [
{
"content": "Question:\n## Factorial Trailing Zeros\n\nComplete the function to calculate the number of trailing zeros in the factorial of a given non-negative integer `n`.\n\nTrailing zeros are the number of zeros at the end of the number (e.g., `25,000` has `3` trailing zeros).\n\n**Examples:**\n```python\nf... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7034,
"level": 1,
"question": "## Factorial Trailing Zeros\n\nComplete the function to calculate the number of trailing zeros in the factorial of a given non-negative integer `n`.\n\nTrailing zeros are the number of zeros at the end of the number (e.g., `25,000` has `3` trailing zer... |
from typing import List
def reconstruct_permutation(encoded: List[int], first: int) -> List[int]:
permutation = [first]
for e in encoded:
next_element = permutation[-1] ^ e
permutation.append(next_element)
return permutation | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement: Reconstruct the Permutation\n\nYou are given an encoded list derived from the original permutation of integers from 0 to n-1 by XORing every two adjacent elements. Your task is to reconstruct the original permutation.\n\n### Function Signature\n```python\ndef reco... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7035,
"level": 1,
"question": "### Problem Statement: Reconstruct the Permutation\n\nYou are given an encoded list derived from the original permutation of integers from 0 to n-1 by XORing every two adjacent elements. Your task is to reconstruct the original permutation.\n\n### Func... |
def reverse_string(s):
return s[::-1] | simplelr_Filter | [
{
"content": "Question:\nThis code snippet defines a function called `reverse_string` which takes a string as input and returns its reversed counterpart.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7036,
"level": 1,
"question": "This code snippet defines a function called `reverse_string` which takes a string as input and returns its reversed counterpart.",
"split": "train"
} |
def build_heads(tuples):
if tuples is None:
return []
return [seq[0] for seq in tuples if seq] | simplelr_Filter | [
{
"content": "Question:\nHere is a Python-related problem I'm experiencing. There's a simple function (`build_heads`) that takes a list of tuples (where each tuple contains two integers), and returns a new list containing only the first element of each tuple. Here's the code I have so far:\n\n```\ndef build_hea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7037,
"level": 1,
"question": "Here is a Python-related problem I'm experiencing. There's a simple function (`build_heads`) that takes a list of tuples (where each tuple contains two integers), and returns a new list containing only the first element of each tuple. Here's the code I... |
def print_reverse(arr):
for i in range(len(arr)-1, -1, -1):
print(arr[i]) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to print the elements of an array in reverse order without creating a new array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7038,
"level": 1,
"question": "Write a function to print the elements of an array in reverse order without creating a new array.",
"split": "train"
} |
def reverse_array(arr):
n = len(arr)
for i in range(n // 2):
j = n - 1 - i
arr[i], arr[j] = arr[j], arr[i]
return arr
| simplelr_Taco | [
{
"content": "Question:\n## Reverse Array in Place\n\nWrite a function called `reverseArray` (Python: `reverse_array`) that takes an array as an argument and reverses the array in place. The function should not create a new array and should instead modify the original array directly.\n\n```if-not:csharp\nThe fu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7039,
"level": 1,
"question": "## Reverse Array in Place\n\nWrite a function called `reverseArray` (Python: `reverse_array`) that takes an array as an argument and reverses the array in place. The function should not create a new array and should instead modify the original array di... |
def generate_fibonacci(n: int) -> list:
fib_list = [0]
if n == 0:
return fib_list
if 1 <= n:
fib_list.append(1)
a, b = 0, 1
while True:
next_num = a + b
if next_num > n:
break
fib_list.append(next_num)
a, b = b, next_num
return fib_list | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question: Generate Fibonacci Sequence Up to a Limit\n\nImagine you are developing a program for a mathematical tool that needs to generate elements in the Fibonacci sequence, but only up to a certain limit for any number provided by the user. The Fibonacci sequence starts wit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7040,
"level": 1,
"question": "### Coding Question: Generate Fibonacci Sequence Up to a Limit\n\nImagine you are developing a program for a mathematical tool that needs to generate elements in the Fibonacci sequence, but only up to a certain limit for any number provided by the user... |
def max_values_from_lists(lst_of_lists):
result = []
for sublist in lst_of_lists:
if not sublist:
result.append(None)
else:
result.append(max(sublist))
return result | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function that takes a list of lists of numbers and returns a new list containing the maximum value from each inner list, but only if the inner list contains numbers; otherwise, it should return `None` for that list.\nAnswer:\nLet's think step by step.\n",
"r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7041,
"level": 1,
"question": "Can you provide a Python function that takes a list of lists of numbers and returns a new list containing the maximum value from each inner list, but only if the inner list contains numbers; otherwise, it should return `None` for that list.",
"split"... |
def hex_to_dec(hex_string):
return int(hex_string, 16) | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that converts a given hexadecimal number to its decimal equivalent?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7042,
"level": 1,
"question": "How can I create a Python function that converts a given hexadecimal number to its decimal equivalent?",
"split": "train"
} |
def remove_duplicates_from_string(s):
seen = set()
result = []
for char in s:
if char not in seen:
seen.add(char)
result.append(char)
return ''.join(result) | simplelr_Filter | [
{
"content": "Question:\nI have a Python code snippet that removes duplicates from a list while preserving the order of elements. How can I modify it to remove duplicates from a string while preserving the order of characters?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7043,
"level": 1,
"question": "I have a Python code snippet that removes duplicates from a list while preserving the order of elements. How can I modify it to remove duplicates from a string while preserving the order of characters?",
"split": "train"
} |
def visible_buildings(heights):
if not heights:
return []
result = [heights[0]]
max_height = heights[0]
for height in heights[1:]:
if height > max_height:
result.append(height)
max_height = height
return result | simplelr_Apps | [
{
"content": "Question:\nIn this challenge, you are given an array of integers representing the heights of N buildings. The buildings are arranged in a straight line and each building has a different height. You can see the buildings from the left side, and you want to know which buildings are visible when view... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7044,
"level": 1,
"question": "In this challenge, you are given an array of integers representing the heights of N buildings. The buildings are arranged in a straight line and each building has a different height. You can see the buildings from the left side, and you want to know wh... |
from typing import List
def winner_of_game(scoring_history: List[str]) -> str:
p1 = 0
p2 = 0
for point in scoring_history:
if point == 'P1':
p1 += 1
else:
p2 += 1
if (p1 >= 4 or p2 >= 4) and abs(p1 - p2) >= 2:
return "Player 1" if p1 > p2 else "Pl... | simplelr_Apps | [
{
"content": "Question:\nComplete the program to determine the winner of a tennis game based on the rules set below. You are provided with a history of scored points as a list of strings either 'P1' or 'P2', indicating which player won each point sequentially.\n\n* Tennis is played in sets and games. A player n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7045,
"level": 1,
"question": "Complete the program to determine the winner of a tennis game based on the rules set below. You are provided with a history of scored points as a list of strings either 'P1' or 'P2', indicating which player won each point sequentially.\n\n* Tennis is p... |
def longest_same_parity_subarray(nums):
if not nums:
return 0
max_length = 1
current_length = 1
prev_parity = nums[0] % 2
for num in nums[1:]:
current_parity = num % 2
if current_parity == prev_parity:
current_length += 1
else:
if current_lengt... | simplelr_Apps | [
{
"content": "Question:\nLara loves solving puzzles, especially ones involving numbers. Today she encountered an interesting problem and needs your help to solve it. Given a list of positive integers, Lara wants to find the length of the longest contiguous subarray where every element in that subarray has the s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7046,
"level": 1,
"question": "Lara loves solving puzzles, especially ones involving numbers. Today she encountered an interesting problem and needs your help to solve it. Given a list of positive integers, Lara wants to find the length of the longest contiguous subarray where every... |
def longest_increasing_subsequence(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp) | simplelr_Apps | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns the length of the longest subsequence in which the numbers are in an increasing order.\n\nFor example:\n\n```\nlongest_increasing_subsequence([10, 22, 9, 33, 21, 50, 41, 60]) => 5\n// The longest increasing subsequence is [10, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7047,
"level": 1,
"question": "Create a function that takes a list of integers and returns the length of the longest subsequence in which the numbers are in an increasing order.\n\nFor example:\n\n```\nlongest_increasing_subsequence([10, 22, 9, 33, 21, 50, 41, 60]) => 5\n// The long... |
from typing import List
def cycle_sort(arr: List[int]) -> List[int]:
n = len(arr)
if n == 0:
return arr
sorted_arr = sorted(arr)
pos_map = {value: idx for idx, value in enumerate(sorted_arr)}
visited = [False] * n
for i in range(n):
if visited[i]:
continue
... | simplelr_Data_Structure | [
{
"content": "Question:\n**Problem Statement:**\n\n**Cycle Sort Implementation**\n\nYou are given an array of distinct integers. Implement the Cycle Sort algorithm to sort this array in-place. Cycle Sort is efficient in terms of space utilization but can have a quadratic time complexity. Your task is to ensure ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7048,
"level": 1,
"question": "**Problem Statement:**\n\n**Cycle Sort Implementation**\n\nYou are given an array of distinct integers. Implement the Cycle Sort algorithm to sort this array in-place. Cycle Sort is efficient in terms of space utilization but can have a quadratic time ... |
def segregate_zeros_and_ones(arr):
write_pointer = 0
for read_pointer in range(len(arr)):
if arr[read_pointer] == 0:
arr[write_pointer], arr[read_pointer] = arr[read_pointer], arr[write_pointer]
write_pointer += 1
return arr | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to segregate 0s and 1s in an array in a single traversal. The function should rearrange the array such that all 0s come before 1s and the order of 0s and 1s should be the same as in the original array as much as possible. The function should work correctly for any size ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7049,
"level": 1,
"question": "Write a function to segregate 0s and 1s in an array in a single traversal. The function should rearrange the array such that all 0s come before 1s and the order of 0s and 1s should be the same as in the original array as much as possible. The function ... |
from typing import List
def product_except_self(nums: List[int]) -> List[int]:
length = len(nums)
answer = [1] * length
left_product = 1
for i in range(length):
answer[i] = left_product
left_product *= nums[i]
right_product = 1
for i in range(length - 1, -1, -1):
answe... | simplelr_Algorithm | [
{
"content": "Question:\n**Question:**\n\n### Array Product Except Self\n\nGiven an integer array `nums`, return an array `answer` such that `answer[i]` is equal to the product of all the elements of `nums` except `nums[i]`.\n\nThe solution must be provided without using division and should have a time complexi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7050,
"level": 1,
"question": "**Question:**\n\n### Array Product Except Self\n\nGiven an integer array `nums`, return an array `answer` such that `answer[i]` is equal to the product of all the elements of `nums` except `nums[i]`.\n\nThe solution must be provided without using divis... |
def letter_frequency_count(s):
freq = {}
for char in s:
lower_char = char.lower()
if lower_char.isalpha():
if lower_char in freq:
freq[lower_char] += 1
else:
freq[lower_char] = 1
return freq | simplelr_Evol | [
{
"content": "Question:\nWrite a function in Python that takes a string as input and returns a dictionary with the frequency count of each letter in the string. The function should be case-insensitive and should ignore non-alphabet characters. \n\nExample input:\n```\n\"The quick brown fox jumps over the lazy d... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7051,
"level": 1,
"question": "Write a function in Python that takes a string as input and returns a dictionary with the frequency count of each letter in the string. The function should be case-insensitive and should ignore non-alphabet characters. \n\nExample input:\n```\n\"The qu... |
def move_zeros_to_end(arr):
non_zero = []
zero_count = 0
for num in arr:
if num != 0:
non_zero.append(num)
else:
zero_count += 1
return non_zero + [0] * zero_count | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that rearranges an array of integers, moving all the zeros in the array to the end while maintaining the relative order of the non-zero elements.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7052,
"level": 1,
"question": "Write a Python function that rearranges an array of integers, moving all the zeros in the array to the end while maintaining the relative order of the non-zero elements.",
"split": "train"
} |
def sum_of_even_digits(n):
total = 0
n_abs = abs(n)
while n_abs > 0:
digit = n_abs % 10
if digit % 2 == 0:
total += digit
n_abs = n_abs // 10
return total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as input and returns the sum of its digits. However, the function should only consider digits that are even. If the number has no even digits, return 0.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7053,
"level": 1,
"question": "Create a function that takes an integer as input and returns the sum of its digits. However, the function should only consider digits that are even. If the number has no even digits, return 0.",
"split": "train"
} |
def min_deletions_to_avoid_consecutive_repeating(s):
a = b = c = 0
for char in s:
if char == 'a':
new_a = max(b, c) + 1
new_b, new_c = b, c
elif char == 'b':
new_b = max(a, c) + 1
new_a, new_c = a, c
else: # char is 'c'
new_c =... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` containing only three types of characters: `'a'`, `'b'`, and `'c'`. Return the minimum number of characters you need to delete from the string so that the string does not contain any consecutive repeating characters.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7054,
"level": 1,
"question": "You are given a string `s` containing only three types of characters: `'a'`, `'b'`, and `'c'`. Return the minimum number of characters you need to delete from the string so that the string does not contain any consecutive repeating characters.",
"spl... |
def get_permutations(s):
if len(s) == 0:
return ['']
result = []
first = s[0]
rest = s[1:]
for p in get_permutations(rest):
for i in range(len(p) + 1):
result.append(p[:i] + first + p[i:])
return result
# Example usage
print(get_permutations('abc')) | simplelr_Filter | [
{
"content": "Question:\nHere's a problem that I just thought of: create a function that takes a string input, and returns all permutations of that string in a list. \n\nExample input: 'abc'\nExample output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']\n\nHere's a backtracking solution I came up with:\n```python\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7055,
"level": 1,
"question": "Here's a problem that I just thought of: create a function that takes a string input, and returns all permutations of that string in a list. \n\nExample input: 'abc'\nExample output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']\n\nHere's a backtracking s... |
def filter_long_strings(strings):
return [s for s in strings if len(s) > 5] | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that takes a list of strings and returns a new list containing only the strings that have a length greater than 5 characters?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7056,
"level": 1,
"question": "How can I create a Python function that takes a list of strings and returns a new list containing only the strings that have a length greater than 5 characters?",
"split": "train"
} |
def remove_chars_not_in_second(str1, str2):
excluded = set(str2)
return ''.join([c for c in str1 if c not in excluded]) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that returns a string containing all characters from the first string that are not present in the second string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7057,
"level": 1,
"question": "Create a function that returns a string containing all characters from the first string that are not present in the second string.",
"split": "train"
} |
def num_decodings(s: str) -> int:
n = len(s)
dp = [0] * (n + 1)
dp[0] = 1 # Base case: empty string has one way to decode
for i in range(1, n + 1):
res = 0
# Check single digit
if i - 1 >= 0:
one = s[i-1]
if one != '0':
res +... | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem: Ways to Decode\n\nYou are provided with an encoded message containing only digits. Each digit maps to a letter ('A' to 'Z') where 'A' maps to '1', 'B' to '2', ..., and 'Z' to '26'. You need to write a function that determines the total number of ways to decode this message.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7058,
"level": 1,
"question": "### Problem: Ways to Decode\n\nYou are provided with an encoded message containing only digits. Each digit maps to a letter ('A' to 'Z') where 'A' maps to '1', 'B' to '2', ..., and 'Z' to '26'. You need to write a function that determines the total num... |
def list_intersection(list1, list2):
in_list1 = {}
for elem in list1:
if elem not in in_list1:
in_list1[elem] = True
result = []
for elem in list2:
if elem in in_list1 and elem not in result:
result.append(elem)
return result | simplelr_Evol | [
{
"content": "Question:\nCreate a Python function that finds the intersection of two given lists without using any built-in set operations. The function should return a list containing unique elements that appear in both input lists. Ensure that the order of elements in the result list is the same as their firs... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7059,
"level": 1,
"question": "Create a Python function that finds the intersection of two given lists without using any built-in set operations. The function should return a list containing unique elements that appear in both input lists. Ensure that the order of elements in the re... |
import bisect
def contains_nearby_duplicate(nums, k):
pos_dict = {}
for i, num in enumerate(nums):
if num in pos_dict:
indices = pos_dict[num]
target = i - k
# Find the first index in indices >= target
j = bisect.bisect_left(indices, target)
i... | simplelr_Apps | [
{
"content": "Question:\nGiven an integer array nums and an integer k, determine whether the array contains any duplicates within k indices of each other.\n\nExample 1:\nInput: nums = [1, 2, 3, 1], k = 3\nOutput: true\nExplanation: The element nums[3] is a duplicate of nums[0], and they are at most 3 indices ap... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7060,
"level": 1,
"question": "Given an integer array nums and an integer k, determine whether the array contains any duplicates within k indices of each other.\n\nExample 1:\nInput: nums = [1, 2, 3, 1], k = 3\nOutput: true\nExplanation: The element nums[3] is a duplicate of nums[0]... |
def process_files(input_text_file: str, input_binary_file: str, output_text_file: str, output_binary_file: str, encoding='utf-8') -> None:
# Read input text file
text_content = None
try:
with open(input_text_file, 'r', encoding=encoding, errors='replace') as text_file:
text_content = tex... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nTo assess a student's understanding of text and binary I/O operations using Python's `io` module, including text encoding, buffering, and handling different I/O streams.\n\n#### Problem Statement:\nYou are required to write a function `process_files(input_text_file: str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7061,
"level": 1,
"question": "#### Objective:\nTo assess a student's understanding of text and binary I/O operations using Python's `io` module, including text encoding, buffering, and handling different I/O streams.\n\n#### Problem Statement:\nYou are required to write a function ... |
from collections import Counter
def is_anagram_of_palindrome(s):
counts = Counter(s)
odd_count = 0
for count in counts.values():
if count % 2 != 0:
odd_count += 1
if odd_count > 1:
return False
return True | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to detect if a string is an anagram of a palindrome. Return true if it is, and false otherwise. A palindrome is a string that reads the same backward as forward. An anagram is a permutation of a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7062,
"level": 1,
"question": "Write a function to detect if a string is an anagram of a palindrome. Return true if it is, and false otherwise. A palindrome is a string that reads the same backward as forward. An anagram is a permutation of a string.",
"split": "train"
} |
def coupon_combinations(nums, target):
if target < 0:
return 0
dp = [0] * (target + 1)
dp[0] = 1 # Base case: one way to make sum zero (using no coupons)
for i in range(1, target + 1):
for num in nums:
if num <= i:
dp[i] += dp[i - num]
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nImagine you are designing an e-commerce website where users can combine different discount coupons to reach a specific target discount value. You need to develop a function that will count all possible combinations of given coupon values that sum up to the target discount ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7063,
"level": 1,
"question": "### Scenario\nImagine you are designing an e-commerce website where users can combine different discount coupons to reach a specific target discount value. You need to develop a function that will count all possible combinations of given coupon values ... |
def int_to_roman(num):
roman_numerals = [
(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')
]
result = ''
for value, symbol in roman_numerals:
while num >= value:
... | simplelr_Apps | [
{
"content": "Question:\nImplement a function that takes a positive integer and returns a string representing the number in Roman numerals. The function should adhere to the following conventions:\n\n+ Roman numerals are represented by the following symbols: I, V, X, L, C, D, M.\n+ Numbers are formed by combini... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7064,
"level": 1,
"question": "Implement a function that takes a positive integer and returns a string representing the number in Roman numerals. The function should adhere to the following conventions:\n\n+ Roman numerals are represented by the following symbols: I, V, X, L, C, D, ... |
def edit_distance(word_a, word_b):
n = len(word_a)
m = len(word_b)
dp = [[0] * (m + 1) for _ in range(n + 1)]
# Initialize the first row and column
for i in range(n + 1):
dp[i][0] = i
for j in range(m + 1):
dp[0][j] = j
# Fill the DP table
for i in range(1, n + ... | simplelr_Data_Structure | [
{
"content": "Question:\n### Edit Distance Calculation\n\nYou are given two words, `word_a` and `word_b`. The task is to write a function `edit_distance(word_a, word_b)` that calculates the minimum number of operations (insertions, deletions, or substitutions) required to transform `word_a` into `word_b`. This ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7065,
"level": 1,
"question": "### Edit Distance Calculation\n\nYou are given two words, `word_a` and `word_b`. The task is to write a function `edit_distance(word_a, word_b)` that calculates the minimum number of operations (insertions, deletions, or substitutions) required to tran... |
def minimize_max_water(arr):
total = sum(arr)
n = len(arr)
return (total + n - 1) // n | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` representing the amount of water in `n` glasses positioned in a line. You can perform a series of operations to balance the water levels. In one operation, you can choose any glass and pour water from it into the adjacent (left or right) glass. E... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7066,
"level": 1,
"question": "You are given an array of integers `arr` representing the amount of water in `n` glasses positioned in a line. You can perform a series of operations to balance the water levels. In one operation, you can choose any glass and pour water from it into th... |
def is_palindrome(s):
# Process the string to include only alphanumeric characters and convert to lowercase
s_processed = ''.join([c.lower() for c in s if c.isalnum()])
# Check if the processed string is a palindrome
is_pali = s_processed == s_processed[::-1]
# Reverse the original string
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to determine if a given string is a palindrome, considering only alphanumeric characters and ignoring cases. Additionally, modify the function to also check if the string, when reversed, forms a new palindrome. Return `True` if both conditions are met, and `False... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7067,
"level": 1,
"question": "Write a Python function to determine if a given string is a palindrome, considering only alphanumeric characters and ignoring cases. Additionally, modify the function to also check if the string, when reversed, forms a new palindrome. Return `True` if ... |
def levenshtein_distance(s1, s2):
"""
Calculate the Levenshtein distance between two strings using dynamic programming with space optimization.
Args:
s1 (str): The first string.
s2 (str): The second string.
Returns:
int: The Levenshtein distance between s1 and s2.
"... | simplelr_Filter | [
{
"content": "Question:\nHow can I efficiently calculate the Levenshtein distance between two strings in Python, considering performance and ease of implementation? Additionally, could you provide a brief explanation of what Levenshtein distance is and its common applications?\nAnswer:\nLet's think step by step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7068,
"level": 1,
"question": "How can I efficiently calculate the Levenshtein distance between two strings in Python, considering performance and ease of implementation? Additionally, could you provide a brief explanation of what Levenshtein distance is and its common applications?... |
def transitive_closure(vertices, edges):
# Create adjacency list
adj = [[] for _ in range(vertices)]
for u, v in edges:
adj[u].append(v)
# Initialize transitive closure matrix with False
trans = [[0 for _ in range(vertices)] for _ in range(vertices)]
for i in range(vertices):
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Transitive Closure of a Directed Graph\n\nYou are given a directed graph represented by an adjacency list. Your task is to compute the transitive closure of this graph. The transitive closure of a graph is a reachability matrix where the element at row `i` and column `j` is `1` if t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7069,
"level": 1,
"question": "### Transitive Closure of a Directed Graph\n\nYou are given a directed graph represented by an adjacency list. Your task is to compute the transitive closure of this graph. The transitive closure of a graph is a reachability matrix where the element at... |
def difference(num1, num2):
return num1 - num2 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the difference between two numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7070,
"level": 1,
"question": "Create a function that calculates the difference between two numbers.",
"split": "train"
} |
from collections import deque
from typing import List
def can_finish_courses(num_courses: int, prerequisites: List[List[int]]) -> bool:
# Initialize adjacency list and in-degree array
adj = [[] for _ in range(num_courses)]
in_degree = [0] * num_courses
# Build the adjacency list and in-degree arra... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\n#### Course Schedule Validator Using Topological Sorting\n\nYou are given a list of courses and their prerequisites. Implement a function that checks if it is possible to complete all courses without conflicting dependencies (i.e., there are no cycles in the prerequisite... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7071,
"level": 1,
"question": "### Question\n\n#### Course Schedule Validator Using Topological Sorting\n\nYou are given a list of courses and their prerequisites. Implement a function that checks if it is possible to complete all courses without conflicting dependencies (i.e., ther... |
def find_largest(num1, num2):
return max(num1, num2) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the largest of two numbers using the `max` function.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7072,
"level": 1,
"question": "Write a function to find the largest of two numbers using the `max` function.",
"split": "train"
} |
def min_boxes(X, Y, Z, N):
min_total = float('inf')
max_c = N // Z
for c in range(0, max_c + 1):
rem = N - c * Z
if rem < 0:
break
b_max = rem // Y
for b in range(b_max, -1, -1):
rem2 = rem - b * Y
if rem2 < 0:
continue
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an infinite number of boxes in 3 different sizes: small, medium, and large. A small box can hold `X` units, a medium box can hold `Y` units, and a large box can hold `Z` units. Write a function that determines the minimum number of boxes required to exactly fit a given num... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7073,
"level": 1,
"question": "You are given an infinite number of boxes in 3 different sizes: small, medium, and large. A small box can hold `X` units, a medium box can hold `Y` units, and a large box can hold `Z` units. Write a function that determines the minimum number of boxes ... |
def is_palindrome(word):
filtered_word = ''.join([c.lower() for c in word if c.isalnum()])
return filtered_word == filtered_word[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given word is a palindrome. A palindrome is a word that reads the same backward as forward, e.g., \"madam\" or \"racecar\". Your function should ignore spaces, punctuation, and capitalization when determining if a word is a palindrome.\nAnswer:\nLet's thin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7074,
"level": 1,
"question": "Write a function to check if a given word is a palindrome. A palindrome is a word that reads the same backward as forward, e.g., \"madam\" or \"racecar\". Your function should ignore spaces, punctuation, and capitalization when determining if a word is... |
from collections import defaultdict
def find_pairs(A, N, K):
freq = defaultdict(int)
result = []
for num in A:
complement = K - num
result.extend([(complement, num)] * freq[complement])
freq[num] += 1
return result
| simplelr_Taco | [
{
"content": "Question:\nGiven an unsorted array A[] of size N, find all the pairs of elements in the array that sum up to a given target value K. Print the pairs of elements in the format (A[i], A[j]), where A[i] and A[j] are the elements of the pair, and i < j.\n\nExample 1:\nInput:\nN = 5\nArray = {1, 5, 7, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7075,
"level": 1,
"question": "Given an unsorted array A[] of size N, find all the pairs of elements in the array that sum up to a given target value K. Print the pairs of elements in the format (A[i], A[j]), where A[i] and A[j] are the elements of the pair, and i < j.\n\nExample 1:... |
import pandas as pd
import numpy as np
def clean_dataframe(df: pd.DataFrame) -> pd.DataFrame:
"""
This function processes a DataFrame by handling missing values according to specific rules.
Steps:
1. Drops columns with more than 50% missing values.
2. For the remaining columns:
- Numeri... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nDesign a function named `clean_dataframe` that processes a given pandas DataFrame by handling its missing values (both `NA` and `NaT`).\n\n#### Function Signature:\n```python\ndef clean_dataframe(df: pd.DataFrame) -> pd.DataFrame:\n```\n\n#### Inputs:\n* `df` (pd.DataFr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7076,
"level": 1,
"question": "#### Objective:\nDesign a function named `clean_dataframe` that processes a given pandas DataFrame by handling its missing values (both `NA` and `NaT`).\n\n#### Function Signature:\n```python\ndef clean_dataframe(df: pd.DataFrame) -> pd.DataFrame:\n```... |
def increment_subgrid(m, n, operations):
# Initialize the grid with all zeros
grid = [[0 for _ in range(n)] for _ in range(m)]
# Process each operation
for op in operations:
r1, c1, r2, c2 = op
# Convert to 0-based and adjust ranges
for i in range(r1 - 1, r2):
fo... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a grid with m rows and n columns, initially filled with zeros. You need to perform a series of operations, each represented by a triple (r1, c1, r2, c2), where (r1, c1) represents the top-left cell and (r2, c2) represents the bottom-right cell of a subgrid. For each operat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7077,
"level": 1,
"question": "You are given a grid with m rows and n columns, initially filled with zeros. You need to perform a series of operations, each represented by a triple (r1, c1, r2, c2), where (r1, c1) represents the top-left cell and (r2, c2) represents the bottom-right... |
def contains_substring(main_string, sub_string):
return sub_string in main_string | simplelr_Filter | [
{
"content": "Question:\nCan you provide an example of a Python function that checks for the presence of a specific substring in a given string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7078,
"level": 1,
"question": "Can you provide an example of a Python function that checks for the presence of a specific substring in a given string?",
"split": "train"
} |
def length_of_longest_substring(s):
last_occurrence = {}
max_length = 0
start = 0
for end in range(len(s)):
char = s[end]
if char in last_occurrence and last_occurrence[char] >= start:
start = last_occurrence[char] + 1
last_occurrence[char] = end
current_lengt... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s`, write a function to find the length of the longest substring without repeating characters. The function should return an integer representing the maximum length of such a substring.\n\n**Example:**\nInput: `s = \"abcabcbb\"`\nOutput: `3`\nExplanation: The answer is `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7079,
"level": 1,
"question": "Given a string `s`, write a function to find the length of the longest substring without repeating characters. The function should return an integer representing the maximum length of such a substring.\n\n**Example:**\nInput: `s = \"abcabcbb\"`\nOutput... |
from itertools import product
def generate_permutations(s: str) -> list[str]:
parts = []
for c in s:
if c.isdigit():
letters = [chr(ord('a') + i) for i in range(26)]
parts.append(letters)
else:
parts.append([c])
all_perms = product(*parts)
return [''.... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are given a string consisting of lowercase alphabets and integers. Your task is to write a function to generate all possible strings by replacing each integer in the original string with all lowercase alphabets. For each integer in the string, you need to repl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7080,
"level": 1,
"question": "### Problem Statement\nYou are given a string consisting of lowercase alphabets and integers. Your task is to write a function to generate all possible strings by replacing each integer in the original string with all lowercase alphabets. For each inte... |
import ast
def interpret_code(file_path: str) -> list:
global_namespace = {}
results = []
with open(file_path, 'r') as file:
for line in file:
stripped_line = line.strip()
if not stripped_line:
continue
is_expression = False
try:
... | simplelr_Docs | [
{
"content": "Question:\n**Problem Statement:**\n\nYou are responsible for creating a simple Python interpreter emulator that can read code from a file and execute it. Your task includes handling both expression inputs using `eval()` and complete statements using `exec()`.\n\n### Input\nYou will be provided wit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7081,
"level": 1,
"question": "**Problem Statement:**\n\nYou are responsible for creating a simple Python interpreter emulator that can read code from a file and execute it. Your task includes handling both expression inputs using `eval()` and complete statements using `exec()`.\n\n... |
def count_subsequences(nums, target):
dp = {0: 1}
for num in nums:
# Create a copy of current dp items to iterate over
current = list(dp.items())
for s, cnt in current:
new_s = s + num
if new_s in dp:
dp[new_s] += cnt
else:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums` and an integer `target`, return _the number of non-empty **subsequences** of `nums` that sum to `target`_. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. \n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7082,
"level": 1,
"question": "Given an integer array `nums` and an integer `target`, return _the number of non-empty **subsequences** of `nums` that sum to `target`_. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the ... |
def book_tickets(available_seats, requests, partial=False):
results = []
current_available = available_seats
for req in requests:
if req <= current_available:
results.append(req)
current_available -= req
else:
if partial:
if current_availab... | simplelr_Apps | [
{
"content": "Question:\nCreate a function that simulates a simple train ticket booking system. \n\nYou need to implement a function that takes three arguments: the number of available seats, a list of requests (each request is a positive integer representing the number of seats requested), and an optional argu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7083,
"level": 1,
"question": "Create a function that simulates a simple train ticket booking system. \n\nYou need to implement a function that takes three arguments: the number of available seats, a list of requests (each request is a positive integer representing the number of sea... |
def max_subarray_sum(arr):
if not arr:
return 0 # or raise ValueError("Array is empty")
max_current = max_global = arr[0]
for num in arr[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that calculates the maximum sum of a subarray within a given array of integers. This is known as the maximum subarray problem. The function should return the maximum sum found.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7084,
"level": 1,
"question": "Write a Python function that calculates the maximum sum of a subarray within a given array of integers. This is known as the maximum subarray problem. The function should return the maximum sum found.",
"split": "train"
} |
import bisect
def length_of_lis(nums):
tails = []
for num in nums:
index = bisect.bisect_left(tails, num)
if index == len(tails):
tails.append(num)
else:
tails[index] = num
return len(tails) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the length of the longest increasing subsequence (LIS) in a given list of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7085,
"level": 1,
"question": "Write a function to find the length of the longest increasing subsequence (LIS) in a given list of integers.",
"split": "train"
} |
from collections import Counter
def minStepsToAnagram(str1, str2):
count1 = Counter(str1)
count2 = Counter(str2)
common = 0
for c in 'abcdefghijklmnopqrstuvwxyz':
common += min(count1.get(c, 0), count2.get(c, 0))
return (len(str1) + len(str2) - 2 * common)
| simplelr_Taco | [
{
"content": "Question:\nFind the minimum number of steps required to make two strings anagrams of each other. In one step, you can insert a character into, delete a character from, or replace a character in either of the strings. \n\nExample 1:\nInput: str1 = \"abc\", str2 = \"bcf\"\nOutput: 2\nExplanation: Re... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7086,
"level": 1,
"question": "Find the minimum number of steps required to make two strings anagrams of each other. In one step, you can insert a character into, delete a character from, or replace a character in either of the strings. \n\nExample 1:\nInput: str1 = \"abc\", str2 = ... |
def linear_search(array, target):
for index in range(len(array)):
if array[index] == target:
return index
return -1 | simplelr_Filter | [
{
"content": "Question:\nWrite a code for linear search algorithm that returns the index of the first occurrence of the target element in the given array. The array can contain duplicate elements. The code should have a time complexity of O(n) and should not use any built-in search functions or data structures.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7087,
"level": 1,
"question": "Write a code for linear search algorithm that returns the index of the first occurrence of the target element in the given array. The array can contain duplicate elements. The code should have a time complexity of O(n) and should not use any built-in s... |
def next_bigger(num: int) -> int:
digits = list(str(num))
n = len(digits)
pivot = -1
# Step 1: Find the pivot
for i in range(n - 2, -1, -1):
if digits[i] < digits[i + 1]:
pivot = i
break
if pivot == -1:
return -1
# Step 2: Find the smallest digit to... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\n\nGiven a number, find the next higher number which has the exact same set of digits as the original number. If no such number exists, return `-1`.\n\n#### Function Signature\n```python\ndef next_bigger(num: int) -> int:\n```\n\n#### Input\n* A single integer, `num`, where... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7088,
"level": 1,
"question": "### Question\n\nGiven a number, find the next higher number which has the exact same set of digits as the original number. If no such number exists, return `-1`.\n\n#### Function Signature\n```python\ndef next_bigger(num: int) -> int:\n```\n\n#### Inpu... |
def convert(s, numRows):
if numRows == 1:
return s
rows = [''] * numRows
current_row = 0
step = 1 # 1 for down, -1 for up
for char in s:
rows[current_row] += char
if current_row == 0:
step = 1
elif current_row == numRows - 1:
step = -1
... | simplelr_Apps | [
{
"content": "Question:\npuzzle: Create a function that generates a \"zig-zag\" pattern from a given string and an integer representing the number of rows.\n\nIn this pattern, characters are written out in a zig-zag fashion on separate lines and then concatenated together in order.\n\nFor example, given the str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7089,
"level": 1,
"question": "puzzle: Create a function that generates a \"zig-zag\" pattern from a given string and an integer representing the number of rows.\n\nIn this pattern, characters are written out in a zig-zag fashion on separate lines and then concatenated together in o... |
def number_of_digits(n: int) -> int:
if n == 0:
return 1
high = 1
current = 10
while current <= n:
current *= 10
high += 1
return high | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with creating a utility function that determines the number of digits in a given non-negative integer. Given how critical performance can be, your solution should ensure constant time complexity.\n\n**Function Signature**\n```python\ndef number_of_digits(n: int) -> int:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7090,
"level": 1,
"question": "You are tasked with creating a utility function that determines the number of digits in a given non-negative integer. Given how critical performance can be, your solution should ensure constant time complexity.\n\n**Function Signature**\n```python\ndef... |
def merge_sorted_arrays(ar1, ar2):
i = j = 0
result = []
while i < len(ar1) and j < len(ar2):
if ar1[i] <= ar2[j]:
result.append(ar1[i])
i += 1
else:
result.append(ar2[j])
j += 1
# Extend the result with the remaining elements of ar1 or ar2... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to merge two sorted arrays into a single sorted array. The function should take two lists of integers as input and return a new list that is sorted in non-decreasing order. You should not modify the original lists.\nAnswer:\nLet's think step by step.\n",
"rol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7091,
"level": 1,
"question": "Write a python function to merge two sorted arrays into a single sorted array. The function should take two lists of integers as input and return a new list that is sorted in non-decreasing order. You should not modify the original lists.",
"split": ... |
def sum_even_odd(arr):
even_sum = 0
odd_sum = 0
for num in arr:
if num % 2 == 0:
even_sum += num
else:
odd_sum += num
return (even_sum, odd_sum) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the sum of all even numbers and the sum of all odd numbers in an array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7092,
"level": 1,
"question": "Write a python function to find the sum of all even numbers and the sum of all odd numbers in an array.",
"split": "train"
} |
import itertools
def generate_combinations(s):
result = []
n = len(s)
for i in range(1, n + 1):
for combo in itertools.combinations(s, i):
result.append(''.join(combo))
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that generates all possible combinations of a given string's characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7093,
"level": 1,
"question": "Create a function that generates all possible combinations of a given string's characters.",
"split": "train"
} |
def find_kth_largest(arr, k):
sorted_arr = sorted(arr, reverse=True)
return sorted_arr[k-1] | simplelr_Algorithm | [
{
"content": "Question:\n### Find the Kth Largest Element in an Array\n\nYou are required to find the Kth largest element in an array, where K is a given positive integer. The array may contain duplicate elements and it is guaranteed that the value of K is valid (i.e., 1 ≤ K ≤ array's length).\n\n**Input**:\n- ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7094,
"level": 1,
"question": "### Find the Kth Largest Element in an Array\n\nYou are required to find the Kth largest element in an array, where K is a given positive integer. The array may contain duplicate elements and it is guaranteed that the value of K is valid (i.e., 1 ≤ K ≤... |
def max_subarray_sum(arr):
if not arr:
return 0
max_current = max_global = arr[0]
for num in arr[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that identifies the maximum sum of a subarray within a given array. The function should return this maximum sum. For example, given the array `[-2, 1, -3, 4, -1, 2, 1, -5, 4]`, the subarray with the largest sum is `[4, -1, 2, 1]`, which sums to `6`.\nAnswer:\nLet's thi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7095,
"level": 1,
"question": "Create a function that identifies the maximum sum of a subarray within a given array. The function should return this maximum sum. For example, given the array `[-2, 1, -3, 4, -1, 2, 1, -5, 4]`, the subarray with the largest sum is `[4, -1, 2, 1]`, whi... |
def fizz_buzz(n):
result = []
for i in range(1, n + 1):
if i % 15 == 0:
result.append('FizzBuzz')
elif i % 3 == 0:
result.append('Fizz')
elif i % 5 == 0:
result.append('Buzz')
else:
result.append(i)
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as input and returns a list of all the integers from 1 to the input integer (inclusive). However, if a number is divisible by 3, replace it with 'Fizz', and if a number is divisible by 5, replace it with 'Buzz'. If a number is divisible by both 3 ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7096,
"level": 1,
"question": "Create a function that takes an integer as input and returns a list of all the integers from 1 to the input integer (inclusive). However, if a number is divisible by 3, replace it with 'Fizz', and if a number is divisible by 5, replace it with 'Buzz'. ... |
from sklearn.isotonic import IsotonicRegression
from sklearn.metrics import mean_squared_error
def isotonic_regression_example(X_train: list, y_train: list, X_test: list, y_test: list) -> float:
"""
Fits an isotonic regression model to the training data and evaluates it on the test data.
Parameters:
... | simplelr_Docs | [
{
"content": "Question:\n**Objective:**\nImplement an example usage of the `IsotonicRegression` class from the scikit-learn library. The task involves fitting the model to given training data, making predictions on test data, and evaluating the model's performance.\n\n**Problem Statement:**\nGiven the following... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7097,
"level": 1,
"question": "**Objective:**\nImplement an example usage of the `IsotonicRegression` class from the scikit-learn library. The task involves fitting the model to given training data, making predictions on test data, and evaluating the model's performance.\n\n**Proble... |
def max_consecutive_sum(lst, k):
n = len(lst)
if n < k:
return 0
current_sum = sum(lst[:k])
max_sum = current_sum
for i in range(k, n):
current_sum = current_sum - lst[i - k] + lst[i]
if current_sum > max_sum:
max_sum = current_sum
return max_sum
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of integers and an integer `k` and returns the maximum sum of `k` consecutive elements in the list. If there are fewer than `k` elements in the list, the function should return 0.\n\nExample 1:\nInput: lst = [1, 2, 3, 4, 5], k = 2\nOutput: 9\nExplanati... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7098,
"level": 1,
"question": "Write a function that takes a list of integers and an integer `k` and returns the maximum sum of `k` consecutive elements in the list. If there are fewer than `k` elements in the list, the function should return 0.\n\nExample 1:\nInput: lst = [1, 2, 3,... |
def words_to_lengths(words):
return {word: len(word) for word in words} | simplelr_Package | [
{
"content": "Question:\nYou need to write a Python function that generates a dictionary from a given list of words where the keys are the words and the values are the lengths of those words. The function will make use of list comprehensions and dictionary comprehensions.\n\n**Function Specifications:**\n\n- **... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7099,
"level": 1,
"question": "You need to write a Python function that generates a dictionary from a given list of words where the keys are the words and the values are the lengths of those words. The function will make use of list comprehensions and dictionary comprehensions.\n\n*... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.