target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
def find_largest_sum_subarray(lst):
if not lst:
return 0
max_current = max_global = lst[0]
for num in lst[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, write a function find_largest_sum_subarray(lst) that takes the list and returns the sum of the largest contiguous subarray within the given list.\n\nFor example, given the list [-2,1,-3,4,-1,2,1,-5,4], the function find_largest_sum_subarray() should return 6, a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2000,
"level": 1,
"question": "Given a list of integers, write a function find_largest_sum_subarray(lst) that takes the list and returns the sum of the largest contiguous subarray within the given list.\n\nFor example, given the list [-2,1,-3,4,-1,2,1,-5,4], the function find_larges... |
def remove_duplicates(nums):
write_pointer = 0
n = len(nums)
for i in range(n):
current = nums[i]
count = 0
for j in range(write_pointer):
if nums[j] == current:
count += 1
if count >= 2:
break
if count < 2:
... | simplelr_Code_Contests | [
{
"content": "Question:\nYou are given a list of integers. Your task is to modify the list such that every element appears at most twice and return the new length of the list. Do not allocate extra space for another array; you must do this by modifying the input list in-place with O(1) extra memory.\n\nInput\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2001,
"level": 1,
"question": "You are given a list of integers. Your task is to modify the list such that every element appears at most twice and return the new length of the list. Do not allocate extra space for another array; you must do this by modifying the input list in-place ... |
def filter_odd_numbers(numbers):
return [num for num in numbers if num % 2 != 0] | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that filters out even numbers from a list and returns only odd numbers using list comprehension?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2002,
"level": 1,
"question": "How can I create a Python function that filters out even numbers from a list and returns only odd numbers using list comprehension?",
"split": "train"
} |
def fibonacci(n):
if n == 0:
return []
elif n == 1:
return [0]
else:
fib_sequence = [0, 1]
for i in range(2, n):
next_term = fib_sequence[i-1] + fib_sequence[i-2]
fib_sequence.append(next_term)
return fib_sequence | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function to calculate the Fibonacci sequence up to a given number `n`?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2003,
"level": 1,
"question": "Can you provide a Python function to calculate the Fibonacci sequence up to a given number `n`?",
"split": "train"
} |
def max_sum_of_min_partition(arr):
return sum(arr) | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr`, partition the array into (contiguous) subarrays that each contain at least one integer, and return the maximum possible sum of the minimum values of each subarray. For example, if `arr = [3, 1, 2, 4]`, one possible partition could be `[[3], [1, 2], [4]]... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2004,
"level": 1,
"question": "Given an array of integers `arr`, partition the array into (contiguous) subarrays that each contain at least one integer, and return the maximum possible sum of the minimum values of each subarray. For example, if `arr = [3, 1, 2, 4]`, one possible par... |
def extractMax(S):
max_num = -1
current_num = 0
in_number = False
for char in S:
if char.isdigit():
in_number = True
current_num = current_num * 10 + int(char)
else:
if in_number:
if current_num > max_num:
max_num = ... | simplelr_Taco | [
{
"content": "Question:\nYou are given a string S consisting of letters and digits. You need to extract and return the maximum numeric value present in the string. If there are no numeric values in the string, return -1.\n\nExample 1:\nInput:\nS = \"abc123xyz456def\"\nOutput: 456\nExplanation: There are two num... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2005,
"level": 1,
"question": "You are given a string S consisting of letters and digits. You need to extract and return the maximum numeric value present in the string. If there are no numeric values in the string, return -1.\n\nExample 1:\nInput:\nS = \"abc123xyz456def\"\nOutput: ... |
def next_permutation(s: str) -> str:
s_list = list(s)
k = -1
# Step 1: Find the largest index k such that s_list[k] < s_list[k+1]
for i in range(len(s_list) - 2, -1, -1):
if s_list[i] < s_list[i + 1]:
k = i
break
# If no such index, return the smallest permutation
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are required to find the next lexicographically greater permutation for a given string of lowercase English letters. If no such permutation exists (the string is the highest possible permutation), return the smallest permutation (i.e., sorted in ascending or... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2006,
"level": 1,
"question": "### Problem Statement\n\nYou are required to find the next lexicographically greater permutation for a given string of lowercase English letters. If no such permutation exists (the string is the highest possible permutation), return the smallest permut... |
def print_elements(my_list):
for element in my_list:
print(element) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to print all the elements of a list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2007,
"level": 1,
"question": "Write a python function to print all the elements of a list.",
"split": "train"
} |
from typing import List
def cocktail_shaker_sort(arr: List[int]) -> List[int]:
n = len(arr)
if n <= 1:
return arr
swapped = True
while swapped:
swapped = False
# Forward pass: left to right
for i in range(n - 1):
if arr[i] > arr[i + 1]:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Coding Problem: Cocktail Shaker Sort Implementation\n\nYou are tasked with implementing the Cocktail Shaker Sort algorithm, which is a variation of Bubble Sort. In this version, the algorithm iterates through the array in both forward and backward directions to sort the elements. Th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2008,
"level": 1,
"question": "### Coding Problem: Cocktail Shaker Sort Implementation\n\nYou are tasked with implementing the Cocktail Shaker Sort algorithm, which is a variation of Bubble Sort. In this version, the algorithm iterates through the array in both forward and backward ... |
def maxMines(grid):
n = len(grid)
if n == 0:
return 0
m = len(grid[0])
if m == 0:
return 0
dp = [[0 for _ in range(m)] for _ in range(n)]
dp[0][0] = grid[0][0]
# Fill the first row
for j in range(1, m):
dp[0][j] = dp[0][j-1] + grid[0][j]
# Fill ... | simplelr_Codeforces | [
{
"content": "Question:\nA spaceship is navigating through an interstellar minefield. The minefield is represented by a 2D grid of size n x m, where each cell contains a certain number of mines (a non-negative integer). The spaceship can move either to the right or downward from its current position, starting f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2009,
"level": 1,
"question": "A spaceship is navigating through an interstellar minefield. The minefield is represented by a 2D grid of size n x m, where each cell contains a certain number of mines (a non-negative integer). The spaceship can move either to the right or downward fr... |
def move_zeroes(nums):
writePointer = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[writePointer] = nums[i]
writePointer += 1
for i in range(writePointer, len(nums)):
nums[i] = 0
return nums | simplelr_Filter | [
{
"content": "Question:\n# Move Zeroes to End of List\n\nGiven a list of integers `nums`, move all the zeros to the end of the list in-place, \nwhile maintaining the relative order of non-zero elements.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2010,
"level": 1,
"question": "# Move Zeroes to End of List\n\nGiven a list of integers `nums`, move all the zeros to the end of the list in-place, \nwhile maintaining the relative order of non-zero elements.",
"split": "train"
} |
import re
def is_palindrome(text):
"""Checks if a string is a palindrome.
Args:
text: The string to be checked.
Returns:
True if the string is a palindrome, False otherwise.
"""
# Clean the input string by removing non-alphanumeric characters and converting to lowercase
cleane... | simplelr_Filter | [
{
"content": "Question:\nYou are tasked with writing a Python function that:\n\n1. Takes a string as input.\n2. Checks if the string is a palindrome.\n3. Returns True if the string is a palindrome, and False otherwise.\n\n**Note:** A palindrome is a word, phrase, number, or other sequence of characters which re... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2011,
"level": 1,
"question": "You are tasked with writing a Python function that:\n\n1. Takes a string as input.\n2. Checks if the string is a palindrome.\n3. Returns True if the string is a palindrome, and False otherwise.\n\n**Note:** A palindrome is a word, phrase, number, or ot... |
def minimum_distance(words, word1, word2):
if word1 == word2:
last_pos = -1
min_dist = float('inf')
for i, word in enumerate(words):
if word == word1:
if last_pos != -1:
current_dist = i - last_pos + 1
if current_dist < min_... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a collection of strings `words` and two words `word1` and `word2`. Find the minimum distance between these two words in the list. `Distance` is defined as the number of elements between the two words (inclusive) in the list. If the same word appears multiple times, conside... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2012,
"level": 1,
"question": "You are given a collection of strings `words` and two words `word1` and `word2`. Find the minimum distance between these two words in the list. `Distance` is defined as the number of elements between the two words (inclusive) in the list. If the same w... |
def rotate_array(arr, k):
if not arr:
return []
n = len(arr)
effective_k = k % n
return arr[-effective_k:] + arr[:-effective_k] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers and rotates the array to the right by `k` positions. The function should handle cases where `k` is greater than the length of the array. In such cases, the function should perform the rotation as if `k` is equivalent to `k % array length... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2013,
"level": 1,
"question": "Create a function that takes an array of integers and rotates the array to the right by `k` positions. The function should handle cases where `k` is greater than the length of the array. In such cases, the function should perform the rotation as if `k`... |
from collections import deque
def max_buildings_in_segment(heights, K):
if not heights:
return 0
max_deque = deque()
min_deque = deque()
left = 0
max_length = 0
for right in range(len(heights)):
# Update max_deque: maintain decreasing order of heights
while max_deque a... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `heights` representing the heights of buildings in a row, and an integer `K`, return the maximum number of buildings you can include in a segment such that the difference in heights between the tallest and shortest building in the segment is less than or equal to ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2014,
"level": 1,
"question": "Given an integer array `heights` representing the heights of buildings in a row, and an integer `K`, return the maximum number of buildings you can include in a segment such that the difference in heights between the tallest and shortest building in th... |
def sum_of_args(*args):
return sum(args) | simplelr_Filter | [
{
"content": "Question:\nIs it possible to create a function in Python that can accept a variable number of arguments and return the sum of all the arguments? If yes, then how can we do it? If no, then why not?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2015,
"level": 1,
"question": "Is it possible to create a function in Python that can accept a variable number of arguments and return the sum of all the arguments? If yes, then how can we do it? If no, then why not?",
"split": "train"
} |
from typing import List
def find_closest_match(player_skills: List[int], target_skill: int) -> int:
closest_skill = player_skills[0]
smallest_diff = abs(target_skill - closest_skill)
for skill in player_skills[1:]:
current_diff = abs(skill - target_skill)
if current_diff < smallest_dif... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nYou're developing a matchmaking algorithm for an online game. To optimize the matchmaking process, you need to ensure that players with closer skill levels are matched against each other to ensure balanced gameplay.\n\n#### Task\n1. **Fun... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2016,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario\nYou're developing a matchmaking algorithm for an online game. To optimize the matchmaking process, you need to ensure that players with closer skill levels are matched against each other to ensure balanc... |
import bisect
def count_less_or_equal(nums, queries):
nums_sorted = sorted(nums)
result = []
for x in queries:
count = bisect.bisect_right(nums_sorted, x)
result.append(count)
return result | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `nums`, you must answer a series of queries where each query consists of a single integer `x`. For each query, determine the number of integers in the array that are less than or equal to `x`. Return an array of the results for all queries in the order they ar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2017,
"level": 1,
"question": "Given an array of integers `nums`, you must answer a series of queries where each query consists of a single integer `x`. For each query, determine the number of integers in the array that are less than or equal to `x`. Return an array of the results f... |
def caesar_cipher(text, shift):
result = ''
for c in text:
if c.isupper():
offset = ord('A')
elif c.islower():
offset = ord('a')
else:
result += c
continue
new_ord = (ord(c) - offset + shift) % 26 + offset
result += chr(new_... | simplelr_Filter | [
{
"content": "Question:\nI've been tasked with writing code for the Caesar Cipher, a simple encryption technique that replaces each letter with a letter a fixed number of positions down the alphabet.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2018,
"level": 1,
"question": "I've been tasked with writing code for the Caesar Cipher, a simple encryption technique that replaces each letter with a letter a fixed number of positions down the alphabet.",
"split": "train"
} |
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the factorial of a number using recursion, and then use it to calculate the factorial of 5.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2019,
"level": 1,
"question": "Write a python function to calculate the factorial of a number using recursion, and then use it to calculate the factorial of 5.",
"split": "train"
} |
def tuples_to_dict(tuples):
result = {}
for key, value in tuples:
if key in result:
if isinstance(result[key], list):
result[key].append(value)
else:
result[key] = [result[key], value]
else:
result[key] = value
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of tuples as input and returns a dictionary where the first item of each tuple is the key and the second item is the value. If there are duplicate keys, the values should be aggregated into a list.\nAnswer:\nLet's think step by step.\n",
"ro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2020,
"level": 1,
"question": "Write a Python function that takes a list of tuples as input and returns a dictionary where the first item of each tuple is the key and the second item is the value. If there are duplicate keys, the values should be aggregated into a list.",
"split":... |
from typing import List
def linear_search(array: List[int], query: int) -> int:
for index, value in enumerate(array):
if value == query:
return index
return -1 | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given an unsorted array of integers and a target integer (query). Your task is to implement a function to search for the target integer in the array using a linear search algorithm. The function should return the index of the first occurrence of the target integer if found, or -... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2021,
"level": 1,
"question": "You are given an unsorted array of integers and a target integer (query). Your task is to implement a function to search for the target integer in the array using a linear search algorithm. The function should return the index of the first occurrence o... |
def compress_string(s: str) -> str:
if not s:
return s
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
result.append(current_char + str(count))
current_char = char
... | simplelr_Algorithm | [
{
"content": "Question:\n### String Compression\n\nDevelop a function to optimize the storage of a string by compressing it using the counts of repeated characters. Specifically, the function should use a Run Length Encoding (RLE) approach to compress strings where repeated characters are replaced by the charac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2022,
"level": 1,
"question": "### String Compression\n\nDevelop a function to optimize the storage of a string by compressing it using the counts of repeated characters. Specifically, the function should use a Run Length Encoding (RLE) approach to compress strings where repeated ch... |
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif target < arr[mid]:
high = mid - 1
else:
low = mid + 1
return -1 | simplelr_Filter | [
{
"content": "Question:\nI have a problem that needs to be solved using the \"binary search\" method in programming. The problem is: Given a sorted array of integers and a target value, write a function to find the target value in the array. If the target value exists in the array, return its index; otherwise, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2023,
"level": 1,
"question": "I have a problem that needs to be solved using the \"binary search\" method in programming. The problem is: Given a sorted array of integers and a target value, write a function to find the target value in the array. If the target value exists in the a... |
from typing import List
def visible_skyscrapers(heights: List[int]) -> int:
max_height = 0
count = 0
for h in heights:
if h > max_height:
count += 1
max_height = h
return count
| simplelr_Taco | [
{
"content": "Question:\n## Skyscraper View\n\nYou have just been promoted to the position of the city planner in a bustling metropolis. One of your tasks is to assess the visibility of skyscrapers from different viewpoints across the city.\n\n### Problem Statement\n\nConsider an array `heights` where `heights[... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2024,
"level": 1,
"question": "## Skyscraper View\n\nYou have just been promoted to the position of the city planner in a bustling metropolis. One of your tasks is to assess the visibility of skyscrapers from different viewpoints across the city.\n\n### Problem Statement\n\nConsider... |
def find_single_element(nums):
result = 0
for num in nums:
result ^= num
return result | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of `n` integers where every element appears exactly twice except for one element which appears only once. Write a function to find the element that appears only once. Your solution should have a linear runtime complexity and use only constant extra space.\nAnswer:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2025,
"level": 1,
"question": "You are given an array of `n` integers where every element appears exactly twice except for one element which appears only once. Write a function to find the element that appears only once. Your solution should have a linear runtime complexity and use ... |
from collections import Counter
def find_odd_occurrence(nums):
counts = Counter(nums)
for num, count in counts.items():
if count % 2 != 0:
return num
| simplelr_Taco | [
{
"content": "Question:\n```if-not:racket\nWrite a function named `find_odd_occurrence` that takes a list of integers as input and returns the element that occurs an odd number of times in the list. Assume there is always exactly one element that occurs an odd number of times.\n```\n```if:racket\nWrite a functi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2026,
"level": 1,
"question": "```if-not:racket\nWrite a function named `find_odd_occurrence` that takes a list of integers as input and returns the element that occurs an odd number of times in the list. Assume there is always exactly one element that occurs an odd number of times.... |
def fizzbuzz_custom_replacements(n: int, replacements: dict) -> list:
if not isinstance(n, int) or n < 1:
return []
if not isinstance(replacements, dict):
return []
result = []
keys = replacements.keys()
for i in range(1, n + 1):
parts = []
for key in keys:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### FizzBuzz with Additional Constraints\n\nWrite a function `fizzbuzz_custom_replacements(n, replacements)` that returns a list containing the numbers from 1 to n, where each number is replaced based on the following rules:\n\n* If the number is divisible by any key in the `replacement... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2027,
"level": 1,
"question": "### FizzBuzz with Additional Constraints\n\nWrite a function `fizzbuzz_custom_replacements(n, replacements)` that returns a list containing the numbers from 1 to n, where each number is replaced based on the following rules:\n\n* If the number is divis... |
def is_subsequence_sum_possible(arr, t):
if not arr:
return t == 0
min_sum = sum(x for x in arr if x < 0)
max_sum = sum(x for x in arr if x > 0)
if t < min_sum or t > max_sum:
return False
possible_sums = {0}
for num in arr:
new_sums = set()
fo... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `arr` of length `n`. A sub-sequence of `arr` is an array that can be derived by deleting some (possibly zero) elements from `arr` without changing the order of the remaining elements. Return `true` if there exists a sub-sequence of `arr` whose elements sum... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2028,
"level": 1,
"question": "You are given an integer array `arr` of length `n`. A sub-sequence of `arr` is an array that can be derived by deleting some (possibly zero) elements from `arr` without changing the order of the remaining elements. Return `true` if there exists a sub-s... |
def caesar_cipher(text, shift):
"""
Encrypts or decrypts the given text using a Caesar Cipher with the specified shift.
Parameters:
text (str): The text to be encrypted or decrypted.
shift (int): The number of positions to shift each letter. Positive for encryption, negative for decryption.
... | simplelr_Filter | [
{
"content": "Question:\nCan you provide a detailed explanation of how to implement a Caesar Cipher in Python? Certainly! A Caesar Cipher is a simple encryption technique where each letter in the plaintext is shifted a certain number of places down the alphabet. For example, with a shift of 1, 'A' would be repl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2029,
"level": 1,
"question": "Can you provide a detailed explanation of how to implement a Caesar Cipher in Python? Certainly! A Caesar Cipher is a simple encryption technique where each letter in the plaintext is shifted a certain number of places down the alphabet. For example, w... |
from typing import List, Tuple
def calculate_total_sales(sales_data: List[List[float]], product_names: List[str]) -> Tuple[List[str], List[float]]:
totals = []
for product in sales_data:
total = sum(product)
totals.append(total)
return (product_names, totals) | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario:\nYou have been tasked to analyze the performance metrics of a company’s various products over different quarters. The company wants to visualize the total sales for each product over the quarters in the form of a simple bar graph. However, the data provided is in a nested ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2030,
"level": 1,
"question": "### Scenario:\nYou have been tasked to analyze the performance metrics of a company’s various products over different quarters. The company wants to visualize the total sales for each product over the quarters in the form of a simple bar graph. However... |
def square_list(nums):
return [x ** 2 for x in nums] | simplelr_Filter | [
{
"content": "Question:\nCan you provide an example of a Python function that takes a list of integers as input and returns a new list containing the squares of those integers?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2031,
"level": 1,
"question": "Can you provide an example of a Python function that takes a list of integers as input and returns a new list containing the squares of those integers?",
"split": "train"
} |
def is_palindrome(s):
# Filter the string to include only alphanumeric characters and convert to lowercase
cleaned = [c.lower() for c in s if c.isalnum()]
cleaned_str = ''.join(cleaned)
# Check if the cleaned string is the same forwards and backwards
return cleaned_str == cleaned_str[::-1] | simplelr_Evol | [
{
"content": "Question:\nWrite a Python program to determine if a given string is a valid palindrome, considering only alphanumeric characters and ignoring cases. The program should also efficiently handle empty strings and return an appropriate response.\n\nInput Example:\ns = \"A man, a plan, a canal: Panama\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2032,
"level": 1,
"question": "Write a Python program to determine if a given string is a valid palindrome, considering only alphanumeric characters and ignoring cases. The program should also efficiently handle empty strings and return an appropriate response.\n\nInput Example:\ns ... |
import re
def extract_urls(html):
pattern = r'(?:href|src)\s*=\s*["\']?([^"\'>]+)'
urls = re.findall(pattern, html, re.I)
return urls | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to extract all the URLs from a given HTML content. The function should return a list of URLs found in the HTML.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2033,
"level": 1,
"question": "Write a function to extract all the URLs from a given HTML content. The function should return a list of URLs found in the HTML.",
"split": "train"
} |
from typing import List
def smoothen_array(arr: List[int]) -> List[int]:
"""
Smoothen the input array by replacing each element with the average of itself and its neighbors.
Parameters:
- arr: List[int] : Input array of integers
Returns:
- List[int] : The modified array with smoothed ... | simplelr_Package | [
{
"content": "Question:\nYou are asked to write a function called `smoothen_array` that smoothens a given array of integers by replacing each element with the average of itself and its immediate neighbors. The \"average\" here uses integer division.\n\nThe function should:\n\n1. Handle edge cases where elements... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2034,
"level": 1,
"question": "You are asked to write a function called `smoothen_array` that smoothens a given array of integers by replacing each element with the average of itself and its immediate neighbors. The \"average\" here uses integer division.\n\nThe function should:\n\n... |
def decode_message(words):
return ' '.join(sorted(words))
| simplelr_Taco | [
{
"content": "Question:\n### Decode the Jumbled Message\n\nProfessor Xavier left a special encrypted message for the X-Men, but Magneto's minions have jumbled some of the words. The professor's message follows a unique pattern: each word begins with an uppercase letter, and while the order of the words may be s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2035,
"level": 1,
"question": "### Decode the Jumbled Message\n\nProfessor Xavier left a special encrypted message for the X-Men, but Magneto's minions have jumbled some of the words. The professor's message follows a unique pattern: each word begins with an uppercase letter, and wh... |
def ipv4_to_binary(ip):
octets = ip.split('.')
binary_octets = []
for octet in octets:
num = int(octet)
binary = format(num, '08b')
binary_octets.append(binary)
return '.'.join(binary_octets) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to convert an IPv4 address from decimal format to binary format. The IPv4 address is given as a string in the format \"xxx.xxx.xxx.xxx\", where each \"xxx\" is a number from 0 to 255. The function should return the binary representation of the IPv4 address as a s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2036,
"level": 1,
"question": "Write a Python function to convert an IPv4 address from decimal format to binary format. The IPv4 address is given as a string in the format \"xxx.xxx.xxx.xxx\", where each \"xxx\" is a number from 0 to 255. The function should return the binary repres... |
def max_points(colors):
stack = []
points = 0
for c in colors:
if stack and stack[-1] != c:
stack.pop()
points += 1
else:
stack.append(c)
return points | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `colors` where each character represents the color of a balloon, you can remove two consecutive balloons of different colors and gain `1 point` for each pair removed. Return the _maximum points_ you can gain by removing pairs of consecutive balloons of different colors un... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2037,
"level": 1,
"question": "Given a string `colors` where each character represents the color of a balloon, you can remove two consecutive balloons of different colors and gain `1 point` for each pair removed. Return the _maximum points_ you can gain by removing pairs of consecut... |
def is_match(s: str, p: str) -> bool:
n = len(s)
m = len(p)
dp = [[False] * (m + 1) for _ in range(n + 1)]
dp[0][0] = True
for i in range(n + 1):
for j in range(m + 1):
if i == 0 and j == 0:
continue
if j > 0 and p[j-1] == '*' and j >= 2:
... | simplelr_Taco | [
{
"content": "Question:\nGiven a string $s$ and a pattern $p$, determine if the string $s$ matches the pattern $p$ exactly.\n\nThe pattern $p$ can include two special characters:\n- `.` which matches any single character.\n- `*` which matches zero or more of the preceding element.\n\nFor example:\n- The string ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2038,
"level": 1,
"question": "Given a string $s$ and a pattern $p$, determine if the string $s$ matches the pattern $p$ exactly.\n\nThe pattern $p$ can include two special characters:\n- `.` which matches any single character.\n- `*` which matches zero or more of the preceding elem... |
def construct_lexicographically_smallest_string(s, t):
return ''.join([min(s_char, t_char) for s_char, t_char in zip(s, t)]) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings `s` and `t` of the same length containing only lowercase English letters. You need to construct a string `result` by performing a series of transformations on `s`. In each transformation, you can take any character from `s` and replace it with any character fro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2039,
"level": 1,
"question": "You are given two strings `s` and `t` of the same length containing only lowercase English letters. You need to construct a string `result` by performing a series of transformations on `s`. In each transformation, you can take any character from `s` an... |
def factorial(n):
if not isinstance(n, int) or n < 0:
raise ValueError("n must be a non-negative integer")
if n == 0:
return 1
else:
return n * factorial(n - 1) | simplelr_Filter | [
{
"content": "Question:\nThis is what I’ve got so far, but I’m stuck:\n\n\n**The Problem:** \n\nWrite a program that calculates the factorial of a non-negative integer.\n\n**My Code:**\n\n```python\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n - 1)\nAnswer:\nLet's think ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2040,
"level": 1,
"question": "This is what I’ve got so far, but I’m stuck:\n\n\n**The Problem:** \n\nWrite a program that calculates the factorial of a non-negative integer.\n\n**My Code:**\n\n```python\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factori... |
def find_longest_substring(s):
if not isinstance(s, str):
raise TypeError("Input must be a string")
if not s:
return 0
char_index_map = {}
max_len = 0
left = 0
for right in range(len(s)):
char = s[right]
if char in char_index_map and char_index_map[char]... | simplelr_Algorithm | [
{
"content": "Question:\n### Task\nImplement a function `find_longest_substring(s: str) -> int` that finds the length of the longest substring of `s` which contains all unique characters.\n\n### Input and Output\n* **Input**:\n * `s`: A string.\n* **Output**:\n * Returns an integer representing the length of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2041,
"level": 1,
"question": "### Task\nImplement a function `find_longest_substring(s: str) -> int` that finds the length of the longest substring of `s` which contains all unique characters.\n\n### Input and Output\n* **Input**:\n * `s`: A string.\n* **Output**:\n * Returns an ... |
import csv
import logging
# Configure logging
logging.basicConfig(filename='sales_script.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def calculate_total_sales(input_filename, output_filename):
"""
Reads a CSV file containing sales data, calculates total sales per category,
... | simplelr_Evol | [
{
"content": "Question:\nCreate a Python script that reads a CSV file containing sales data, calculates the total sales for each product category, and writes the results to a new CSV file. The sales data CSV file has the following columns: 'ProductID', 'Category', 'ProductName', 'QuantitySold', and 'PricePerUni... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2042,
"level": 1,
"question": "Create a Python script that reads a CSV file containing sales data, calculates the total sales for each product category, and writes the results to a new CSV file. The sales data CSV file has the following columns: 'ProductID', 'Category', 'ProductName... |
def sum_of_squares(lst):
sum_even_squares = 0
for num in lst:
if num % 2 == 0:
sum_even_squares += num ** 2
return sum_even_squares | simplelr_Apps | [
{
"content": "Question:\nImplement a function that takes a list of integers and returns the sum of the squares of all the even numbers in the list. If the list is empty or contains no even numbers, the function should return 0.\n\nExamples:\n\n```\nsum_of_squares([1, 2, 3, 4, 5]) -> 20 // 2^2 + 4^2 = 4 + 16 = 2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2043,
"level": 1,
"question": "Implement a function that takes a list of integers and returns the sum of the squares of all the even numbers in the list. If the list is empty or contains no even numbers, the function should return 0.\n\nExamples:\n\n```\nsum_of_squares([1, 2, 3, 4, ... |
def max_value(a, b):
return max(a, b) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two integers as input and returns the maximum value between them. If the values are equal, return either value.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2044,
"level": 1,
"question": "Create a function that takes two integers as input and returns the maximum value between them. If the values are equal, return either value.",
"split": "train"
} |
def count_substring_occurrences(main, sub):
count = 0
sub_len = len(sub)
for i in range(len(main) - sub_len + 1):
if main[i:i + sub_len] == sub:
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function named `count_substring_occurrences` that counts the number of times a specific substring occurs within a given string, including overlapping occurrences. For example, counting \"aba\" in \"ababa\" should return 2, as the substring \"aba\" overlaps.\nAnswer:\nLet'... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2045,
"level": 1,
"question": "Write a Python function named `count_substring_occurrences` that counts the number of times a specific substring occurs within a given string, including overlapping occurrences. For example, counting \"aba\" in \"ababa\" should return 2, as the substri... |
def is_in_list(lst, num):
return num in lst | simplelr_Filter | [
{
"content": "Question:\nFirst, let's try a simple algorithm to check if an element is in a list: \n\nCan you write a function to determine if a given number is present in a list? \n\nAlso, could you provide a explanation of the time complexity of the algorithm used? \n\nPlease keep it mind that I'm a beginner,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2046,
"level": 1,
"question": "First, let's try a simple algorithm to check if an element is in a list: \n\nCan you write a function to determine if a given number is present in a list? \n\nAlso, could you provide a explanation of the time complexity of the algorithm used? \n\nPleas... |
import collections
def can_finish(numCourses, prerequisites):
# Build adjacency list
adj = [[] for _ in range(numCourses)]
in_degree = [0] * numCourses
for course, prereq in prerequisites:
adj[prereq].append(course)
in_degree[course] += 1
queue = collections.deque()
for i i... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `courses`, where `courses[i] = [course_i, prerequisite_i]` indicates that you must take course `prerequisite_i` before taking course `course_i`. Assume there are a total of `n` courses numbered from `0` to `n-1`. Write a function to determine if it is possible to... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2047,
"level": 1,
"question": "You are given a list of `courses`, where `courses[i] = [course_i, prerequisite_i]` indicates that you must take course `prerequisite_i` before taking course `course_i`. Assume there are a total of `n` courses numbered from `0` to `n-1`. Write a functio... |
def zip_with_defaults(list1: list, list2: list, default=None) -> list:
# Check if both inputs are lists
if not (isinstance(list1, list) and isinstance(list2, list)):
raise TypeError("list1 and list2 must be lists")
max_len = max(len(list1), len(list2))
result = []
for i in range(ma... | simplelr_Algorithm | [
{
"content": "Question:\n### **List Zipping with Default Values**\n\nWrite a function `zip_with_defaults(list1: list, list2: list, default=None) -> list` that zips two lists into a list of tuples. If the lists are of unequal lengths, the shorter list should be padded with the specified default value.\n\n1. **In... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2048,
"level": 1,
"question": "### **List Zipping with Default Values**\n\nWrite a function `zip_with_defaults(list1: list, list2: list, default=None) -> list` that zips two lists into a list of tuples. If the lists are of unequal lengths, the shorter list should be padded with the ... |
def current_borrowed_books(logs):
borrowed = set()
for log in logs:
action, book_id = log.split()
book_id = int(book_id)
if action == 'B':
if book_id not in borrowed:
borrowed.add(book_id)
elif action == 'R':
if book_id in borrowed:
... | simplelr_Taco | [
{
"content": "Question:\nA library database system allows people to borrow books. The library has a system to keep track of the borrowing and returning of books. Your task is to implement a function to determine the books that are currently borrowed, based on a log of actions.\n\nEach action is either a borrowi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2049,
"level": 1,
"question": "A library database system allows people to borrow books. The library has a system to keep track of the borrowing and returning of books. Your task is to implement a function to determine the books that are currently borrowed, based on a log of actions.... |
def isPalindrome(s):
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True | simplelr_Filter | [
{
"content": "Question:\nHere's a problem:\n\n\nYou are given a string `s` consisting of lowercase English letters only. Your task is to determine whether the string is a palindrome.\n\n**A palindrome is a string that reads the same backward as forward.** For example, \"madam\" and \"racecar\" are palindromes, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2050,
"level": 1,
"question": "Here's a problem:\n\n\nYou are given a string `s` consisting of lowercase English letters only. Your task is to determine whether the string is a palindrome.\n\n**A palindrome is a string that reads the same backward as forward.** For example, \"madam\... |
import os
def extract_file_names(file_paths):
file_names = []
for path in file_paths:
_, filename = os.path.split(path)
file_names.append(filename)
return file_names | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a task related to creating a Python function that processes a list of file paths and returns a list of file names? Given a list of file paths, the function should extract and return only the file names without their directory paths.\nAnswer:\nLet's think step by ste... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2051,
"level": 1,
"question": "Can you help me with a task related to creating a Python function that processes a list of file paths and returns a list of file names? Given a list of file paths, the function should extract and return only the file names without their directory paths... |
from collections import deque
def minStepsToTarget(board, source, target):
rows = len(board)
cols = len(board[0]) if rows > 0 else 0
directions = [(2, 1), (1, 2), (-1, 2), (-2, 1),
(-2, -1), (-1, -2), (1, -2), (2, -1)]
sx, sy = source
tx, ty = target
# Check if sourc... | simplelr_Filter | [
{
"content": "Question:\nThe given game board consists of 7x7 squares and the goal is to reach the target position (6, 6) from the source position (0, 0) with a knight (moves in L-shape). The knight has to avoid the blocked positions. The board is 0-indexed. \n\nHere is the code for the given problem:\n```pytho... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2052,
"level": 1,
"question": "The given game board consists of 7x7 squares and the goal is to reach the target position (6, 6) from the source position (0, 0) with a knight (moves in L-shape). The knight has to avoid the blocked positions. The board is 0-indexed. \n\nHere is the co... |
import heapq
def merge_sorted_lists(lists):
heap = []
for i in range(len(lists)):
lst = lists[i]
if len(lst) > 0:
heapq.heappush(heap, (lst[0], i, 0))
result = []
last_added = None
while heap:
current = heapq.heappop(heap)
current_val, list_idx,... | simplelr_Algorithm | [
{
"content": "Question:\n### Merge Sorted Lists and Handle Duplicate Removal\n\nIn a data processing project, you need to merge multiple sorted lists into a single sorted list, removing any duplicate elements. Your task is to implement a function `merge_sorted_lists` that merges the lists and eliminates duplica... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2053,
"level": 1,
"question": "### Merge Sorted Lists and Handle Duplicate Removal\n\nIn a data processing project, you need to merge multiple sorted lists into a single sorted list, removing any duplicate elements. Your task is to implement a function `merge_sorted_lists` that merg... |
import numpy as np
def generate_random_walks(n_steps, n_walks=1, start=0):
"""
Generate random walks.
Parameters:
n_steps (int): The number of steps for each random walk.
n_walks (int): The number of random walks to generate. Default is 1.
start (int or float): The starting point of the walk. ... | simplelr_Filter | [
{
"content": "Question:\nYou can use the following code as a starting point to create a new, high-quality solution to the problem:\n```python\nimport numpy as np\n\ndef generate_random_walks(n_steps, n_walks=1, start=0):\n \"\"\"\n Generate random walks.\n\n Parameters:\n n_steps (int): The number o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2054,
"level": 1,
"question": "You can use the following code as a starting point to create a new, high-quality solution to the problem:\n```python\nimport numpy as np\n\ndef generate_random_walks(n_steps, n_walks=1, start=0):\n \"\"\"\n Generate random walks.\n\n Parameter... |
from typing import List
def next_execution_times(reference_time: int, intervals: List[int]) -> List[int]:
result = []
for ti in intervals:
quotient = reference_time // ti
next_time = (quotient + 1) * ti
result.append(next_time)
return result | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario\nYou are designing a system that schedules periodic tasks. Each task must be executed based on its own schedule without interfering with other tasks. You need to implement a function that helps calculate the next execution time for all tasks after a given reference time.\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2055,
"level": 1,
"question": "### Scenario\nYou are designing a system that schedules periodic tasks. Each task must be executed based on its own schedule without interfering with other tasks. You need to implement a function that helps calculate the next execution time for all tas... |
def remove_k_characters(s, k):
stack = []
for c in s:
while stack and k > 0 and stack[-1] > c:
stack.pop()
k -= 1
stack.append(c)
if k > 0:
stack = stack[:-k]
return ''.join(stack) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` representing a sequence of lowercase Latin letters, and an integer `k`. The task is to remove `k` characters from the string in such a way that the resulting string is the lexicographically smallest possible.\n\nReturn _the lexicographically smallest string_ t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2056,
"level": 1,
"question": "You are given a string `s` representing a sequence of lowercase Latin letters, and an integer `k`. The task is to remove `k` characters from the string in such a way that the resulting string is the lexicographically smallest possible.\n\nReturn _the l... |
def character_frequency(s):
s = s.lower()
freq = {}
for char in s:
if char == ' ':
continue
if char in freq:
freq[char] += 1
else:
freq[char] = 1
return freq | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the frequency of each character in a string and return the result as a dictionary. The function should drop all spaces and be case-insensitive. Here is a string \"Hello World\". The function should output `{ 'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2057,
"level": 1,
"question": "Write a function to find the frequency of each character in a string and return the result as a dictionary. The function should drop all spaces and be case-insensitive. Here is a string \"Hello World\". The function should output `{ 'h': 1, 'e': 1, 'l'... |
import heapq
def dijkstra(graph: dict, start: int) -> dict:
# Initialize distances to infinity for all nodes except the start node
distances = {node: float('inf') for node in graph}
distances[start] = 0
# Priority queue: (distance, node)
heap = []
heapq.heappush(heap, (0, start))
while he... | simplelr_Algorithm | [
{
"content": "Question:\n**Graph Traversal Challenge**\n\nYou have been provided with a weighted, undirected graph represented as an adjacency list and must implement Dijkstra's algorithm to find the shortest path from a given starting node to all other nodes in the graph.\n\n### Problem Statement\nWrite a func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2058,
"level": 1,
"question": "**Graph Traversal Challenge**\n\nYou have been provided with a weighted, undirected graph represented as an adjacency list and must implement Dijkstra's algorithm to find the shortest path from a given starting node to all other nodes in the graph.\n\n... |
def longest_activity_streak(days: list[int]) -> int:
if not days:
return 0
days.sort()
max_streak = 1
current_streak = 1
previous_day = days[0]
for day in days[1:]:
if day == previous_day:
continue
elif day == previous_day + 1:
current_st... | simplelr_Algorithm | [
{
"content": "Question:\n### Context\nA tech company is building an application to analyze user activities. One aspect of this task involves determining the longest streak of continuous days a user has been active. Given a list of days a user has been active, you need to calculate the longest streak of consecut... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2059,
"level": 1,
"question": "### Context\nA tech company is building an application to analyze user activities. One aspect of this task involves determining the longest streak of continuous days a user has been active. Given a list of days a user has been active, you need to calcu... |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def generate_plots(data: dict) -> None:
# 1. Print the default plotting context parameters.
print("Default plotting context parameters:")
print(sns.plotting_context())
# Convert data to DataFrame
df = pd.DataFrame(data)
... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\nDemonstrate your comprehension of different plotting contexts in `seaborn` and how to apply them to generate visualizations with varying styles.\n\n#### Problem Statement\nYou are provided with a dataset containing scores of students in three subjects: Mathematics, Physi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2060,
"level": 1,
"question": "#### Objective\nDemonstrate your comprehension of different plotting contexts in `seaborn` and how to apply them to generate visualizations with varying styles.\n\n#### Problem Statement\nYou are provided with a dataset containing scores of students in... |
from typing import List
def find_missing_number(arr: List[int]) -> int:
n = len(arr) + 1
total = n * (n + 1) // 2
sum_arr = sum(arr)
return total - sum_arr | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Description\n\nYou need to implement a function `find_missing_number` that determines the missing number in an array containing distinct numbers from `1` to `n` except one missing number.\n\n### Function Signature\n```python\ndef find_missing_number(arr: List[int]) -> int:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2061,
"level": 1,
"question": "### Problem Description\n\nYou need to implement a function `find_missing_number` that determines the missing number in an array containing distinct numbers from `1` to `n` except one missing number.\n\n### Function Signature\n```python\ndef find_missi... |
def find_common_elements(a, b, c):
set_a = set(a)
set_b = set(b)
set_c = set(c)
common = set_a & set_b & set_c
return sorted(common) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the common elements in three arrays.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2062,
"level": 1,
"question": "Write a python function to find the common elements in three arrays.",
"split": "train"
} |
def findQuadruplets(nums, target):
nums.sort()
res = []
n = len(nums)
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
left, right = j +... | simplelr_Apps | [
{
"content": "Question:\nGiven an integer array `nums` and an integer `target`, write a function that finds all unique quadruplets `[nums[a], nums[b], nums[c], nums[d]]` such that:\n1. `0 <= a, b, c, d < nums.length`\n2. `a`, `b`, `c`, and `d` are distinct indices\n3. `nums[a] + nums[b] + nums[c] + nums[d] == t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2063,
"level": 1,
"question": "Given an integer array `nums` and an integer `target`, write a function that finds all unique quadruplets `[nums[a], nums[b], nums[c], nums[d]]` such that:\n1. `0 <= a, b, c, d < nums.length`\n2. `a`, `b`, `c`, and `d` are distinct indices\n3. `nums[a]... |
def length_of_longest_substring(s):
last_seen = {}
start = 0
max_length = 0
for i, char in enumerate(s):
if char in last_seen and last_seen[char] >= start:
start = last_seen[char] + 1
last_seen[char] = i
current_length = i - start + 1
if current_length > max_l... | simplelr_Taco | [
{
"content": "Question:\nImplement a function that takes a string s and returns the length of the longest substring without repeating characters.\n\n------ Input ------ \n\nThe input consists of a single string s with a length between 1 and $10^5$. The string s will contain only printable ASCII characters.\n\n-... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2064,
"level": 1,
"question": "Implement a function that takes a string s and returns the length of the longest substring without repeating characters.\n\n------ Input ------ \n\nThe input consists of a single string s with a length between 1 and $10^5$. The string s will contain on... |
def diamond_pattern(n: int) -> str:
if n < 1 or n % 2 == 0:
return ""
middle = (n - 1) // 2
result = []
for i in range(n):
distance = abs(i - middle)
stars = 2 * (middle - distance) + 1
leading_spaces = (n - stars) // 2
line = ' ' * leading_spaces + '*' * stars + ... | simplelr_Apps | [
{
"content": "Question:\nAnna wants to generate a unique diamond pattern using the function **diamond_pattern** that accepts an odd integer **n** (1 <= n <= 99) as input and returns the pattern as a string. The pattern should be **n** rows high, where **n** is always an odd number. For example, if **n** is 5, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2065,
"level": 1,
"question": "Anna wants to generate a unique diamond pattern using the function **diamond_pattern** that accepts an odd integer **n** (1 <= n <= 99) as input and returns the pattern as a string. The pattern should be **n** rows high, where **n** is always an odd nu... |
def validated_factorial(n: int) -> int:
"""
Computes the factorial of a non-negative integer.
Parameters:
n (int): The input non-negative integer whose factorial is to be calculated.
Returns:
int: The factorial of the input integer n.
Raises:
ValueError: If the input is a neg... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement: Factorial with Input Validation\n\nYou are required to implement a function `validated_factorial` that calculates the factorial of a given non-negative integer. The function should handle invalid inputs by raising appropriate errors. The function signature is as f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2066,
"level": 1,
"question": "### Problem Statement: Factorial with Input Validation\n\nYou are required to implement a function `validated_factorial` that calculates the factorial of a given non-negative integer. The function should handle invalid inputs by raising appropriate err... |
MOD = 10**9 + 7
def max_path_sum(grid):
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
# Initialize the dp_prev array for the first row
dp_prev = [0] * n
dp_prev[0] = grid[0][0] % MOD
for j in range(1, n):
dp_prev[j] = (dp_prev[j-1] + grid[0][j]) % ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a matrix `grid` with dimensions `m x n` where each cell contains an integer, your task is to find all possible paths from the top-left corner `(0, 0)` to the bottom-right corner `(m-1, n-1)` of the grid. You can only move either down or right at any point in time. The sum of a pat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2067,
"level": 1,
"question": "Given a matrix `grid` with dimensions `m x n` where each cell contains an integer, your task is to find all possible paths from the top-left corner `(0, 0)` to the bottom-right corner `(m-1, n-1)` of the grid. You can only move either down or right at ... |
from collections import defaultdict
def max_sum_subarray_with_k_distinct(nums, k):
if not nums:
return 0 # Assuming the function should return 0 for an empty list, though the problem guarantees a non-empty list.
max_sum = float('-inf')
current_sum = 0
freq = defaultdict(int)
left = 0
f... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers `nums` and an integer `k`. Return the maximum sum of a non-empty substring (also sometimes referred to as a subarray) of `nums` that consists of at most `k` distinct integers. A substring is a contiguous subsequence of the array. For example, for the arr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2068,
"level": 1,
"question": "You are given a list of integers `nums` and an integer `k`. Return the maximum sum of a non-empty substring (also sometimes referred to as a subarray) of `nums` that consists of at most `k` distinct integers. A substring is a contiguous subsequence of ... |
def are_anagrams(str1: str, str2: str) -> bool:
if len(str1) != len(str2):
return False
count1 = [0] * 26
count2 = [0] * 26
for c in str1:
index = ord(c) - ord('a')
count1[index] += 1
for c in str2:
index = ord(c) - ord('a')
count2[index] += 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Anagram Checking\n\nYou are given two strings, `str1` and `str2`. Your task is to determine if `str1` and `str2` are anagrams of each other.\n\n### Input\n* `str1` - A string where 1 ≤ length of `str1` ≤ 1000.\n* `str2` - A string where 1 ≤ length of `str2` ≤ 1000.\n\n### Output\n* ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2069,
"level": 1,
"question": "### Anagram Checking\n\nYou are given two strings, `str1` and `str2`. Your task is to determine if `str1` and `str2` are anagrams of each other.\n\n### Input\n* `str1` - A string where 1 ≤ length of `str1` ≤ 1000.\n* `str2` - A string where 1 ≤ length ... |
def convert(time_str):
parts = time_str.split(':')
hours = int(parts[0])
minutes = parts[1]
if hours == 0:
new_hour = 12
period = 'AM'
elif 1 <= hours < 12:
new_hour = hours
period = 'AM'
elif hours == 12:
new_hour = 12
period = 'PM'
else:... | simplelr_Filter | [
{
"content": "Question:\nCreate a convert() function to transform times from 24-hour format to 12-hour format. The convert() function should take a string in the format of a 24-hour time and return the same time converted to 12-hour format (EX: \"16:32\" => \"4:32 PM\"). Time should be returned as a string in t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2070,
"level": 1,
"question": "Create a convert() function to transform times from 24-hour format to 12-hour format. The convert() function should take a string in the format of a 24-hour time and return the same time converted to 12-hour format (EX: \"16:32\" => \"4:32 PM\"). Time ... |
def split_path(path: str) -> tuple:
if not path:
return ('', '')
idx = path.rfind('/')
if idx == -1:
return ('', path)
else:
dir_part = path[:idx]
file_part = path[idx + 1:]
return (dir_part, file_part) | simplelr_Data_Structure | [
{
"content": "Question:\n### Question:\n\n**Context**:\nIn many file systems, paths are used to locate files or directories. A common task is to split these paths into their directory and file components so that the components can be processed individually. Given the code snippet that uses Python's built-in `os... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2071,
"level": 1,
"question": "### Question:\n\n**Context**:\nIn many file systems, paths are used to locate files or directories. A common task is to split these paths into their directory and file components so that the components can be processed individually. Given the code snip... |
def remove_duplicates_preserve_order(strings):
seen = set()
result = []
for s in strings:
if s not in seen:
result.append(s)
seen.add(s)
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of strings and returns a new list with duplicates removed, preserving the order of the first occurrence of each string. The function should ensure that each string appears only once in the returned list, in the order of their first appearance.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2072,
"level": 1,
"question": "Write a Python function that takes a list of strings and returns a new list with duplicates removed, preserving the order of the first occurrence of each string. The function should ensure that each string appears only once in the returned list, in the... |
import re
def is_valid_email(email):
# Check overall length
if not email or len(email) > 254:
return False
# Check for exactly one '@'
if email.count('@') != 1:
return False
local, domain = email.split('@')
# Check local part length
if len(local) > 64:
return False
... | simplelr_Filter | [
{
"content": "Question:\nwrite a Python function that checks if a given string is a valid email address. The function should return `True` if the string is a valid email address and `False` otherwise. Consider the standard email format rules.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2073,
"level": 1,
"question": "write a Python function that checks if a given string is a valid email address. The function should return `True` if the string is a valid email address and `False` otherwise. Consider the standard email format rules.",
"split": "train"
} |
def solve(arr, k):
n = len(arr)
if n == 0:
return 0
max_deque = []
min_deque = []
left = 0
max_len = 0
for right in range(n):
# Update max deque
while max_deque and arr[max_deque[-1]] <= arr[right]:
max_deque.pop()
max_deque.append(right)
... | simplelr_Apps | [
{
"content": "Question:\nGiven a list of integers, you are required to find the longest contiguous subarray such that the difference between the maximum and minimum values in this subarray is at most a given integer `k`.\n\n```\nExamples:\nsolve([1, 3, 2, 4, 5, 6], 2) = 3. The longest subarray is [3, 2, 4] wher... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2074,
"level": 1,
"question": "Given a list of integers, you are required to find the longest contiguous subarray such that the difference between the maximum and minimum values in this subarray is at most a given integer `k`.\n\n```\nExamples:\nsolve([1, 3, 2, 4, 5, 6], 2) = 3. The... |
def generate_spiral_matrix(N):
matrix = [[0 for _ in range(N)] for _ in range(N)]
top = 0
bottom = N - 1
left = 0
right = N - 1
num = 1
while left <= right and top <= bottom:
# Fill top row
for i in range(left, right + 1):
matrix[top][i] = num
num += ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to generate a spiral matrix of a given size N. A spiral matrix is a square grid filled with numbers in a spiral order, starting from the top-left corner. The numbers should increase sequentially from 1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2075,
"level": 1,
"question": "Write a function to generate a spiral matrix of a given size N. A spiral matrix is a square grid filled with numbers in a spiral order, starting from the top-left corner. The numbers should increase sequentially from 1.",
"split": "train"
} |
from datetime import date
def get_academic_year(given_date: date) -> str:
year = given_date.year
month = given_date.month
if month >= 9:
academic_start = year
else:
academic_start = year - 1
academic_end = academic_start + 1
return f"{academic_start}-{academic_end}" | simplelr_Filter | [
{
"content": "Question:\nI have a project where I need to create a function that determines the academic year based on a given date. The academic year typically starts on September 1st and ends on August 31st of the following year. The function should take a date as input and return the academic year in the for... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2076,
"level": 1,
"question": "I have a project where I need to create a function that determines the academic year based on a given date. The academic year typically starts on September 1st and ends on August 31st of the following year. The function should take a date as input and ... |
def top_rated_movies(reviews):
movie_ratings = {}
for movie, rating in reviews:
if movie in movie_ratings:
movie_ratings[movie][0] += rating
movie_ratings[movie][1] += 1
else:
movie_ratings[movie] = [rating, 1]
if not movie_ratings:
return []
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Problem:\nYou are tasked with designing a system that processes movie reviews. Each review consists of a comment and a rating. The rating is an integer between 1 and 5. Your task is to identify the movies with the highest average rating and list them. In case of ti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2077,
"level": 1,
"question": "### Coding Assessment Problem:\nYou are tasked with designing a system that processes movie reviews. Each review consists of a comment and a rating. The rating is an integer between 1 and 5. Your task is to identify the movies with the highest average ... |
def checkerboard_pattern(n):
rows = []
for i in range(n):
row = []
for j in range(n):
if (i + j) % 2 == 0:
row.append('#')
else:
row.append(' ')
rows.append(''.join(row))
return '\n'.join(rows) | simplelr_Apps | [
{
"content": "Question:\nCheckerboard Pattern\n\nYou will receive an even integer n (>= 4) and your task is to draw a checkerboard pattern using the characters: '#' and ' ' (space). The pattern should alternate between the characters, starting with '#' in the top-left corner. Each row should be separated with '... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2078,
"level": 1,
"question": "Checkerboard Pattern\n\nYou will receive an even integer n (>= 4) and your task is to draw a checkerboard pattern using the characters: '#' and ' ' (space). The pattern should alternate between the characters, starting with '#' in the top-left corner. ... |
import seaborn.objects as so
from seaborn import load_dataset
def create_diamond_plot():
diamonds = load_dataset("diamonds")
(
so.Plot(diamonds, "cut", "price")
.scale(y="log")
.add(so.Dot(), so.Perc([0, 25, 50, 75, 100]))
.add(so.Dots(pointsize=1, alpha=0.2), so.Jitter(0.3))
... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nTo assess your understanding of seaborn's object interface by creating complex visualizations and applying transformations to a dataset.\n\n#### Problem Statement:\nYou have been provided a dataset `diamonds` from seaborn's dataset repository. Your task is to implement ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2079,
"level": 1,
"question": "#### Objective:\nTo assess your understanding of seaborn's object interface by creating complex visualizations and applying transformations to a dataset.\n\n#### Problem Statement:\nYou have been provided a dataset `diamonds` from seaborn's dataset rep... |
def count_characters(s):
lowercase = 0
uppercase = 0
digits = 0
special = 0
for char in s:
if char.islower():
lowercase += 1
elif char.isupper():
uppercase += 1
elif char.isdigit():
digits += 1
else:
special += 1
ret... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a string and counts the number of lowercase letters, uppercase letters, digits, and special characters in the string. The function should return these counts in a struct.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2080,
"level": 1,
"question": "Create a function that takes in a string and counts the number of lowercase letters, uppercase letters, digits, and special characters in the string. The function should return these counts in a struct.",
"split": "train"
} |
def find_intersection(list1, list2):
"""
Find the intersection of two lists and return a sorted list of unique elements.
Parameters:
- list1 : List[int]
The first input list of integers.
- list2 : List[int]
The second input list of integers.
Returns:
- result: List[int]
... | simplelr_Package | [
{
"content": "Question:\nYou need to create a function that determines the intersection of two given lists of integers. Specifically, your task is to write a function `find_intersection` that returns a sorted list of unique integers that appear in both input lists.\n\n#### Function Definition\n\n```python\ndef ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2081,
"level": 1,
"question": "You need to create a function that determines the intersection of two given lists of integers. Specifically, your task is to write a function `find_intersection` that returns a sorted list of unique integers that appear in both input lists.\n\n#### Fun... |
from datetime import datetime
def convert_date_string_to_datetime(date_str):
return datetime.strptime(date_str, '%Y%m%d') | simplelr_Filter | [
{
"content": "Question:\nWrite a python function that can convert a date string in the format YYYYMMDD to a python datetime object.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2082,
"level": 1,
"question": "Write a python function that can convert a date string in the format YYYYMMDD to a python datetime object.",
"split": "train"
} |
import math
def getPermutation(n, k):
nums = list(range(1, n + 1))
k -= 1 # Convert to 0-based index
result = []
for i in range(n):
remaining = len(nums)
fact = math.factorial(remaining - 1)
index = k // fact
num = nums.pop(index)
result.append(str(num))
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the kth permutation sequence of the set {1, 2, 3, ..., n}. For example, if n = 3, the permutations in lexicographical order are: \"123\", \"132\", \"213\", \"231\", \"312\", \"321\". If k = 4, the function should return \"231\". Note that k is 1-based.\nA... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2083,
"level": 1,
"question": "Write a Python function to find the kth permutation sequence of the set {1, 2, 3, ..., n}. For example, if n = 3, the permutations in lexicographical order are: \"123\", \"132\", \"213\", \"231\", \"312\", \"321\". If k = 4, the function should return ... |
def run_length_encoding(text: str) -> str:
if not text:
return ""
current_char = text[0]
count = 1
result = []
for char in text[1:]:
if char == current_char:
count += 1
else:
result.append(current_char + str(count))
current_char = char
... | simplelr_Algorithm | [
{
"content": "Question:\n### Task:\n\nWrite a function to implement the run-length encoding (RLE) of a string. RLE is a simple lossless compression that replaces consecutive identical characters (runs) with the number of occurrences followed by the character.\n\n### Problem Statement:\n\nWrite a Python function... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2084,
"level": 1,
"question": "### Task:\n\nWrite a function to implement the run-length encoding (RLE) of a string. RLE is a simple lossless compression that replaces consecutive identical characters (runs) with the number of occurrences followed by the character.\n\n### Problem St... |
import seaborn as sns
import matplotlib.pyplot as plt
def analyze_and_plot_regressions():
# Load dataset
tips = sns.load_dataset("tips")
# Linear regression plot
plt.figure(figsize=(10, 6))
sns.regplot(data=tips, x="total_bill", y="tip")
plt.xlabel("Total Bill")
plt.ylabel("Tip")
p... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nUse the seaborn library to analyze relationships between variables in a dataset and visualize these relationships using various types of regression plots. Customize the plots to enhance readability and presentation.\n\n#### Task:\n\n1. **Dataset Loading**: \n - Load t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2085,
"level": 1,
"question": "#### Objective:\nUse the seaborn library to analyze relationships between variables in a dataset and visualize these relationships using various types of regression plots. Customize the plots to enhance readability and presentation.\n\n#### Task:\n\n1.... |
import re
from collections import Counter
def count_specific_words(text, words_to_count):
# Extract all words using regex, considering sequences of alphabetic characters
text_words = re.findall(r'[a-zA-Z]+', text)
# Count occurrences of each word in lowercase
text_word_counts = Counter(word.lower() for... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `count_specific_words` that takes a string `text` and a list of words `words_to_count` as arguments and returns a dictionary where the keys are the words from `words_to_count` and the values are the counts of how many times each word appears in `text`. The words ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2086,
"level": 1,
"question": "Write a Python function `count_specific_words` that takes a string `text` and a list of words `words_to_count` as arguments and returns a dictionary where the keys are the words from `words_to_count` and the values are the counts of how many times each... |
def reverse_list(lst, index=None):
if index is None:
index = len(lst) - 1
if index < 0:
return []
else:
return [lst[index]] + reverse_list(lst, index - 1) | simplelr_Filter | [
{
"content": "Question:\nReverse the order of the items in the list using recursion. Additionally, you are not allowed to use any built-in or library functions for list manipulation. Your solution should have a time complexity of O(n), where n is the length of the list. The input list will always contain unique... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2087,
"level": 1,
"question": "Reverse the order of the items in the list using recursion. Additionally, you are not allowed to use any built-in or library functions for list manipulation. Your solution should have a time complexity of O(n), where n is the length of the list. The in... |
import numpy as np
from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
from sklearn.metrics import adjusted_rand_score, silhouette_score
from typing import Dict
def evaluate_clustering(data: np.ndarray, true_labels: np.ndarray) -> Dict[str, Dict[str, float]]:
"""
Evaluate the performance of K-M... | simplelr_Docs | [
{
"content": "Question:\n### Question\n\n**Objective:**\nThe goal of this assessment is to evaluate your understanding of clustering algorithms in scikit-learn and your ability to apply, evaluate, and compare their performance.\n\n**Task:**\n1. Implement a function `evaluate_clustering` that takes a dataset and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2088,
"level": 1,
"question": "### Question\n\n**Objective:**\nThe goal of this assessment is to evaluate your understanding of clustering algorithms in scikit-learn and your ability to apply, evaluate, and compare their performance.\n\n**Task:**\n1. Implement a function `evaluate_c... |
def get_last_surname(full_name):
stripped = full_name.strip()
if not stripped:
return ''
return stripped.split()[-1] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function named `get_last_surname` that takes a string `full_name` as input and returns the last word, which is assumed to be the surname. The function should handle cases where the input string is empty or contains only spaces, returning an empty string in such cases. Add... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2089,
"level": 1,
"question": "Write a Python function named `get_last_surname` that takes a string `full_name` as input and returns the last word, which is assumed to be the surname. The function should handle cases where the input string is empty or contains only spaces, returning... |
def find_duplicate_values_with_keys(input_dict):
if not isinstance(input_dict, dict):
return {}
value_map = {}
for key, value in input_dict.items():
if value in value_map:
value_map[value].append(key)
else:
value_map[value] = [key]
result = {value: keys fo... | simplelr_Filter | [
{
"content": "Question:\nDevelop a for loop that traverses through the dictionary and returns the duplicate values with their associated keys, not just the values with \"a\" in them. In addition, incorporate error handling for non-iterable inputs.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2090,
"level": 1,
"question": "Develop a for loop that traverses through the dictionary and returns the duplicate values with their associated keys, not just the values with \"a\" in them. In addition, incorporate error handling for non-iterable inputs.",
"split": "train"
} |
def square(x):
return x ** 2 | simplelr_Filter | [
{
"content": "Question:\nWhich of the following is the correct way to define a function in Python that takes a single parameter and returns the value of that parameter squared?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2091,
"level": 1,
"question": "Which of the following is the correct way to define a function in Python that takes a single parameter and returns the value of that parameter squared?",
"split": "train"
} |
import csv
def read_csv_file(filename):
with open(filename, 'r') as file:
csv_reader = csv.reader(file)
rows = [row for row in csv_reader]
return rows | simplelr_Filter | [
{
"content": "Question:\nCan you provide an example of a Python function that reads a CSV file and returns a list of lists, where each inner list represents a row in the CSV file?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2092,
"level": 1,
"question": "Can you provide an example of a Python function that reads a CSV file and returns a list of lists, where each inner list represents a row in the CSV file?",
"split": "train"
} |
def increment_numbers(s):
parts = s.split()
valid_numbers = []
for part in parts:
try:
num = int(part)
valid_numbers.append(num)
except ValueError:
pass
return [x + 1 for x in valid_numbers] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string of numbers separated by spaces and returns a list of the numbers with each number incremented by 1. The function should handle any valid integer values and ignore any non-integer values.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2093,
"level": 1,
"question": "Create a function that takes a string of numbers separated by spaces and returns a list of the numbers with each number incremented by 1. The function should handle any valid integer values and ignore any non-integer values.",
"split": "train"
} |
def most_frequent_word(words):
if not words:
return ''
word_info = {}
for index, word in enumerate(words):
if word in word_info:
word_info[word]['count'] += 1
word_info[word]['last_index'] = index
else:
word_info[word] = {'count': 1, 'las... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of strings `words`. Each string in `words` consists of lowercase English letters. Write a function to find the word that appears the most number of times in `words`. If there are multiple words with the same highest frequency, return the one that appears last in the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2094,
"level": 1,
"question": "You are given a list of strings `words`. Each string in `words` consists of lowercase English letters. Write a function to find the word that appears the most number of times in `words`. If there are multiple words with the same highest frequency, retu... |
import random
from typing import List
def simulate_die_game(n: int, m: int, weights: List[float] = None) -> float:
total_score = 0.0
for _ in range(m):
round_score = 0
for _ in range(n):
if weights is None:
roll = random.randint(1, 6)
else:
... | simplelr_Docs | [
{
"content": "Question:\n**Objective:** \nTo design a function that leverages the Python `random` module to perform a statistical task, ensuring an understanding of the module's various random number generation and distribution functions.\n\n**Problem Statement:** \nYou are required to simulate the rounds of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2095,
"level": 1,
"question": "**Objective:** \nTo design a function that leverages the Python `random` module to perform a statistical task, ensuring an understanding of the module's various random number generation and distribution functions.\n\n**Problem Statement:** \nYou are ... |
def sum_and_square_sum(n):
if n < 1:
return (0, 0)
sum_numbers = n * (n + 1) // 2
sum_squares = n * (n + 1) * (2 * n + 1) // 6
return (sum_numbers, sum_squares) | simplelr_Filter | [
{
"content": "Question:\nPlease provide a Python code snippet for a function that calculates the sum of the first `n` natural numbers, and also the sum of the squares of the first `n` natural numbers. The function should return these two sums as a tuple.\nAnswer:\nLet's think step by step.\n",
"role": "user... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2096,
"level": 1,
"question": "Please provide a Python code snippet for a function that calculates the sum of the first `n` natural numbers, and also the sum of the squares of the first `n` natural numbers. The function should return these two sums as a tuple.",
"split": "train"
} |
def factorial(n):
if n == 0 or n == 1:
return 1
else:
res = n * factorial(n - 1)
print(f"Current number: {n}, Intermediate result: {res}")
return res | simplelr_Filter | [
{
"content": "Question:\nGiven a Python function that calculates the factorial of a number using recursion, how can you modify it to also print each step of the calculation, showing the current number being multiplied and the intermediate result? This will help in understanding the flow of the recursive calls.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2097,
"level": 1,
"question": "Given a Python function that calculates the factorial of a number using recursion, how can you modify it to also print each step of the calculation, showing the current number being multiplied and the intermediate result? This will help in understandin... |
def find_min_value(tuples_list):
return min(tuples_list, key=lambda x: x[1]) | simplelr_Filter | [
{
"content": "Question:\nI have a list of tuples and I want to find the tuple that contains the minimum value in the second position of the tuples. If there are multiple tuples with the same minimum value, I want to find the first occurrence.\n\nThis is my code so far:\n\n```python\ndef find_min_value(tuples_li... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2098,
"level": 1,
"question": "I have a list of tuples and I want to find the tuple that contains the minimum value in the second position of the tuples. If there are multiple tuples with the same minimum value, I want to find the first occurrence.\n\nThis is my code so far:\n\n```p... |
def max_subarray_sum(nums):
if not nums:
return 0
current_max = max_current = nums[0]
for num in nums[1:]:
current_max = max(num, current_max + num)
max_current = max(max_current, current_max)
return max_current | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums` where `nums[i]` could be either positive or negative. Find and return the maximum sum of any contiguous subarray of the array `nums`. A contiguous subarray is defined as a part of an array where consecutive elements of the original array are ret... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2099,
"level": 1,
"question": "You are given an array of integers `nums` where `nums[i]` could be either positive or negative. Find and return the maximum sum of any contiguous subarray of the array `nums`. A contiguous subarray is defined as a part of an array where consecutive ele... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.