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 byte_array_to_char(byte_array):
return bytes(byte_array).decode('utf-8') | simplelr_Filter | [
{
"content": "Question:\nFollowing byte string represents an uppercase letter. Given a byte string, which represents an uppercase English alphabet character, your task is to determine what that letter is. The byte string is provided in the form of an array of integers, where each integer corresponds to a byte o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4000,
"level": 1,
"question": "Following byte string represents an uppercase letter. Given a byte string, which represents an uppercase English alphabet character, your task is to determine what that letter is. The byte string is provided in the form of an array of integers, where e... |
from typing import List, Dict
import fnmatch
def match_filenames(filenames: List[str], patterns: List[str]) -> Dict[str, Dict[str, List[str]]]:
all_lower_filenames = [fn.lower() for fn in filenames]
result = {}
for pattern in patterns:
case_insensitive = []
case_sensitive = []
lower... | simplelr_Docs | [
{
"content": "Question:\nAdvanced Filename Matching\n\nIn this exercise, you will implement a function that takes a list of filenames and a list of patterns, and returns a dictionary summarizing which filenames match each pattern using both case-insensitive and case-sensitive matching. \n\nYour task is to imple... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4001,
"level": 1,
"question": "Advanced Filename Matching\n\nIn this exercise, you will implement a function that takes a list of filenames and a list of patterns, and returns a dictionary summarizing which filenames match each pattern using both case-insensitive and case-sensitive ... |
def abs_diff(a, b):
return abs(a - b) | simplelr_Filter | [
{
"content": "Question:\nI will give you a list of functions to implement. For this response, I will give you two integers, and I want you to create a function that takes two integers as parameters and returns the absolute difference between them.\n\nHere is the function definition: \ndef abs_diff(a, b):\n #... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4002,
"level": 1,
"question": "I will give you a list of functions to implement. For this response, I will give you two integers, and I want you to create a function that takes two integers as parameters and returns the absolute difference between them.\n\nHere is the function defin... |
def calculate_average_height(person_data: list[tuple[str, int, float]]) -> dict[int, float]:
age_heights = {}
for person in person_data:
name, age, height = person
if age not in age_heights:
age_heights[age] = []
age_heights[age].append(height)
average_heights = {}
... | simplelr_Package | [
{
"content": "Question:\nYou are given a list of tuples, where each tuple contains three elements: a string representing a person's name, an integer representing their age, and a floating-point number representing their height in meters. Your task is to write a function named `calculate_average_height` that tak... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4003,
"level": 1,
"question": "You are given a list of tuples, where each tuple contains three elements: a string representing a person's name, an integer representing their age, and a floating-point number representing their height in meters. Your task is to write a function named ... |
def bubble_sort(arr):
arr_copy = arr.copy()
n = len(arr_copy)
swap_count = 0
for i in range(n - 1):
swapped = False
for j in range(n - i - 1):
if arr_copy[j] > arr_copy[j + 1]:
# Swap elements
arr_copy[j], arr_copy[j + 1] = arr_copy[j + 1], arr... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to sort an array using the bubble sort algorithm and also count the number of swaps made during the sorting process.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4004,
"level": 1,
"question": "Write a python function to sort an array using the bubble sort algorithm and also count the number of swaps made during the sorting process.",
"split": "train"
} |
def generate_multiplication_table(num, limit):
lines = [f"{num} * {m} = {num * m}" for m in range(1, limit + 1)]
return '\n'.join(lines) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to generate a multiplication table for a given number up to a specified limit. The function should take two arguments: the number for which the table is to be generated and the limit up to which the multiplication should be performed. The output should be a neatl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4005,
"level": 1,
"question": "Write a Python function to generate a multiplication table for a given number up to a specified limit. The function should take two arguments: the number for which the table is to be generated and the limit up to which the multiplication should be perf... |
def find_min_max(filename):
"""
Reads a sequence of integers from a file and finds the smallest and largest integers.
Args:
filename: The name of the file containing the integers.
Returns:
A tuple containing the smallest and largest integers, respectively.
"""
min_integer = flo... | simplelr_Filter | [
{
"content": "Question:\nThe problem statement is as follows :\n\n**Problem Statement:** Design a program that reads a sequence of integers from a file named “numbers.txt” and determines the smallest and largest integers in the sequence. \n**Constraints:**\n\n- The input file “numbers.txt” will contain one inte... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4006,
"level": 1,
"question": "The problem statement is as follows :\n\n**Problem Statement:** Design a program that reads a sequence of integers from a file named “numbers.txt” and determines the smallest and largest integers in the sequence. \n**Constraints:**\n\n- The input file ... |
from collections import Counter
def find_duplicates(lst):
counts = Counter(lst)
duplicates = [num for num, count in counts.items() if count >= 2]
duplicates.sort()
return duplicates | simplelr_Apps | [
{
"content": "Question:\n## Task\n\nYou have to write a function **find_duplicates** which takes a list of integers and returns another list containing the duplicates from the list, sorted in ascending order.\n\n### Rules/Note:\n* If there are no duplicates, return an empty list.\n* The input list can contain n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4007,
"level": 1,
"question": "## Task\n\nYou have to write a function **find_duplicates** which takes a list of integers and returns another list containing the duplicates from the list, sorted in ascending order.\n\n### Rules/Note:\n* If there are no duplicates, return an empty li... |
def is_increasing_order(s):
times = s.split()
if not times:
return True
prev = 0
for time in times:
hh, mm = time.split(':')
current = int(hh) * 60 + int(mm)
if current <= prev:
return False
prev = current
return True
| simplelr_Taco | [
{
"content": "Question:\nYou receive some event timestamps as a space-delimited string. Each timestamp is in the \"HH:MM\" format. Verify if all the timestamps are in strictly increasing order.\n\nReturn:\n\n* `True` if all timestamps are in strictly increasing order.\n* `False` if there is any timestamp that i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4008,
"level": 1,
"question": "You receive some event timestamps as a space-delimited string. Each timestamp is in the \"HH:MM\" format. Verify if all the timestamps are in strictly increasing order.\n\nReturn:\n\n* `True` if all timestamps are in strictly increasing order.\n* `Fals... |
def decimal_to_binary(n):
if n == 0:
return ("0", 0, 1)
binary_digits = []
count_1 = 0
count_0 = 0
while n > 0:
remainder = n % 2
binary_digits.append(remainder)
if remainder == 1:
count_1 += 1
else:
count_0 += 1
n = n... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that converts a decimal number to binary using the division by 2 method. The function should take an integer as input and return the binary number as a string. In addition, the function should also return the number of 1s and 0s in the binary representation.\nAnswer:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4009,
"level": 1,
"question": "Create a function that converts a decimal number to binary using the division by 2 method. The function should take an integer as input and return the binary number as a string. In addition, the function should also return the number of 1s and 0s in th... |
def highest_grades(students_grades):
student_dict = {}
for name, grade in students_grades:
if name in student_dict:
if grade > student_dict[name]:
student_dict[name] = grade
else:
student_dict[name] = grade
return student_dict
students_grades = [("Joh... | simplelr_Evol | [
{
"content": "Question:\nCreate a Python function that takes a list of tuples, where each tuple contains a student's name and their grade, and returns a dictionary that maps each student's name to their highest grade. If a student's name appears more than once in the list, you should only store the highest grad... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4010,
"level": 1,
"question": "Create a Python function that takes a list of tuples, where each tuple contains a student's name and their grade, and returns a dictionary that maps each student's name to their highest grade. If a student's name appears more than once in the list, you... |
def max_appointments(D, appointments):
# Sort the appointments based on their end times
appointments.sort(key=lambda x: x[1])
count = 0
current_end = 0
for appt in appointments:
if appt[0] >= current_end:
count += 1
current_end = appt[1]
return count | simplelr_Algorithm | [
{
"content": "Question:\n***Appointment Scheduling Problem***\n\n### Context\nYou are responsible for managing appointment schedules in a busy clinic. Each appointment has a specific duration, and you aim to maximize the number of appointments that can be scheduled without any overlaps, given the available time... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4011,
"level": 1,
"question": "***Appointment Scheduling Problem***\n\n### Context\nYou are responsible for managing appointment schedules in a busy clinic. Each appointment has a specific duration, and you aim to maximize the number of appointments that can be scheduled without any... |
def most_frequent_character(s):
char_info = {} # key: lowercase character, value: {'count': int, 'first_index': int}
max_count = 0
result_char = None
result_first_index = float('inf') # Initialize to a high value
for i, c in enumerate(s):
if c.isalpha():
lower_c = c.lower()
... | simplelr_Evol | [
{
"content": "Question:\nDesign a function that analyzes a string to identify the most frequently occurring character. In the case where multiple characters have the highest frequency, return the character that appears first in the string. Ignore spaces and punctuation, and ensure the function is case-insensiti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4012,
"level": 1,
"question": "Design a function that analyzes a string to identify the most frequently occurring character. In the case where multiple characters have the highest frequency, return the character that appears first in the string. Ignore spaces and punctuation, and en... |
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for _ in range(2, n + 1):
c = a + b
a = b
b = c
return b | simplelr_Filter | [
{
"content": "Question:\nShow me a python function that given an integer n, returns the nth fibonacci number. Remember that the fibonacci sequence starts with 0 and 1, and every subsequent number is the sum of the previous two.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4013,
"level": 1,
"question": "Show me a python function that given an integer n, returns the nth fibonacci number. Remember that the fibonacci sequence starts with 0 and 1, and every subsequent number is the sum of the previous two.",
"split": "train"
} |
import math
def sieve_of_eratosthenes(n):
"""
Generates a list of all prime numbers from 1 to n using the Sieve of Eratosthenes algorithm.
Args:
n (int): The upper bound of the range (inclusive).
Returns:
list: A list of prime numbers within the range [1, n].
Raises:
Valu... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that generates a list of all prime numbers within a given range, from 1 to n, using the Sieve of Eratosthenes algorithm. The function should be efficient and clearly documented.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4014,
"level": 1,
"question": "Write a Python function that generates a list of all prime numbers within a given range, from 1 to n, using the Sieve of Eratosthenes algorithm. The function should be efficient and clearly documented.",
"split": "train"
} |
import numpy as np
def array_to_string(arr):
flat = arr.flatten()
return ' '.join(map(str, flat)) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that converts a 2D NumPy array of any shape into a single string. Each element of the array should be included in the string representation, and elements should be separated by spaces. The function should handle arrays of any size and shape, flattening them into ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4015,
"level": 1,
"question": "Write a Python function that converts a 2D NumPy array of any shape into a single string. Each element of the array should be included in the string representation, and elements should be separated by spaces. The function should handle arrays of any si... |
def combine_lists_to_dict(keys, values):
"""
Combines two lists into a dictionary where the first list elements are keys and the second list elements are values.
Args:
keys (list): The list of keys for the dictionary.
values (list): The list of values for the dictionary.
Return... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python program that combines two lists into a dictionary. However, instead of combining them by alternating between the two lists, combine them such that the second list acts as the values and the first list acts as the keys. The length of lists will always be the same. Also, i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4016,
"level": 1,
"question": "Create a Python program that combines two lists into a dictionary. However, instead of combining them by alternating between the two lists, combine them such that the second list acts as the values and the first list acts as the keys. The length of lis... |
def min_split_cost(arr):
n = len(arr)
if n == 0:
return 0
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
current_max = arr[i - 1]
current_min = arr[i - 1]
dp[i] = dp[i - 1] # Considering the case where we take the last element as a single subarray
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `arr` of length `n`. You need to split the array into multiple contiguous subarrays such that each element in the array belongs to exactly one subarray. The **split cost** of a subarray is defined as the difference between the maximum and mini... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4017,
"level": 1,
"question": "You are given a **0-indexed** integer array `arr` of length `n`. You need to split the array into multiple contiguous subarrays such that each element in the array belongs to exactly one subarray. The **split cost** of a subarray is defined as the diff... |
def trap(height):
left = 0
right = len(height) - 1
max_left = max_right = 0
res = 0
while left <= right:
if height[left] <= height[right]:
if height[left] >= max_left:
max_left = height[left]
else:
res += max_left - height[left]
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of n non-negative integers representing the amount of rainwater trapped in each block, where the width of each block is 1. Write a function to compute the total amount of water trapped, taking into account the elevation map defined by the array. The function shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4018,
"level": 1,
"question": "You are given an array of n non-negative integers representing the amount of rainwater trapped in each block, where the width of each block is 1. Write a function to compute the total amount of water trapped, taking into account the elevation map defin... |
import wave
import struct
def double_volume_of_wav(input_wav_path: str, output_wav_path: str) -> None:
# Read input file
with wave.open(input_wav_path, 'rb') as reader:
params = reader.getparams()
n_channels, sampwidth, framerate, n_frames, comptype, compname = params
frames = reader.re... | simplelr_Docs | [
{
"content": "Question:\n### WAV File Manipulation with Python's \"wave\" Module\n\nYou are tasked with writing a Python function that reads a WAVE file, processes the audio data by doubling the volume, and writes the processed data to a new WAVE file.\n\n### Function Signature\n\n```python\ndef double_volume_o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4019,
"level": 1,
"question": "### WAV File Manipulation with Python's \"wave\" Module\n\nYou are tasked with writing a Python function that reads a WAVE file, processes the audio data by doubling the volume, and writes the processed data to a new WAVE file.\n\n### Function Signatur... |
def insert_sorted(lst, element):
"""
Inserts an element into a sorted list while maintaining the sorted order
without modifying the original list.
Args:
lst (list): The sorted list to insert the element into.
element: The element to be inserted into the list.
Returns:
list:... | simplelr_Filter | [
{
"content": "Question:\nI need help with creating a Python function that can insert an element into a sorted list while maintaining the sorted order. Here's what I've come up with so far:\n\n```python\ndef insert_sorted(lst, element):\n \"\"\"\n Inserts an element into a sorted list while maintaining the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4020,
"level": 1,
"question": "I need help with creating a Python function that can insert an element into a sorted list while maintaining the sorted order. Here's what I've come up with so far:\n\n```python\ndef insert_sorted(lst, element):\n \"\"\"\n Inserts an element into ... |
def length_of_lis(nums):
if not nums:
return 0
n = len(nums)
dp = [1] * n
for i in range(n):
for j in range(i):
if nums[j] < nums[i]:
if dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
return max(dp) if n > 0 else 0 | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the length of the longest increasing subsequence in a given list of integers. The function should use dynamic programming to achieve a time complexity of O(n^2), where n is the length of the input list. For example, given the list [10, 9, 2, 5, 3, 7, 101,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4021,
"level": 1,
"question": "Write a Python function to find the length of the longest increasing subsequence in a given list of integers. The function should use dynamic programming to achieve a time complexity of O(n^2), where n is the length of the input list. For example, give... |
def manual_str_to_int(s):
# Handle empty string case
if not s:
return 0
# Initialize variables
result = 0
base = 1
i = 0
negative = False
# Check for negative sign
if s[0] == '-':
negative = True
i = 1 # Start from next character
elif s[0] == '+':
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert a string to an integer manually, without using the built-in `int()` function. The function should handle both positive and negative integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4022,
"level": 1,
"question": "Write a python function to convert a string to an integer manually, without using the built-in `int()` function. The function should handle both positive and negative integers.",
"split": "train"
} |
def longest_unique_substring(s: str) -> str:
"""
This function finds the longest substring without repeating characters in a given string.
Args:
s (str): The input string.
Returns:
str: The longest substring without repeating characters.
"""
if not s:
retur... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a string as input and returns the longest substring without repeating characters. The function should be case-sensitive, maintaining the original case of the letters. Additionally, your implementation should efficiently handle input strings of up to 100,000 c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4023,
"level": 1,
"question": "Write a function that takes a string as input and returns the longest substring without repeating characters. The function should be case-sensitive, maintaining the original case of the letters. Additionally, your implementation should efficiently hand... |
def communicationGroups(ids):
groups = set()
for id in ids:
s = str(id)
unique_digits = set(s)
key = ''.join(sorted(unique_digits))
groups.add(key)
return len(groups) | simplelr_Apps | [
{
"content": "Question:\nIn a small village, every villager has a unique ID represented by an integer. The villagers have decided to create a secret communication network. In this network, each villager can only communicate with others whose IDs share the same set of unique digits (order of digits does not matt... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4024,
"level": 1,
"question": "In a small village, every villager has a unique ID represented by an integer. The villagers have decided to create a secret communication network. In this network, each villager can only communicate with others whose IDs share the same set of unique di... |
def minimum_difference_partition(weights):
total = sum(weights)
target = total // 2
dp = [False] * (target + 1)
dp[0] = True # Base case: empty subset
for weight in weights:
# Iterate backwards to prevent using the same weight multiple times
for j in range(target, weight - 1, -1):
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** array of positive integers `weights`, where `weights[i]` represents the weight of the `ith` item. You need to divide all the items into two groups so that the difference in the sums of the weights between the two groups is as small as possible. Return _the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4025,
"level": 1,
"question": "You are given a **0-indexed** array of positive integers `weights`, where `weights[i]` represents the weight of the `ith` item. You need to divide all the items into two groups so that the difference in the sums of the weights between the two groups is... |
def distinct_integers(lst):
return len(set(lst)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the number of distinct integers in a list. How can we use Python sets to solve this problem efficiently?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4026,
"level": 1,
"question": "Write a python function to find the number of distinct integers in a list. How can we use Python sets to solve this problem efficiently?",
"split": "train"
} |
def is_divisible_by_3_or_5(n):
return (n / 3 == n // 3) or (n / 5 == n // 5) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given number is divisible by 3 or 5 without using the modulus operator in Python.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4027,
"level": 1,
"question": "Write a function to check if a given number is divisible by 3 or 5 without using the modulus operator in Python.",
"split": "train"
} |
def trap(nums):
left = 0
right = len(nums) - 1
left_max = 0
right_max = 0
result = 0
while left <= right:
if left_max <= right_max:
if nums[left] >= left_max:
left_max = nums[left]
else:
result += left_max - nums[left]
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums`, return _the **total amount of water** that can be trapped between the numbers_ after raining. Each element in the array represents a vertical bar's height, and the width of each bar is 1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4028,
"level": 1,
"question": "Given an integer array `nums`, return _the **total amount of water** that can be trapped between the numbers_ after raining. Each element in the array represents a vertical bar's height, and the width of each bar is 1.",
"split": "train"
} |
from collections import Counter
def are_anagrams(str1, str2):
if len(str1) != len(str2):
return False
return Counter(str1) == Counter(str2)
# Example usage:
print(are_anagrams("listen", "silent")) # Output: True
print(are_anagrams("hello", "world")) # Output: False | simplelr_Filter | [
{
"content": "Question:\nHow can I build a program that determines if a given string is an anagram of another string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4029,
"level": 1,
"question": "How can I build a program that determines if a given string is an anagram of another string?",
"split": "train"
} |
def filter_positive_integers(lst):
return [x for x in lst if x > 0] | simplelr_Apps | [
{
"content": "Question:\n## Task:\n\nWrite a function **filter_positive_integers** that takes a list of integers and returns a new list containing only the positive integers from the input list.\n\n## Examples:\n\nfilter_positive_integers([1, -2, 3, -4, 5]):\n\n [1, 3, 5]\n \nfilter_positive_integers([-1,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4030,
"level": 1,
"question": "## Task:\n\nWrite a function **filter_positive_integers** that takes a list of integers and returns a new list containing only the positive integers from the input list.\n\n## Examples:\n\nfilter_positive_integers([1, -2, 3, -4, 5]):\n\n [1, 3, 5]\n... |
def correct_words(corrections_list, sentence):
corrections = {misspelled: correct for misspelled, correct in corrections_list}
words = sentence.split()
corrected_words = [corrections.get(word, word) for word in words]
return ' '.join(corrected_words) | simplelr_Apps | [
{
"content": "Question:\n**Task**\n\nAlex is working on a text editor application and he is trying to implement a feature that automatically corrects certain misspelled words based on a given dictionary. He wants your help to write a function that will correct the misspelled words in a sentence.\n\nYou need to ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4031,
"level": 1,
"question": "**Task**\n\nAlex is working on a text editor application and he is trying to implement a feature that automatically corrects certain misspelled words based on a given dictionary. He wants your help to write a function that will correct the misspelled w... |
def sort_string(s):
letters = []
digits = []
for char in s:
if char.isalpha():
letters.append(char)
else:
digits.append(char)
letters.sort(key=lambda x: x.lower())
digits.sort()
return ''.join(letters + digits)
| simplelr_Taco | [
{
"content": "Question:\nGiven a string containing letters and digits, sort the string such that the letters come first in alphabetical order, followed by digits in non-decreasing order. The input string will only contain alpha-numeric characters.\n\nFunction input:\n- A string containing letters and digits, e.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4032,
"level": 1,
"question": "Given a string containing letters and digits, sort the string such that the letters come first in alphabetical order, followed by digits in non-decreasing order. The input string will only contain alpha-numeric characters.\n\nFunction input:\n- A strin... |
from collections import deque
def can_visit_all_rooms(rooms):
visited = set()
visited.add(0)
queue = deque([0])
while queue:
room = queue.popleft()
for key in rooms[room]:
if key not in visited:
visited.add(key)
queue.append(key)
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a matrix `rooms` representing a list of rooms in a building. Each room is a list of keys to other rooms. Some rooms may have keys to access other rooms and some rooms may not. Initially, all rooms are locked except for room `0`. You can move between rooms only if you have ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4033,
"level": 1,
"question": "You are given a matrix `rooms` representing a list of rooms in a building. Each room is a list of keys to other rooms. Some rooms may have keys to access other rooms and some rooms may not. Initially, all rooms are locked except for room `0`. You can m... |
def cumulative_sum(lst):
current_sum = 0
result = []
for num in lst:
current_sum += num
result.append(current_sum)
return result
| simplelr_Taco | [
{
"content": "Question:\nImplement a function that takes a list of integers and returns a new list where each element is the sum of the corresponding element from the original list and all previous elements. This is known as a running total or cumulative sum. For example:\n```\n[1, 2, 3, 4] --> [1, 3, 6, 10]\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4034,
"level": 1,
"question": "Implement a function that takes a list of integers and returns a new list where each element is the sum of the corresponding element from the original list and all previous elements. This is known as a running total or cumulative sum. For example:\n```... |
def make_readable(seconds):
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
return f"{hours:02}:{minutes:02}:{seconds:02}"
# Test cases
test_cases = [
(0, "00:00:00"),
(1, "00:00:01"),
(60, "00:01:00"),
(3600, "01:00:00"),
(3661, "01:01:01"),
(359... | simplelr_Filter | [
{
"content": "Question:\n```python\ndef make_readable(seconds):\n \"\"\"\n Given a number of seconds, convert it to a readable format.\n\n Args:\n seconds: An integer representing the number of seconds.\n\n Returns:\n A string representing the time in the format HH:MM:SS.\n \"\"\"\n \n hours = seco... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4035,
"level": 1,
"question": "```python\ndef make_readable(seconds):\n \"\"\"\n Given a number of seconds, convert it to a readable format.\n\n Args:\n seconds: An integer representing the number of seconds.\n\n Returns:\n A string representing the time in the format HH:M... |
def read_large_file(filename):
result = []
with open(filename, 'r') as file:
for line in file:
processed_line = line.strip() # Example processing: remove leading/trailing whitespace
result.append(processed_line)
return result | simplelr_Filter | [
{
"content": "Question:\nI have a function that needs to open a file, read it, and then return the result. The file is too large to fit into memory, so I need to process it line by line. How can I do that in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4036,
"level": 1,
"question": "I have a function that needs to open a file, read it, and then return the result. The file is too large to fit into memory, so I need to process it line by line. How can I do that in Python?",
"split": "train"
} |
def countingSortString(s):
count = [0] * 26
for char in s:
index = ord(char) - ord('a')
count[index] += 1
result = []
for i in range(26):
if count[i] > 0:
result.append(chr(i + ord('a')) * count[i])
return ''.join(result)
| simplelr_Taco | [
{
"content": "Question:\nGiven a string s consisting of lowercase alphabets, arrange all the characters of the string in lexicographically increasing order using the counting sort algorithm.\n\nExample 1:\nInput:\ns = \"geeksforgeeks\"\nOutput:\neefggkkorssse\n\nExample 2:\nInput:\ns = \"programming\"\nOutput:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4037,
"level": 1,
"question": "Given a string s consisting of lowercase alphabets, arrange all the characters of the string in lexicographically increasing order using the counting sort algorithm.\n\nExample 1:\nInput:\ns = \"geeksforgeeks\"\nOutput:\neefggkkorssse\n\nExample 2:\nIn... |
def findFirstUnmatch(s):
stack = []
pair = {')': '(', '}': '{', ']': '['}
for i, char in enumerate(s):
if char in ['(', '{', '[']:
stack.append((char, i)) # Store the character and its index
elif char in [')', '}', ']']:
if not stack:
return i # Unma... | simplelr_Filter | [
{
"content": "Question:\nIn this problem, we are given a string of parentheses, brackets, and curly braces, and we need to find the first pair that does not match.\nLet's use a stack to solve this problem. The idea is to push every opening bracket into the stack and then, whenever we encounter a closing bracket... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4038,
"level": 1,
"question": "In this problem, we are given a string of parentheses, brackets, and curly braces, and we need to find the first pair that does not match.\nLet's use a stack to solve this problem. The idea is to push every opening bracket into the stack and then, when... |
def power_by_position(s):
numbers = [int(x) for x in s.split()]
return [num ** i for i, num in enumerate(numbers, 1)] | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a string of space-separated numbers and returns a list of numbers where each number is taken to the power of its position in the list (1-indexed).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4039,
"level": 1,
"question": "Create a Python function that takes a string of space-separated numbers and returns a list of numbers where each number is taken to the power of its position in the list (1-indexed).",
"split": "train"
} |
def custom_slice(sequence, start, stop, step):
"""
Emulates slicing behavior with additional error checking and custom handling.
Args:
sequence (list or tuple): The sequence to slice.
start (int or None): The starting index of the slice. If None, it defaults based on the step.
stop ... | simplelr_Docs | [
{
"content": "Question:\n### Python/C API Slice and Ellipsis Implementation Challenge\n\n#### Objective:\nYou are required to implement a custom function in Python that emulates portions of the behavior described in the Python/C API documentation regarding slice objects and handling sequences.\n\n#### Function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4040,
"level": 1,
"question": "### Python/C API Slice and Ellipsis Implementation Challenge\n\n#### Objective:\nYou are required to implement a custom function in Python that emulates portions of the behavior described in the Python/C API documentation regarding slice objects and ha... |
def triple_numbers(nums):
return [num * 3 for num in nums] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers as a parameter and returns a new list where each number is tripled.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4041,
"level": 1,
"question": "Write a Python function that takes a list of integers as a parameter and returns a new list where each number is tripled.",
"split": "train"
} |
def is_point_in_rectangle(x1: float, y1: float, x2: float, y2: float, x: float, y: float) -> bool:
x_min = min(x1, x2)
x_max = max(x1, x2)
y_min = min(y1, y2)
y_max = max(y1, y2)
return (x >= x_min) and (x <= x_max) and (y >= y_min) and (y <= y_max) | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are working on a software library for geometry calculations, and one of the key functionalities needed is to determine if a given point lies inside a rectangle. In this task, the rectangle is defined by two of its opposite corners.\n\nGiven two points repres... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4042,
"level": 1,
"question": "### Problem Statement\n\nYou are working on a software library for geometry calculations, and one of the key functionalities needed is to determine if a given point lies inside a rectangle. In this task, the rectangle is defined by two of its opposite ... |
from typing import List
def make_unique_variables(variable_names: List[str]) -> List[str]:
counts = {}
result = []
for name in variable_names:
if name not in counts:
counts[name] = 1
result.append(name)
else:
new_name = name + str(counts[name])
... | simplelr_Taco | [
{
"content": "Question:\nBabka is trying to create a new programming language. She has decided that variables in her language will be strings composed of lowercase English letters. Each variable name must be unique and follow the rules she has established.\n\nGiven a list of initial variable names (possibly wit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4043,
"level": 1,
"question": "Babka is trying to create a new programming language. She has decided that variables in her language will be strings composed of lowercase English letters. Each variable name must be unique and follow the rules she has established.\n\nGiven a list of i... |
def can_be_constructed(s):
n = len(s)
for d in range(1, (n // 2) + 1):
if n % d == 0:
k = n // d
p = s[:d]
valid = True
for i in range(1, k):
current = s[i*d : (i+1)*d]
if current != p:
valid = False
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase letters. Determine if it can be recursively constructed by concatenating some string `p` with itself multiple times (i.e., `p + p + ... + p = s`). Return `true` if it can be constructed in this way, otherwise return `false`.\nAnswer:\nL... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4044,
"level": 1,
"question": "You are given a string `s` consisting of lowercase letters. Determine if it can be recursively constructed by concatenating some string `p` with itself multiple times (i.e., `p + p + ... + p = s`). Return `true` if it can be constructed in this way, ot... |
def compare_strings(str1, str2):
len1 = len(str1)
len2 = len(str2)
if len1 > len2:
return str1
elif len2 > len1:
return str2
else:
return "Both strings are equal in length." | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to compare two strings and return the one with the greater number of characters. If both strings have the same number of characters, return \"Both strings are equal in length.\"\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4045,
"level": 1,
"question": "Write a python function to compare two strings and return the one with the greater number of characters. If both strings have the same number of characters, return \"Both strings are equal in length.\"",
"split": "train"
} |
def longest_substring_without_repeating_characters(s: str) -> str:
char_index = {}
start = 0
max_length = 0
start_max = 0
end_max = 0
for end in range(len(s)):
char = s[end]
if char in char_index and char_index[char] >= start:
start = char_index[char] + 1
c... | simplelr_Filter | [
{
"content": "Question:\nGiven a string, find the longest substring without repeating characters.\n\nExample:\n\nInput: \"abcabcbb\"\n\nOutput: \"abc\"\n\nInput: \"bbbbb\"\n\nOutput: \"b\"\n\nInput: \"pwwkew\"\n\nOutput: \"wke\"\n\nConstraints:\n\n 0 <= s.length <= 5 10⁴\n s consists of English letters, digits... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4046,
"level": 1,
"question": "Given a string, find the longest substring without repeating characters.\n\nExample:\n\nInput: \"abcabcbb\"\n\nOutput: \"abc\"\n\nInput: \"bbbbb\"\n\nOutput: \"b\"\n\nInput: \"pwwkew\"\n\nOutput: \"wke\"\n\nConstraints:\n\n 0 <= s.length <= 5 10⁴\n s ... |
def max_value(s):
current = 0
max_val = 0
for c in s:
if c == '1':
current += 1
if current > max_val:
max_val = current
else:
current -= 1
if current < 0:
current = 0
return max_val
| simplelr_Taco | [
{
"content": "Question:\nYou are given an n-length binary string representing a sequence of operations, where '1' stands for an \"increase operation\" and '0' stands for a \"decrease operation\". You need to find the maximum possible value after performing the operations starting from an initial value of zero. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4047,
"level": 1,
"question": "You are given an n-length binary string representing a sequence of operations, where '1' stands for an \"increase operation\" and '0' stands for a \"decrease operation\". You need to find the maximum possible value after performing the operations start... |
def add_key_value(payload, key, value):
if isinstance(payload, dict):
new_payload = payload.copy()
new_payload[key] = value
return new_payload
else:
return payload | simplelr_Filter | [
{
"content": "Question:\nI've a JSON payload that is either a dictionary or a single atomic value (i.e., a number, a string, a boolean). Given this JSON payload, I want to add a key-value pair to the JSON payload if and only if the JSON payload is a dictionary.\n\nHere is an example of a JSON payload that is a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4048,
"level": 1,
"question": "I've a JSON payload that is either a dictionary or a single atomic value (i.e., a number, a string, a boolean). Given this JSON payload, I want to add a key-value pair to the JSON payload if and only if the JSON payload is a dictionary.\n\nHere is an e... |
def reverse_integer(n):
is_negative = False
if n < 0:
is_negative = True
n = abs(n)
reversed_str = str(n)[::-1]
reversed_num = int(reversed_str)
if is_negative:
reversed_num = -reversed_num
return reversed_num | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as an argument and returns the integer with its digits reversed. If the integer is negative, reverse the digits without the '-' sign at the beginning, and then add the '-' sign back at the end.\nAnswer:\nLet's think step by step.\n",
"role": "... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4049,
"level": 1,
"question": "Create a function that takes an integer as an argument and returns the integer with its digits reversed. If the integer is negative, reverse the digits without the '-' sign at the beginning, and then add the '-' sign back at the end.",
"split": "trai... |
def trap_water(height):
if not height:
return 0
left = 0
right = len(height) - 1
left_max = right_max = 0
sum_water = 0
while left <= right:
if left_max <= right_max:
if height[left] >= left_max:
left_max = height[left]
else:
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a list of non-negative integers representing heights of walls where the width of each wall is 1. Compute how much water it is able to trap after raining.\n\nFormulate an algorithm to find the total amount of trapped water between the walls.\n\nExample 1:\n\nInput: [0,1,0,2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4050,
"level": 1,
"question": "You are given a list of non-negative integers representing heights of walls where the width of each wall is 1. Compute how much water it is able to trap after raining.\n\nFormulate an algorithm to find the total amount of trapped water between the wall... |
def is_palindrome(n):
if n < 0:
return False
s = str(n)
return s == s[::-1] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to check if a given number is a palindrome. A palindrome is a number that reads the same backward as forward, such as 121 or 12321. The function should return `True` if the number is a palindrome and `False` otherwise. Make sure your code is self-contained and cl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4051,
"level": 1,
"question": "Write a Python function to check if a given number is a palindrome. A palindrome is a number that reads the same backward as forward, such as 121 or 12321. The function should return `True` if the number is a palindrome and `False` otherwise. Make sure... |
def find_max(numbers):
if not numbers:
return None
return max(numbers) | simplelr_Filter | [
{
"content": "Question:\nHow can I create a function in Python that automatically finds and returns the maximum value in a list of numbers?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4052,
"level": 1,
"question": "How can I create a function in Python that automatically finds and returns the maximum value in a list of numbers?",
"split": "train"
} |
from typing import List
def distribute_bulbs(num_bulbs: int, num_rooms: int) -> List[int]:
rem = num_bulbs - num_rooms
if rem == 0:
return [1] * num_rooms
base, extra = divmod(rem, num_rooms)
distribution = [1 + base] * num_rooms
for i in range(extra):
distribution[i] += 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Bulb Distribution\nYou are a lighting engineer, and you need to distribute a given number of identical bulbs across several specified rooms in such a way that the light intensity is balanced. Each room must have at least one bulb, and the distribution should minimize the difference ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4053,
"level": 1,
"question": "### Bulb Distribution\nYou are a lighting engineer, and you need to distribute a given number of identical bulbs across several specified rooms in such a way that the light intensity is balanced. Each room must have at least one bulb, and the distribut... |
def find_substring(main_str, substr):
return main_str.find(substr) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that finds the first occurrence of a given substring within a string. If the substring is not found, the function should return -1. The function should be case-sensitive.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4054,
"level": 1,
"question": "Write a Python function that finds the first occurrence of a given substring within a string. If the substring is not found, the function should return -1. The function should be case-sensitive.",
"split": "train"
} |
def min_operations(s1, s2):
len1 = len(s1)
len2 = len(s2)
# Create a DP table with (len1+1) rows and (len2+1) columns
dp = [[0]*(len2+1) for _ in range(len1+1)]
# Initialize the base cases
for i in range(len1+1):
dp[i][0] = i # Deleting 'i' characters
for j in range(len2+1... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given two strings, `s1` and `s2`, both consisting of lowercase English letters. The goal is to determine the minimum number of operations required to transform `s1` into `s2`. The allowed operations are:\n1. Insert a character into `s1`.\n2. Remove a character from `s1`.\n3. Rep... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4055,
"level": 1,
"question": "You are given two strings, `s1` and `s2`, both consisting of lowercase English letters. The goal is to determine the minimum number of operations required to transform `s1` into `s2`. The allowed operations are:\n1. Insert a character into `s1`.\n2. Re... |
from typing import List
def missing_number(nums: List[int]) -> int:
num_set = set(nums)
counter = 1
while True:
if counter not in num_set:
return counter
counter += 1 | simplelr_Code_Contests | [
{
"content": "Question:\nGiven a list of integers, write a function `missing_number` that finds the smallest positive integer that is missing from the list.\n\n#### Function Signature\n```python\ndef missing_number(nums: List[int]) -> int:\n pass\n```\n\n#### Input\n- A list of integers, `nums` (1 ≤ len(nums... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4056,
"level": 1,
"question": "Given a list of integers, write a function `missing_number` that finds the smallest positive integer that is missing from the list.\n\n#### Function Signature\n```python\ndef missing_number(nums: List[int]) -> int:\n pass\n```\n\n#### Input\n- A lis... |
from typing import List
def rearrange_array(arr: List[int], k: int) -> List[int]:
less_or_equal = []
greater = []
for num in arr:
if num <= k:
less_or_equal.append(num)
else:
greater.append(num)
return less_or_equal + greater
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes an array of integers and an integer `k`, and rearranges the array in such a way that all elements less than or equal to `k` come before all elements greater than `k`. The relative order of the elements which are less than or equal to `k` and the relative orde... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4057,
"level": 1,
"question": "Write a function that takes an array of integers and an integer `k`, and rearranges the array in such a way that all elements less than or equal to `k` come before all elements greater than `k`. The relative order of the elements which are less than or... |
def merge_intervals(intervals):
if not intervals:
return []
# Sort intervals based on the start times
sorted_intervals = sorted(intervals, key=lambda x: x[0])
# Initialize the merged list with the first interval
merged = [list(sorted_intervals[0])]
for current in sorted_in... | simplelr_Leetcode | [
{
"content": "Question:\nDesign a function that, given a list of intervals representing a set of events, merges all overlapping intervals and returns a list of the merged intervals. Each interval is represented as a tuple `(start, end)`, where `start` and `end` are integers. The given intervals are not necessar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4058,
"level": 1,
"question": "Design a function that, given a list of intervals representing a set of events, merges all overlapping intervals and returns a list of the merged intervals. Each interval is represented as a tuple `(start, end)`, where `start` and `end` are integers. T... |
def countVowels(s):
count = 0
vowels = 'aeiou'
for char in s:
if char.lower() in vowels:
count += 1
return count
| simplelr_Taco | [
{
"content": "Question:\n**Vowel Counter**\n\nCreate a function called `countVowels` that accepts a single string argument and returns an integer representing the number of vowels (a, e, i, o, u, both lowercase and uppercase) found in the string.\n\nIf the input string is empty, the function should return 0.\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4059,
"level": 1,
"question": "**Vowel Counter**\n\nCreate a function called `countVowels` that accepts a single string argument and returns an integer representing the number of vowels (a, e, i, o, u, both lowercase and uppercase) found in the string.\n\nIf the input string is empt... |
def most_frequent(words):
"""
Finds the most frequent word in a list of words.
Args:
words: A list of words.
Returns:
The most frequent word in the list, or None if the list is empty.
"""
word_counts = {}
for word in words:
if word in word_counts:
word_c... | simplelr_Filter | [
{
"content": "Question:\nThe following Python code aims to analyze a list of words and determine which word appears most frequently:\n\n```python\ndef most_frequent(words):\n \"\"\"\n Finds the most frequent word in a list of words.\n\n Args:\n words: A list of words.\n\n Returns:\n The most frequent ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4060,
"level": 1,
"question": "The following Python code aims to analyze a list of words and determine which word appears most frequently:\n\n```python\ndef most_frequent(words):\n \"\"\"\n Finds the most frequent word in a list of words.\n\n Args:\n words: A list of words.\n\... |
def fibonacci(n):
# Check if n is a positive integer
if not isinstance(n, int) or n < 1:
return []
# Handle the case where n is 1
if n == 1:
return [0]
# Initialize the Fibonacci sequence with the first two numbers
fib_sequence = [0, 1]
# Generate the sequence ... | simplelr_Filter | [
{
"content": "Question:\nPlease write a Python function to calculate the Fibonacci sequence up to a certain number of terms. The function should take an integer `n` as input and return a list containing the Fibonacci sequence up to `n` terms. The Fibonacci sequence starts with 0 and 1, and each subsequent numbe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4061,
"level": 1,
"question": "Please write a Python function to calculate the Fibonacci sequence up to a certain number of terms. The function should take an integer `n` as input and return a list containing the Fibonacci sequence up to `n` terms. The Fibonacci sequence starts with... |
def max_subarray_sum(nums):
if not nums:
return 0
current_max = max_so_far = nums[0]
for num in nums[1:]:
current_max = max(num, current_max + num)
if current_max > max_so_far:
max_so_far = current_max
return max_so_far | simplelr_Apps | [
{
"content": "Question:\nIn a given integer array `nums`, you need to find a contiguous subarray that has the largest sum, and then return that sum. A subarray is a contiguous part of an array.\n\nIf the input array is empty, return `0`. The input array can contain both positive and negative numbers.\n\n**Examp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4062,
"level": 1,
"question": "In a given integer array `nums`, you need to find a contiguous subarray that has the largest sum, and then return that sum. A subarray is a contiguous part of an array.\n\nIf the input array is empty, return `0`. The input array can contain both positi... |
import html
def process_html_content(html_content: str, escape: bool) -> str:
if escape:
return html.escape(html_content)
else:
return html.unescape(html_content)
| simplelr_Docs | [
{
"content": "Question:\n### HTML Content Processor\n\nYou are tasked with creating an HTML content processor for a web application that handles user-generated content. The application needs to safely display user input on a web page while also being able to process and restore any HTML entities within the inpu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4063,
"level": 1,
"question": "### HTML Content Processor\n\nYou are tasked with creating an HTML content processor for a web application that handles user-generated content. The application needs to safely display user input on a web page while also being able to process and restor... |
def rotateImage(grid):
return [list(row[::-1]) for row in zip(*grid)] | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an n x n 2D matrix `grid` representing an image, where each element is an integer that represents the pixel value at that specific coordinate. Your task is to \"rotate\" the image 90 degrees clockwise and return the new 2D matrix.\n\nTo rotate the image 90 degrees clockwis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4064,
"level": 1,
"question": "You are given an n x n 2D matrix `grid` representing an image, where each element is an integer that represents the pixel value at that specific coordinate. Your task is to \"rotate\" the image 90 degrees clockwise and return the new 2D matrix.\n\nTo r... |
def is_palindrome(s):
s = ''.join(c for c in s if c.isalnum()).lower()
return s == s[::-1] | simplelr_Filter | [
{
"content": "Question:\n### Problem 1\n# A palindrome is a number or a text phrase that reads the same backwards as forwards. For example, \"12321\" is a palindrome number. \n# Given a string, write a function to determine if it's a palindrome. \n\n### Problem 2\n# Create a class to perform operations on a que... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4065,
"level": 1,
"question": "### Problem 1\n# A palindrome is a number or a text phrase that reads the same backwards as forwards. For example, \"12321\" is a palindrome number. \n# Given a string, write a function to determine if it's a palindrome. \n\n### Problem 2\n# Create a c... |
def prime_factors(n):
if n == 0:
return []
n = abs(n)
factors = []
i = 2
while i * i <= n:
while n % i == 0:
factors.append(i)
n = n // i
i += 1
if n > 1:
factors.append(n)
return factors | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find all the prime factors of a given number. The function should return a list of prime factors, where each factor appears as many times as it divides the given number. The function should work for both positive and negative numbers, but the negative sign should not... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4066,
"level": 1,
"question": "Write a function to find all the prime factors of a given number. The function should return a list of prime factors, where each factor appears as many times as it divides the given number. The function should work for both positive and negative number... |
from typing import List
def max_subarray_sum(nums: List[int]) -> int:
if not nums:
return 0 # According to the problem, this case won't occur as nums has at least one element.
max_current = max_so_far = nums[0]
for num in nums[1:]:
max_current = max(num, max_current + num)
if max_c... | simplelr_Algorithm | [
{
"content": "Question:\n### Maximum Subarray Sum: Dynamic Programming\n\n**Context:**\nIn the field of finance, finding optimal sections of an investment period that yield the highest returns is a common problem. This can be modeled using arrays where each element represents the return for a specific day. You ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4067,
"level": 1,
"question": "### Maximum Subarray Sum: Dynamic Programming\n\n**Context:**\nIn the field of finance, finding optimal sections of an investment period that yield the highest returns is a common problem. This can be modeled using arrays where each element represents ... |
def longest_unique_substring(s):
char_dict = {}
max_length = 0
start = 0
left = 0
for right in range(len(s)):
char = s[right]
if char in char_dict and char_dict[char] >= left:
left = char_dict[char] + 1
char_dict[char] = right
current_length = right - left... | simplelr_Filter | [
{
"content": "Question:\nGiven a string of characters, write a function that returns the longest substring of the string that contains no repeating characters.\n\nExample:\nInput: \"abcabcbb\"\nOutput: \"abc\"\n\nExample:\nInput: \"bbbbb\"\nOutput: \"\"\n\nExample:\nInput: \"pwwkew\"\nOutput: \"wke\"\n\nNote:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4068,
"level": 1,
"question": "Given a string of characters, write a function that returns the longest substring of the string that contains no repeating characters.\n\nExample:\nInput: \"abcabcbb\"\nOutput: \"abc\"\n\nExample:\nInput: \"bbbbb\"\nOutput: \"\"\n\nExample:\nInput: \"p... |
def find_lower(a, b):
return a if a < b else b | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that accepts two numbers, a and b, and returns the lower of the two.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4069,
"level": 1,
"question": "Create a function that accepts two numbers, a and b, and returns the lower of the two.",
"split": "train"
} |
def filter_and_sort_words(words, length):
filtered_words = [word for word in words if len(word) >= length]
return sorted(filtered_words, key=lambda x: x.lower(), reverse=True) | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that filters out all the words from a list that are shorter than a given length and then returns the list in reverse alphabetical order. The function should be able to handle both uppercase and lowercase letters while performing the sort.\n\nAdditionally, a piece... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4070,
"level": 1,
"question": "Write a Python function that filters out all the words from a list that are shorter than a given length and then returns the list in reverse alphabetical order. The function should be able to handle both uppercase and lowercase letters while performing... |
import pandas as pd
from pandas.tseries.offsets import CustomBusinessDay
def adjust_and_analyze_dates(dates, holidays):
"""
Adjusts the input dates to the next business day if they fall on a weekend or holiday.
Parameters:
- dates (list of str): List of date strings in the format 'YYYY-MM-DD'.
... | simplelr_Docs | [
{
"content": "Question:\n### Business Date Adjustment and Analysis using Pandas Offsets\n\n#### Objective:\nImplement a function that adjusts a given date to the next business day if it falls on a weekend or holiday, and analyze the adjusted dates to determine the frequency position within a month and quarter.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4071,
"level": 1,
"question": "### Business Date Adjustment and Analysis using Pandas Offsets\n\n#### Objective:\nImplement a function that adjusts a given date to the next business day if it falls on a weekend or holiday, and analyze the adjusted dates to determine the frequency po... |
def first_non_repeating_char_index(s: str) -> int:
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
for i, char in enumerate(s):
if counts[char] == 1:
return i
return -1 | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` consisting of lowercase alphabetical characters, determine the first non-repeating character in the string and return its index. If all characters are repeating, return `-1`. The solution should aim for linear time complexity.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4072,
"level": 1,
"question": "Given a string `s` consisting of lowercase alphabetical characters, determine the first non-repeating character in the string and return its index. If all characters are repeating, return `-1`. The solution should aim for linear time complexity.",
"s... |
def sum_to_n(n):
"""
This function calculates the sum of integers from 1 to n using a loop.
Args:
n: An integer representing the upper limit of the sum.
Returns:
An integer representing the sum of integers from 1 to n.
"""
total = 0
i = 1
while i <= n:
total += ... | simplelr_Filter | [
{
"content": "Question:\nThis code snippet calculates the sum of integers from 1 to `n`.\n\n```python\ndef sum_to_n(n):\n \"\"\"\n This function calculates the sum of integers from 1 to n\n\n Args:\n n: An integer representing the upper limit of the sum.\n\n Returns:\n An integer representing the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4073,
"level": 1,
"question": "This code snippet calculates the sum of integers from 1 to `n`.\n\n```python\ndef sum_to_n(n):\n \"\"\"\n This function calculates the sum of integers from 1 to n\n\n Args:\n n: An integer representing the upper limit of the sum.\n\n Returns:\... |
def char_frequency(s):
char_count = {}
for char in s:
lower_char = char.lower()
if lower_char == ' ':
continue
char_count[lower_char] = char_count.get(lower_char, 0) + 1
return char_count | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that takes a string as an argument and returns a dictionary containing the frequency of each character in the string. The program should ignore spaces and be case-insensitive.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4074,
"level": 1,
"question": "Write a Python program that takes a string as an argument and returns a dictionary containing the frequency of each character in the string. The program should ignore spaces and be case-insensitive.",
"split": "train"
} |
import re
def check_palindromes(input_string):
# Remove leading and trailing spaces from the input string
input_string = input_string.strip()
# Split the string into words based on commas followed by any number of spaces
words = re.split(r',\s*', input_string)
# Filter out any empty strings that ma... | simplelr_Filter | [
{
"content": "Question:\nTo determine palindromes in a string, we need to check if a word, phrase, number, or other sequence of characters is the same forward and backward (reading the same backward as forward). Create an algorithm that iterates through each word in a given string and determines if the word is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4075,
"level": 1,
"question": "To determine palindromes in a string, we need to check if a word, phrase, number, or other sequence of characters is the same forward and backward (reading the same backward as forward). Create an algorithm that iterates through each word in a given st... |
def cap_frequencies(lst: list, N: int) -> list:
if N == 0:
return []
frequency = {}
result = []
for num in lst:
count = frequency.get(num, 0)
if count < N:
result.append(num)
frequency[num] = count + 1
return result | simplelr_Data_Structure | [
{
"content": "Question:\n### Frequency Capped List Filter\n\nYou are given a list and a number N. Your task is to implement a function `cap_frequencies` that creates a new list where each element occurs at most N times while maintaining the original order of elements.\n\n#### Function Signature\n```python\ndef ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4076,
"level": 1,
"question": "### Frequency Capped List Filter\n\nYou are given a list and a number N. Your task is to implement a function `cap_frequencies` that creates a new list where each element occurs at most N times while maintaining the original order of elements.\n\n#### ... |
def reverse_string(s):
return s[::-1] | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python function to reverse the order of a given string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4077,
"level": 1,
"question": "Can you help me with a Python function to reverse the order of a given string?",
"split": "train"
} |
def longest_binary_gap(N: int) -> int:
binary_str = bin(N)[2:]
one_positions = [i for i, c in enumerate(binary_str) if c == '1']
if len(one_positions) < 2:
return 0
max_gap = 0
for i in range(1, len(one_positions)):
gap = one_positions[i] - one_positions[i-1] - 1
if gap > max... | simplelr_Codeforces | [
{
"content": "Question:\nA binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.\n\nFor example, number 529 has binary representation 1000010001 and contains two binary gaps, of lengths 4 and 3. The longest ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4078,
"level": 1,
"question": "A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.\n\nFor example, number 529 has binary representation 1000010001 and contains two binary gap... |
def prime_factors(n):
factors = []
# Handle the case of 2 separately
while n % 2 == 0:
factors.append(2)
n = n // 2
# Now n must be odd, start from 3
i = 3
while i * i <= n:
while n % i == 0:
factors.append(i)
n = n // i
i += 2
# If rem... | simplelr_Taco | [
{
"content": "Question:\n___\n\n# Prime Factorization\n\nA prime number is a number that is only divisible by 1 and itself. Prime factorization is expressing a number as a product of its prime factors.\n\n___\n\n# Task\n\n**_Given_** a positive integer, N, **_return_** the list of its prime factors in ascending... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4079,
"level": 1,
"question": "___\n\n# Prime Factorization\n\nA prime number is a number that is only divisible by 1 and itself. Prime factorization is expressing a number as a product of its prime factors.\n\n___\n\n# Task\n\n**_Given_** a positive integer, N, **_return_** the lis... |
def longestMountain(nums):
n = len(nums)
if n < 3:
return 0
inc = [1] * n
for i in range(1, n):
if nums[i] > nums[i-1]:
inc[i] = inc[i-1] + 1
else:
inc[i] = 1
dec = [1] * n
for i in range(n-2, -1, -1):
if nums[i] > nums[i+1]:
... | simplelr_Taco | [
{
"content": "Question:\nGiven an array of positive integers `nums`, we consider a \"mountain\" to be a sequence of adjacent integers that strictly increase to a peak (the highest value in the sequence), and then strictly decrease to the end of the sequence. A mountain cannot start or end with the peak value. I... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4080,
"level": 1,
"question": "Given an array of positive integers `nums`, we consider a \"mountain\" to be a sequence of adjacent integers that strictly increase to a peak (the highest value in the sequence), and then strictly decrease to the end of the sequence. A mountain cannot ... |
def visualize_diamonds_price():
import seaborn.objects as so
from seaborn import load_dataset
# Load the diamonds dataset
diamonds = load_dataset("diamonds")
# Create a plot focused on 'price' for diamonds with 'Ideal' cut
p = so.Plot(diamonds.query("cut == 'Ideal'"), x="price")
# Add cus... | simplelr_Docs | [
{
"content": "Question:\n**Objective:**\nCreate a histogram using seaborn's objects interface to visualize the distribution of the 'price' column from the 'diamonds' dataset. Customize the bar properties and handle overlapping bars.\n\n**Requirements:**\n\n1. **Load Dataset:**\n - Load the 'diamonds' dataset ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4081,
"level": 1,
"question": "**Objective:**\nCreate a histogram using seaborn's objects interface to visualize the distribution of the 'price' column from the 'diamonds' dataset. Customize the bar properties and handle overlapping bars.\n\n**Requirements:**\n\n1. **Load Dataset:**... |
def sort_dict_by_value(d):
return dict(sorted(d.items(), key=lambda item: item[1])) | simplelr_Filter | [
{
"content": "Question:\nI have a Python dictionary and I want to rearrange it in ascending order based on the values. How can I write a function that achieves this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4082,
"level": 1,
"question": "I have a Python dictionary and I want to rearrange it in ascending order based on the values. How can I write a function that achieves this?",
"split": "train"
} |
def rle_encode(input_string: str) -> str:
if not input_string:
return ""
result = ""
current_char = input_string[0]
count = 1
for char in input_string[1:]:
if char == current_char:
count += 1
else:
result += current_char + str(count)
curren... | simplelr_Apps | [
{
"content": "Question:\nIn a particular programming language, strings can be encoded using a simple Run Length Encoding (RLE) algorithm. This algorithm works by replacing sequences of the same character with a single character followed by the number of occurrences. \n\nFor example:\n- The string `\"aaabbcc\"` ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4083,
"level": 1,
"question": "In a particular programming language, strings can be encoded using a simple Run Length Encoding (RLE) algorithm. This algorithm works by replacing sequences of the same character with a single character followed by the number of occurrences. \n\nFor ex... |
def longest_common_prefix(strs):
"""
Find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Args:
strs (list(str)): A list of strings
Returns:
str: The longest common prefix string.
"""
if not... | simplelr_Filter | [
{
"content": "Question:\nThis is a question I was recently asked in an interview.\n\n **You have a list of strings. Write a\n\nfunction to find the **longest common prefix**\n\nstring amongst an \narray of strings.\n\nIf there is no common prefix,\n\nreturn an empty string ` \"\" `.\n\n**For example:**\n\n```py... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4084,
"level": 1,
"question": "This is a question I was recently asked in an interview.\n\n **You have a list of strings. Write a\n\nfunction to find the **longest common prefix**\n\nstring amongst an \narray of strings.\n\nIf there is no common prefix,\n\nreturn an empty string ` \... |
import heapq
def find_min_meeting_rooms(intervals):
if not intervals:
return 0
# Sort the intervals based on start times
sorted_intervals = sorted(intervals, key=lambda x: x[0])
# Initialize a min-heap to keep track of end times
heap = []
max_rooms = 0
for start, end ... | simplelr_Package | [
{
"content": "Question:\nSuppose you are given a list of tuples where each tuple contains two integers representing the start and end times of a meeting. Your goal is to determine the minimum number of meeting rooms required to accommodate all meetings. Write a function `find_min_meeting_rooms(intervals)` that ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4085,
"level": 1,
"question": "Suppose you are given a list of tuples where each tuple contains two integers representing the start and end times of a meeting. Your goal is to determine the minimum number of meeting rooms required to accommodate all meetings. Write a function `find_... |
def invert_case(s):
return s.swapcase() | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to invert the case of each character in a string. For example, if you input the string \"World\", the function should return \"wORLD\". Additionally, ensure your function handles special characters and numbers without altering them.\nAnswer:\nLet's think step by step.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4086,
"level": 1,
"question": "Write a function to invert the case of each character in a string. For example, if you input the string \"World\", the function should return \"wORLD\". Additionally, ensure your function handles special characters and numbers without altering them.",
... |
from typing import List, Tuple
def find_repeated_events(logs: List[Tuple[int, str]], window: int) -> List[str]:
# Sort the logs by timestamp to process them in chronological order
sorted_logs = sorted(logs, key=lambda x: x[0])
seen = {}
result = set()
for timestamp, event in sorted_logs:
... | simplelr_Codeforces | [
{
"content": "Question:\nA company uses a custom logging system to record events happening in their system. Each event log contains a timestamp and an event ID. The system needs to check for repeated events within a certain time window to identify potential issues.\n\nEach log entry is represented as a tuple (t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4087,
"level": 1,
"question": "A company uses a custom logging system to record events happening in their system. Each event log contains a timestamp and an event ID. The system needs to check for repeated events within a certain time window to identify potential issues.\n\nEach log... |
def sum_of_adjacent_numbers(nums):
return [nums[i] + nums[i + 1] for i in range(len(nums) - 1)] | simplelr_Filter | [
{
"content": "Question:\nGiven a list of numbers, write a Python function that returns a new list where each number is the sum of adjacent numbers in the original list. For example, given the list [1, 2, 3, 4], the function should return [3, 5, 7], as these are the sums of (1+2), (2+3), and (3+4) respectively.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4088,
"level": 1,
"question": "Given a list of numbers, write a Python function that returns a new list where each number is the sum of adjacent numbers in the original list. For example, given the list [1, 2, 3, 4], the function should return [3, 5, 7], as these are the sums of (1+... |
def sort_by_length(strings):
return sorted(strings, key=len) | simplelr_Filter | [
{
"content": "Question:\nFor this problem, we will be using Python. We need to sort a list of strings according to their length in ascending order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4089,
"level": 1,
"question": "For this problem, we will be using Python. We need to sort a list of strings according to their length in ascending order.",
"split": "train"
} |
def longest_common_subsequence(s1, s2):
m = len(s1)
n = len(s2)
# Create a table to store lengths of longest common subsequence.
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Fill dp table
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i-1] == s2[j-1]:
... | simplelr_Filter | [
{
"content": "Question:\nCreate a function in Python that takes two string variables, and returns the longest common subsequence (LCS) of characters between them.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4090,
"level": 1,
"question": "Create a function in Python that takes two string variables, and returns the longest common subsequence (LCS) of characters between them.",
"split": "train"
} |
def pair_sum_exists(lst, target):
seen = set()
for num in lst:
complement = target - num
if complement in seen:
return True
seen.add(num)
return False | simplelr_Package | [
{
"content": "Question:\nGiven a list of integers and a target sum, write a Python function `pair_sum_exists(lst, target)` that determines if there are any two distinct elements in the list that add up to the given target sum. The function should return `True` if such a pair exists and `False` otherwise.\n\nTo ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4091,
"level": 1,
"question": "Given a list of integers and a target sum, write a Python function `pair_sum_exists(lst, target)` that determines if there are any two distinct elements in the list that add up to the given target sum. The function should return `True` if such a pair e... |
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
if __name__ == "__main__":
n = int(input().stri... | simplelr_Taco | [
{
"content": "Question:\nGiven an array of integers, a subarray is defined as a contiguous subset of the array. You are required to find the sum of the largest sum subarray using the \"Kadane's Algorithm\". \n\nIn simple terms, we intend to find the sum of maximum subarray among all possible subarrays.\n\nKadan... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4092,
"level": 1,
"question": "Given an array of integers, a subarray is defined as a contiguous subset of the array. You are required to find the sum of the largest sum subarray using the \"Kadane's Algorithm\". \n\nIn simple terms, we intend to find the sum of maximum subarray amo... |
from collections import deque
def is_k_diverse(arr, k):
n = len(arr)
if n < k:
return True
max_deque = deque()
min_deque = deque()
for j in range(n):
# Update max_deque
while max_deque and arr[j] >= arr[max_deque[-1]]:
max_deque.pop()
max_deque.append(j)
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a 0-indexed integer array `arr` and an integer `k`. An array `arr` is called **k-diverse** if the difference between the maximum and minimum values in any contiguous subarray of length `k` is less than or equal to `k`. Return `true` if the given array `arr` is **k-diverse*... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4093,
"level": 1,
"question": "You are given a 0-indexed integer array `arr` and an integer `k`. An array `arr` is called **k-diverse** if the difference between the maximum and minimum values in any contiguous subarray of length `k` is less than or equal to `k`. Return `true` if th... |
def allowed_riders(heights, min_height, max_height):
allowed = []
for height in heights:
if min_height <= height <= max_height:
allowed.append(height)
return allowed
| simplelr_Taco | [
{
"content": "Question:\n# Roller Coaster Queue Management\n\nA popular amusement park has implemented a new rule for managing the queue system for its top roller coaster ride. Each visitor's height (in cm) is recorded upon entry, and only those within a specified height range are allowed to board the ride.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4094,
"level": 1,
"question": "# Roller Coaster Queue Management\n\nA popular amusement park has implemented a new rule for managing the queue system for its top roller coaster ride. Each visitor's height (in cm) is recorded upon entry, and only those within a specified height range... |
def reverse_words(sentence: str) -> str:
words = sentence.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Algorithm | [
{
"content": "Question:\n### Reverse Words in a String\n\n#### Overview\nYou are developing a feature to process text input for a messaging app. As a part of this feature, you need to implement a function that reverses the order of words in a given string.\n\n#### Problem Statement\nImplement a function `revers... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4095,
"level": 1,
"question": "### Reverse Words in a String\n\n#### Overview\nYou are developing a feature to process text input for a messaging app. As a part of this feature, you need to implement a function that reverses the order of words in a given string.\n\n#### Problem Stat... |
def next_available_ticket_id(reserved_tickets):
reserved = set(reserved_tickets)
candidate = 1
while candidate in reserved:
candidate += 1
return candidate
| simplelr_Taco | [
{
"content": "Question:\nA theater has a system of advanced ticket reservations for upcoming shows. Customers can reserve tickets which are identified by a unique ticket ID. Ticket IDs are assigned in an increasing order starting from 1. However, sometimes customers might cancel their reservations, making those... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4096,
"level": 1,
"question": "A theater has a system of advanced ticket reservations for upcoming shows. Customers can reserve tickets which are identified by a unique ticket ID. Ticket IDs are assigned in an increasing order starting from 1. However, sometimes customers might canc... |
def evaluate_postfix(expression):
stack = []
tokens = expression.split()
operators = {'+', '-', '*', '/'}
for token in tokens:
if token in operators:
if len(stack) < 2:
raise ValueError("Not enough operands for operator")
right = stack.pop()
... | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python program that evaluates a given expression as a postfix notation (Reverse Polish Notation)?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4097,
"level": 1,
"question": "How can I create a Python program that evaluates a given expression as a postfix notation (Reverse Polish Notation)?",
"split": "train"
} |
def longest_arith_seq_length(lst):
if not lst:
return 0
n = len(lst)
if n == 1:
return 1
dp = [{} for _ in range(n)]
max_length = 1
for i in range(n):
for j in range(i):
d = lst[i] - lst[j]
current_length = 2
if d in dp[j]:
... | simplelr_Apps | [
{
"content": "Question:\n# Task\nGiven a list of integers, determine the length of the longest subsequence that forms an arithmetic progression.\n\nAn arithmetic progression is a sequence of numbers in which the difference between any two consecutive elements is the same.\n\n# Examples\n\nFor `lst = [1, 7, 10, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4098,
"level": 1,
"question": "# Task\nGiven a list of integers, determine the length of the longest subsequence that forms an arithmetic progression.\n\nAn arithmetic progression is a sequence of numbers in which the difference between any two consecutive elements is the same.\n\n#... |
import heapq
def calculate_mst(n, edges):
start = 0
visited = set()
heap = []
total_weight = 0
# Initialize the heap with edges from the starting node
for neighbor, weight in edges[start]:
heapq.heappush(heap, (weight, start, neighbor))
visited.add(start)
while heap:
... | simplelr_Taco | [
{
"content": "Question:\nYou are given a weighted, undirected graph represented as an adjacency list. Your task is to find the minimum spanning tree (MST) of this graph using Prim's algorithm. The graph is connected and has `n` vertices where `1 <= n <= 1000`.\n\nThe graph is represented using a dictionary wher... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4099,
"level": 1,
"question": "You are given a weighted, undirected graph represented as an adjacency list. Your task is to find the minimum spanning tree (MST) of this graph using Prim's algorithm. The graph is connected and has `n` vertices where `1 <= n <= 1000`.\n\nThe graph is ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.