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 fizzbuzz(n):
result = []
for i in range(1, n + 1):
if i % 15 == 0:
result.append("FizzBuzz")
elif i % 3 == 0:
result.append("Fizz")
elif i % 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to implement the FizzBuzz problem. The function should take one argument n, and return a list of strings from 1 to n, but for multiples of 3, Return \"Fizz\" instead of the number, for multiples of 5, return \"Buzz\", and for multiples of 15, return \"FizzBuzz\".\nAnswe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7800,
"level": 1,
"question": "Write a function to implement the FizzBuzz problem. The function should take one argument n, and return a list of strings from 1 to n, but for multiples of 3, Return \"Fizz\" instead of the number, for multiples of 5, return \"Buzz\", and for multiples... |
def first_non_repeating_character(s):
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
for char in s:
if counts[char] == 1:
return char
return '#' | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the first non-repeating character in a given string. If no such character exists, return '#'. The string consists of lowercase English letters only.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7801,
"level": 1,
"question": "Write a python function to find the first non-repeating character in a given string. If no such character exists, return '#'. The string consists of lowercase English letters only.",
"split": "train"
} |
def two_sum(nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return [] | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers, you need to find a pair of numbers that when added together, equals a specific target number. If such a pair exists, return the indices of the two numbers. If no such pair exists, return an empty list.\n\nYou can assume that each input would have exactly one ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7802,
"level": 1,
"question": "Given an array of integers, you need to find a pair of numbers that when added together, equals a specific target number. If such a pair exists, return the indices of the two numbers. If no such pair exists, return an empty list.\n\nYou can assume that... |
def binary_search(data, target):
"""
Searches for the target element in the given sorted list.
Args:
- data: A sorted list of elements.
- target: The element to be searched.
Returns:
- The index of the target element if found, -1 otherwise.
"""
low = 0
high = len(data) - 1
... | simplelr_Filter | [
{
"content": "Question:\nHere is a Python program that uses binary search to find an element in a sorted list:\n```\ndef binary_search(data, target):\n \"\"\"\n Searches for the target element in the given sorted list.\n\n Args:\n - data: A sorted list of elements.\n - target: The element to be s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7803,
"level": 1,
"question": "Here is a Python program that uses binary search to find an element in a sorted list:\n```\ndef binary_search(data, target):\n \"\"\"\n Searches for the target element in the given sorted list.\n\n Args:\n - data: A sorted list of elements.... |
def most_popular_category(orders):
# Count the occurrence of each category
frequency = {}
for order in orders:
category = order['category']
if category in frequency:
frequency[category] += 1
else:
frequency[category] = 1
# Find the maximum frequency
... | simplelr_Algorithm | [
{
"content": "Question:\n### Scenario:\nYou have been tasked with developing a utility for processing and summarizing order data for a retail company. Your goal is to create a function that identifies the most popular product category based on the provided purchase records.\n\n### Function Specification:\nYou a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7804,
"level": 1,
"question": "### Scenario:\nYou have been tasked with developing a utility for processing and summarizing order data for a retail company. Your goal is to create a function that identifies the most popular product category based on the provided purchase records.\n\... |
def first_unique_character(s):
# Create a frequency dictionary
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
# Find the first unique character
for char in s:
if freq[char] == 1:
return char
# I... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the first unique character in a string and return it. If there is no unique character, return -1. Assume all characters are lower case and the string is non-empty.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7805,
"level": 1,
"question": "Write a python function to find the first unique character in a string and return it. If there is no unique character, return -1. Assume all characters are lower case and the string is non-empty.",
"split": "train"
} |
from collections import deque
def ladderLength(beginWord, endWord, wordList):
word_set = set(wordList)
if beginWord == endWord:
return 1
if len(beginWord) != len(endWord):
return 0
if endWord not in word_set:
return 0
queue = deque()
queue.append((beginWord, 1)... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a word list `wordList` where each word consists of lowercase English letters. You are also given two words `beginWord` and `endWord`. Your task is to find the **length of the shortest transformation sequence** from `beginWord` to `endWord` such that:\n\n1. Only one letter ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7806,
"level": 1,
"question": "You are given a word list `wordList` where each word consists of lowercase English letters. You are also given two words `beginWord` and `endWord`. Your task is to find the **length of the shortest transformation sequence** from `beginWord` to `endWord... |
def atbash_cipher(text: str) -> str:
result = []
for c in text:
if c.islower():
mirrored = chr(ord('a') + ord('z') - ord(c))
result.append(mirrored)
elif c.isupper():
mirrored = chr(ord('A') + ord('Z') - ord(c))
result.append(mirrored)
else... | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario:\nYou are tasked with securing a simple message by using a historical cipher technique. The Atbash cipher is a substitution cipher where each letter in the alphabet is mapped to its reverse. Specifically, 'a' becomes 'z', 'b' becomes 'y', and so on. This transformation is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7807,
"level": 1,
"question": "#### Scenario:\nYou are tasked with securing a simple message by using a historical cipher technique. The Atbash cipher is a substitution cipher where each letter in the alphabet is mapped to its reverse. Specifically, 'a' becomes 'z', 'b' becomes 'y',... |
def calculateMedian(numbers):
if not numbers:
return None
sorted_numbers = sorted(numbers)
n = len(sorted_numbers)
if n % 2 == 0:
mid1 = sorted_numbers[(n // 2) - 1]
mid2 = sorted_numbers[n // 2]
return (mid1 + mid2) / 2
else:
return sorted_numbers[n // 2] | simplelr_Apps | [
{
"content": "Question:\nWrite a function/method that calculates the median of a list of numbers. The list may contain positive, negative numbers or decimals. Your function should be able to handle and return the correct result for empty lists as well. If the list is empty, it should return None.\n\nExamples:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7808,
"level": 1,
"question": "Write a function/method that calculates the median of a list of numbers. The list may contain positive, negative numbers or decimals. Your function should be able to handle and return the correct result for empty lists as well. If the list is empty, it... |
def rotate_matrix(matrix):
if not matrix:
return []
return [list(row) for row in zip(*matrix[::-1])] | simplelr_Apps | [
{
"content": "Question:\nWrite a function that will rotate a given matrix 90 degrees clockwise.\n\n**Example:**\n\nGiven the following matrix:\n```\n[\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\n```\nThe output should be:\n```\n[\n [7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]\n]\n```\n\nThe function should take in t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7809,
"level": 1,
"question": "Write a function that will rotate a given matrix 90 degrees clockwise.\n\n**Example:**\n\nGiven the following matrix:\n```\n[\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\n```\nThe output should be:\n```\n[\n [7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]\n]\n`... |
import itertools
def find_shortest_route(N, distances):
if N == 1:
return 0 # Though N is at least 2 according to constraints
checkpoints = list(range(2, N + 1))
min_total = float('inf')
for perm in itertools.permutations(checkpoints):
total = 0
# Start at checkpoint 1, mo... | simplelr_Codeforces | [
{
"content": "Question:\nMartin is organizing a marathon in the town of Runville. Runners must complete a unique race that spans through several checkpoints around town. Each checkpoint is represented as a node on a graph, and the paths between them are represented as edges with a positive integer distance. The... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7810,
"level": 1,
"question": "Martin is organizing a marathon in the town of Runville. Runners must complete a unique race that spans through several checkpoints around town. Each checkpoint is represented as a node on a graph, and the paths between them are represented as edges wi... |
def unique_paths_with_obstacles(grid):
if not grid or not grid[0]:
return -1
m = len(grid)
n = len(grid[0])
# Check if start or end is blocked
if grid[0][0] == 1 or grid[m-1][n-1] == 1:
return -1
# Initialize DP table
dp = [[0 for _ in range(n)] for _ in range(... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the number of paths in a grid with obstacles that can only move right and down. The grid is represented as a 2D list where 0 represents an empty cell and 1 represents an obstacle. The function should take the grid as input and return the number of un... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7811,
"level": 1,
"question": "Write a python function to calculate the number of paths in a grid with obstacles that can only move right and down. The grid is represented as a 2D list where 0 represents an empty cell and 1 represents an obstacle. The function should take the grid a... |
def increment_values(d):
new_dict = {}
for key, value in d.items():
if isinstance(value, dict):
new_dict[key] = increment_values(value)
elif type(value) in (int, float):
new_dict[key] = value + 10
else:
new_dict[key] = value
return new_dict | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a dictionary as input and returns a new dictionary with all values incremented by 10. The function should handle nested dictionaries, where the inner dictionaries' values are also incremented by 10. If a value is not a number, it should remain unchange... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7812,
"level": 1,
"question": "Write a Python function that takes a dictionary as input and returns a new dictionary with all values incremented by 10. The function should handle nested dictionaries, where the inner dictionaries' values are also incremented by 10. If a value is not ... |
def find_palindromes(strings):
return [s for s in strings if s == s[::-1]] | simplelr_Filter | [
{
"content": "Question:\nWrite a python function called `find_palindromes` that takes a list of strings as input and returns a new list containing all the strings from the original list that are palindromes.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7813,
"level": 1,
"question": "Write a python function called `find_palindromes` that takes a list of strings as input and returns a new list containing all the strings from the original list that are palindromes.",
"split": "train"
} |
from typing import List
def cycle_sort(arr: List[int]) -> List[int]:
if not arr:
return []
sorted_ref = sorted(arr)
n = len(arr)
for i in range(n):
correct_val = sorted_ref[i]
j = i
# Find the position j where arr[j] == correct_val, starting from i
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Sorting a List with Minimal Writes using Cycle Sort\n\nAs part of a programming assessment, you are tasked with implementing a function based on a sorting algorithm that minimizes write operations. Specifically, you need to use the **Cycle Sort** algorithm to sort a list in ascendin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7814,
"level": 1,
"question": "### Sorting a List with Minimal Writes using Cycle Sort\n\nAs part of a programming assessment, you are tasked with implementing a function based on a sorting algorithm that minimizes write operations. Specifically, you need to use the **Cycle Sort** a... |
def length_of_longest_substring(s):
max_length = 0
left = 0
last_seen = {}
for right in range(len(s)):
char = s[right]
if char in last_seen and last_seen[char] >= left:
left = last_seen[char] + 1
last_seen[char] = right
current_length = right - left + 1
... | simplelr_Filter | [
{
"content": "Question:\nYou are given a string `s` containing only lowercase English letters.\n\nReturn the length of the longest substring without repeating characters.\n\nExample:\n\n```\nInput: s = \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\n```\n\nConstraints:\n\n```... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7815,
"level": 1,
"question": "You are given a string `s` containing only lowercase English letters.\n\nReturn the length of the longest substring without repeating characters.\n\nExample:\n\n```\nInput: s = \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the lengt... |
def transform_list(lst):
transformed = []
for x in lst:
if x % 2 == 0:
if x % 4 == 0:
transformed.append(round(x, 2))
else:
transformed.append(round(x))
else:
transformed.append(str(x))
return transformed | simplelr_Filter | [
{
"content": "Question:\nGiven a Python list, write a program to convert all its odd numbers to strings and all its even numbers to floats. Additionally, if an even number is divisible by 4, round it to 2 decimal places, else round it to the nearest integer. The transformed list must maintain its original order... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7816,
"level": 1,
"question": "Given a Python list, write a program to convert all its odd numbers to strings and all its even numbers to floats. Additionally, if an even number is divisible by 4, round it to 2 decimal places, else round it to the nearest integer. The transformed li... |
def is_3d_array_ascending(arr):
if not arr or not arr[0] or not arr[0][0]:
return True
depth = len(arr)
rows = len(arr[0])
cols = len(arr[0][0])
for layer in arr:
if len(layer) != rows:
return False
for row in layer:
if len(row) != cols:
... | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function to verify if all the elements in a given 3D array are in ascending order depth-wise, row-wise, and column-wise. Also, write suitable test cases to validate your function.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7817,
"level": 1,
"question": "Design a Python function to verify if all the elements in a given 3D array are in ascending order depth-wise, row-wise, and column-wise. Also, write suitable test cases to validate your function.",
"split": "train"
} |
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2) | simplelr_Filter | [
{
"content": "Question:\nCan you explain how to write a recursive function in Python that calculates the nth Fibonacci number, where the first two numbers in the series are 0 and 1?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7818,
"level": 1,
"question": "Can you explain how to write a recursive function in Python that calculates the nth Fibonacci number, where the first two numbers in the series are 0 and 1?",
"split": "train"
} |
def does_robot_return(moves: str) -> bool:
x, y = 0, 0
for move in moves:
if move == 'U':
y += 1
elif move == 'D':
y -= 1
elif move == 'R':
x += 1
elif move == 'L':
x -= 1
return x == 0 and y == 0 | simplelr_Data_Structure | [
{
"content": "Question:\n### Robot Movement Path Checker\n\nImagine you are designing a control system for a simple robot that moves in a 2D plane. The robot starts at the origin (0, 0) and can move up ('U'), down ('D'), left ('L'), or right ('R'). You are required to write a function to determine if a sequence... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7819,
"level": 1,
"question": "### Robot Movement Path Checker\n\nImagine you are designing a control system for a simple robot that moves in a 2D plane. The robot starts at the origin (0, 0) and can move up ('U'), down ('D'), left ('L'), or right ('R'). You are required to write a ... |
def sum_array(arr):
return sum(arr) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum of a given array of integers. The function should take an array of integers as input and return the sum of all the elements in the array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7820,
"level": 1,
"question": "Write a function to calculate the sum of a given array of integers. The function should take an array of integers as input and return the sum of all the elements in the array.",
"split": "train"
} |
def reverse_binary(n: int) -> str:
reversed_str = bin(n)[2:][::-1]
reversed_int = int(reversed_str, 2)
return bin(reversed_int) | simplelr_Algorithm | [
{
"content": "Question:\n## Question\n\n### Problem Statement:\nYou are working on a special encoding system and need to implement a function that reverses the binary representation of non-negative integers. Your task is to write a function `reverse_binary(n: int) -> str` that takes an integer `n`, converts it ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7821,
"level": 1,
"question": "## Question\n\n### Problem Statement:\nYou are working on a special encoding system and need to implement a function that reverses the binary representation of non-negative integers. Your task is to write a function `reverse_binary(n: int) -> str` that... |
import pandas as pd
import matplotlib.pyplot as plt
def analyze_stock_data(file_path: str, window: int) -> None:
# Load the stock data from the CSV
data = pd.read_csv(file_path)
# Parse the "Date" column as datetime
data['Date'] = pd.to_datetime(data['Date'])
# Set the "Date" column as th... | simplelr_Package | [
{
"content": "Question:\nYou are required to implement a function named `analyze_stock_data` that performs the following tasks:\n\n1. **Loading Data**: Read a CSV file containing daily stock prices for a single stock. The CSV file contains columns: \"Date\" (in YYYY-MM-DD format), \"Open\", \"High\", \"Low\", \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7822,
"level": 1,
"question": "You are required to implement a function named `analyze_stock_data` that performs the following tasks:\n\n1. **Loading Data**: Read a CSV file containing daily stock prices for a single stock. The CSV file contains columns: \"Date\" (in YYYY-MM-DD form... |
def max_consecutive_months_within_budget(expenses, B):
max_length = 0
n = len(expenses)
for i in range(n):
current_sum = 0
for j in range(i, n):
current_sum += expenses[j]
if current_sum > B:
break
current_length = j - i + 1
if ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `expenses` representing your monthly expenses for a year, where `expenses[i]` is the expense for the `i-th` month. Find the maximum number of consecutive months within one year where the sum of expenses is less than or equal to a given budget `B`. Return t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7823,
"level": 1,
"question": "You are given an integer array `expenses` representing your monthly expenses for a year, where `expenses[i]` is the expense for the `i-th` month. Find the maximum number of consecutive months within one year where the sum of expenses is less than or eq... |
from typing import List
def max_area(height: List[int]) -> int:
left = 0
right = len(height) - 1
max_area = 0
while left < right:
current_height = min(height[left], height[right])
current_width = right - left
current_area = current_height * current_width
if current_area... | simplelr_Algorithm | [
{
"content": "Question:\n### Container With Most Water\n\n#### Problem Statement\nYou are given `n` non-negative integers representing the heights of vertical lines drawn on a graph. These lines are placed such that the two endpoints of the ith line are at (i, 0) and (i, height[i]). Find two lines, which togeth... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7824,
"level": 1,
"question": "### Container With Most Water\n\n#### Problem Statement\nYou are given `n` non-negative integers representing the heights of vertical lines drawn on a graph. These lines are placed such that the two endpoints of the ith line are at (i, 0) and (i, heigh... |
def unique_elements(list1, list2):
set1 = set(list1)
set2 = set(list2)
sym_diff = set1 ^ set2
return sorted(sym_diff) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in two lists of integers and returns a sorted list of all unique elements that appear in exactly one of the input lists.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7825,
"level": 1,
"question": "Create a function that takes in two lists of integers and returns a sorted list of all unique elements that appear in exactly one of the input lists.",
"split": "train"
} |
def max_subarray_sum(nums):
if not nums: # Handle empty list case, though problem states it's non-empty
return 0
current_max = global_max = nums[0]
for num in nums[1:]:
current_max = max(num, current_max + num)
if current_max > global_max:
global_max = current_max
re... | simplelr_Package | [
{
"content": "Question:\nYou are given a list of integers that may contain both positive and negative numbers. Write a function that finds the subarray (containing at least one number) which has the largest sum and returns the sum.\n\n1. Function Name: `max_subarray_sum`\n2. Inputs:\n - `nums`: A list of inte... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7826,
"level": 1,
"question": "You are given a list of integers that may contain both positive and negative numbers. Write a function that finds the subarray (containing at least one number) which has the largest sum and returns the sum.\n\n1. Function Name: `max_subarray_sum`\n2. I... |
def max_profit(prices):
if len(prices) < 2:
return 0
min_price = prices[0]
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
else:
current_profit = price - min_price
if current_profit > max_profit:
max_... | simplelr_Package | [
{
"content": "Question:\nGiven a list of stock prices for consecutive days, each element representing the price of a particular stock on that day, calculate the maximum profit that can be achieved from exactly one buy and one sell transaction. The function should return the maximum profit possible. If no profit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7827,
"level": 1,
"question": "Given a list of stock prices for consecutive days, each element representing the price of a particular stock on that day, calculate the maximum profit that can be achieved from exactly one buy and one sell transaction. The function should return the ma... |
def search_first_occurrence(nums, target):
low, high = 0, len(nums) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
result = mid
high = mid - 1 # Search the left half for earlier occurrence
elif nums[mid] < target:
... | simplelr_Filter | [
{
"content": "Question:\nGiven a sorted array of integers, find the first occurrence of a target value (where the target value is also an integer). If the target does not exist, return -1.\n\nExample:\nInput: nums = [5, 7, 7, 8, 8, 10], target = 8\nOutput: 2\nExplanation: The first occurrence of the value 8 is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7828,
"level": 1,
"question": "Given a sorted array of integers, find the first occurrence of a target value (where the target value is also an integer). If the target does not exist, return -1.\n\nExample:\nInput: nums = [5, 7, 7, 8, 8, 10], target = 8\nOutput: 2\nExplanation: The... |
def filter_by_prefix(dictionary, prefix):
"""
Filters a dictionary to include only keys that start with a specified prefix.
Args:
dictionary (dict): The input dictionary to be filtered.
prefix (str): The prefix string that keys must start with.
Returns:
dict: A new dictionary c... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to filter out key-value pairs from a dictionary where the keys have a specified prefix. The function should take two arguments: the dictionary and the prefix string. It should return a new dictionary containing only the key-value pairs where the key starts with t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7829,
"level": 1,
"question": "Write a Python function to filter out key-value pairs from a dictionary where the keys have a specified prefix. The function should take two arguments: the dictionary and the prefix string. It should return a new dictionary containing only the key-valu... |
def remove_redundant_elements(input_list):
seen = set()
result = []
for element in input_list:
if element not in seen:
seen.add(element)
result.append(element)
return result | simplelr_Filter | [
{
"content": "Question:\nDefine a Python function to remove all redundant elements from a list and return a list with only unique elements. The function should also take into consideration that the order of the elements in the output list should be the same as the order of their first occurrence in the original... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7830,
"level": 1,
"question": "Define a Python function to remove all redundant elements from a list and return a list with only unique elements. The function should also take into consideration that the order of the elements in the output list should be the same as the order of the... |
def minOperations(nums, x):
n = len(nums)
if n == 0:
return -1 if x != 0 else 0 # Handle edge case where array is empty
# Compute prefix sums
prefix = [0]
current = 0
for num in nums:
current += num
prefix.append(current)
# Compute suffix sums
suffix = ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums` and an integer `x`, return _the minimum number of operations to reduce `x` to exactly_ `0` _by subtracting elements from the edges of the array_ `nums`. _An operation consists of removing either the leftmost or the rightmost element from the array, and subt... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7831,
"level": 1,
"question": "Given an integer array `nums` and an integer `x`, return _the minimum number of operations to reduce `x` to exactly_ `0` _by subtracting elements from the edges of the array_ `nums`. _An operation consists of removing either the leftmost or the rightmo... |
def is_valid_expression(expression):
stack = []
closer_to_opener = {')': '(', '}': '{', ']': '['}
for char in expression:
if char in ['(', '{', '[']:
stack.append(char)
elif char in closer_to_opener:
if not stack:
return False
if stack.pop(... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `expression` that contains only the characters `(`, `)`, `{`, `}`, `[` and `]`. Write a function to determine if the given expression is a valid arithmetic expression. An arithmetic expression is considered valid if all opening brackets have a corresponding closin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7832,
"level": 1,
"question": "You are given a string `expression` that contains only the characters `(`, `)`, `{`, `}`, `[` and `]`. Write a function to determine if the given expression is a valid arithmetic expression. An arithmetic expression is considered valid if all opening b... |
import pandas as pd
def analyze_transactions(file_path: str) -> dict:
# Read the CSV file into a DataFrame
df = pd.read_csv(file_path)
# Calculate the total number of transactions
total_transactions = len(df)
# Calculate total and average transaction amount
total_amount = df['Amount']... | simplelr_Package | [
{
"content": "Question:\n**\n\nGiven a CSV file `data/TransactionData.csv`, which contains records of financial transactions. Each row in the file represents a single transaction, where each transaction is described by several attributes such as transaction ID, amount, date, and category.\n\nThe file follows th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7833,
"level": 1,
"question": "**\n\nGiven a CSV file `data/TransactionData.csv`, which contains records of financial transactions. Each row in the file represents a single transaction, where each transaction is described by several attributes such as transaction ID, amount, date, a... |
def arrangeArray(arr):
positives = []
zeros = []
negatives = []
for num in arr:
if num > 0:
positives.append(num)
elif num == 0:
zeros.append(num)
else:
negatives.append(num)
return positives + zeros + negatives
| simplelr_Taco | [
{
"content": "Question:\nArrange the provided array of integers such that all positive integers appear first in the original order, followed by all zeros in their original order, and finally, all negative integers in their original order.\n\nExample:\n\n```\narrangeArray([1, -1, 3, 0, -2, 5, 0, -4]) // should r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7834,
"level": 1,
"question": "Arrange the provided array of integers such that all positive integers appear first in the original order, followed by all zeros in their original order, and finally, all negative integers in their original order.\n\nExample:\n\n```\narrangeArray([1, -... |
def optimal_traffic_flow(arrival_rate: float, throughput: float) -> float:
if arrival_rate <= 0 or throughput <= 0:
raise ValueError("arrival_rate and throughput must be positive")
cycle_length = throughput / arrival_rate
cycle_length = min(max(cycle_length, 15.0), 180.0)
return cycle_length | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Task:\n\n#### Context:\nYou are a software developer for a traffic management system company. Your team is upgrading the system to handle more complex traffic signal scenarios, including adaptive signal control to optimize traffic flow.\n\n#### Problem Statement:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7835,
"level": 1,
"question": "### Coding Assessment Task:\n\n#### Context:\nYou are a software developer for a traffic management system company. Your team is upgrading the system to handle more complex traffic signal scenarios, including adaptive signal control to optimize traffic... |
def is_anagram_optimized(s: str, t: str) -> bool:
if len(s) != len(t):
return False
counts = [0] * 26
for c in s:
counts[ord(c) - 97] += 1
for c in t:
counts[ord(c) - 97] -= 1
return all(v == 0 for v in counts) | simplelr_Data_Structure | [
{
"content": "Question:\n### Anagram Verification\n\n**Objective**: Write a function `is_anagram_optimized(s: str, t: str) -> bool` that determines if the string `t` is an anagram of the string `s`.\n\n### Input:\n* Two strings `s` and `t` of lowercase alphabets only.\n\n### Output:\n* A boolean value `true` if... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7836,
"level": 1,
"question": "### Anagram Verification\n\n**Objective**: Write a function `is_anagram_optimized(s: str, t: str) -> bool` that determines if the string `t` is an anagram of the string `s`.\n\n### Input:\n* Two strings `s` and `t` of lowercase alphabets only.\n\n### O... |
def reverse_string(s):
return s[::-1] | simplelr_Filter | [
{
"content": "Question:\nSure, provide a simple example of a Python function that takes a string input and returns the string in reverse order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7837,
"level": 1,
"question": "Sure, provide a simple example of a Python function that takes a string input and returns the string in reverse order.",
"split": "train"
} |
import re
def replace_digits(input_string: str, replacement: str) -> str:
return re.sub(r'\d+', replacement, input_string)
| simplelr_Docs | [
{
"content": "Question:\n### Regular Expression Search and Replace\n\nIn this assessment, you will demonstrate your understanding of regular expressions by performing a search and replace operation on a string. You will be given a string containing a mix of letters, numbers, and special characters. Your task is... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7838,
"level": 1,
"question": "### Regular Expression Search and Replace\n\nIn this assessment, you will demonstrate your understanding of regular expressions by performing a search and replace operation on a string. You will be given a string containing a mix of letters, numbers, a... |
from typing import List
def smallest_in_rows(matrix: List[List[int]]) -> List[int]:
result = []
for row in matrix:
result.append(min(row))
return result | simplelr_Evol | [
{
"content": "Question:\nWrite a function that, given a rectangular matrix of integers, returns the smallest value in each row as a list. The matrix will be non-empty, and each row will contain at least one integer. Implement this function in Python, ensuring that it performs efficiently even for large matrices... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7839,
"level": 1,
"question": "Write a function that, given a rectangular matrix of integers, returns the smallest value in each row as a list. The matrix will be non-empty, and each row will contain at least one integer. Implement this function in Python, ensuring that it performs ... |
def can_sort_by_adjacent_swaps(nums):
return True | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` containing `n` unique numbers in the range from `1` to `n`. The array may be shuffled and may contain any permutation of these numbers. Your task is to determine if it is possible to sort this array in ascending order by performing a series of opera... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7840,
"level": 1,
"question": "You are given an integer array `nums` containing `n` unique numbers in the range from `1` to `n`. The array may be shuffled and may contain any permutation of these numbers. Your task is to determine if it is possible to sort this array in ascending or... |
import seaborn.objects as so
from seaborn import load_dataset
def analyze_tips_data():
# Load the dataset
tips = load_dataset("tips")
# Plot 1: Total number of tips given each day
so.Plot(tips, x="day").add(so.Bar(), so.Count()).show()
# Plot 2: Total number of tips given each day, separated by s... | simplelr_Docs | [
{
"content": "Question:\n**Question: Analyzing Restaurant Tips Data Using Seaborn**\n\nGiven the seaborn `tips` dataset, we would like to perform a visual analysis of the dataset using Seaborn's object-oriented interface. Specifically, we aim to investigate how different variables impact the tips given by custo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7841,
"level": 1,
"question": "**Question: Analyzing Restaurant Tips Data Using Seaborn**\n\nGiven the seaborn `tips` dataset, we would like to perform a visual analysis of the dataset using Seaborn's object-oriented interface. Specifically, we aim to investigate how different varia... |
def int_to_roman(num):
roman_numerals = [
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(90, 'XC'),
(50, 'L'),
(40, 'XL'),
(10, 'X'),
(9, 'IX'),
(5, 'V'),
(4, 'IV'),
(1, 'I')
]
result = "... | simplelr_Taco | [
{
"content": "Question:\nWrite a function that converts a given integer to its corresponding Roman numeral representation. The input will be a positive integer within the range from 1 to 3999. The function should return a string representing the Roman numeral.\n\nFor example: \n- input = 9 should return \"IX\"\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7842,
"level": 1,
"question": "Write a function that converts a given integer to its corresponding Roman numeral representation. The input will be a positive integer within the range from 1 to 3999. The function should return a string representing the Roman numeral.\n\nFor example: ... |
def check_leap_year(year: int) -> None:
"""Checks if a given year is a leap year and prints the result.
A leap year is exactly divisible by 4 except for century years (years ending with 00).
The century year is a leap year only if it is perfectly divisible by 400.
Args:
year (int): The year to... | simplelr_Filter | [
{
"content": "Question:\nCan you write a Python function that checks if a given year is a leap year and returns a message indicating whether it is a leap year or not? A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly di... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7843,
"level": 1,
"question": "Can you write a Python function that checks if a given year is a leap year and returns a message indicating whether it is a leap year or not? A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a l... |
from collections import defaultdict, deque
from typing import List, Tuple
def longest_chain(edits: List[str], references: List[Tuple[str, str]]) -> int:
if not edits:
return 0
# Build the graph and in-degree dictionary
graph = defaultdict(list)
in_degree = defaultdict(int)
# Initi... | simplelr_Taco | [
{
"content": "Question:\nYou are working on a text-based collaborative document editor that tracks a sequence of edits made to a document. Each edit is represented by a string consisting of lowercase English letters and digits, which uniquely identify that edit. The edits form a chain, with each edit confirming... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7844,
"level": 1,
"question": "You are working on a text-based collaborative document editor that tracks a sequence of edits made to a document. Each edit is represented by a string consisting of lowercase English letters and digits, which uniquely identify that edit. The edits form... |
def find_intersection(arr1: list, arr2: list) -> list:
# Check if both inputs are lists
if not isinstance(arr1, list) or not isinstance(arr2, list):
return []
# Convert arrays to sets to find unique elements
set1 = set(arr1)
set2 = set(arr2)
# Find the intersection of the two sets
co... | simplelr_Algorithm | [
{
"content": "Question:\n### Find the Intersection of Two Arrays\n\nWrite a function `find_intersection` that finds the intersection of two arrays.\n\n#### Function Signature\n```python\ndef find_intersection(arr1: list, arr2: list) -> list:\n pass\n```\n\n### Input\n- Two arrays `arr1` and `arr2` of integer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7845,
"level": 1,
"question": "### Find the Intersection of Two Arrays\n\nWrite a function `find_intersection` that finds the intersection of two arrays.\n\n#### Function Signature\n```python\ndef find_intersection(arr1: list, arr2: list) -> list:\n pass\n```\n\n### Input\n- Two ... |
def bacteria_count(hours):
return 2 ** hours | simplelr_Apps | [
{
"content": "Question:\nA renowned biologist is studying a species of rapidly multiplying bacteria. She notices that every hour, each bacterium doubles in count. She starts with a single bacterium. Your task is to calculate the total number of bacteria present after a given number of hours.\n\nWrite a function... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7846,
"level": 1,
"question": "A renowned biologist is studying a species of rapidly multiplying bacteria. She notices that every hour, each bacterium doubles in count. She starts with a single bacterium. Your task is to calculate the total number of bacteria present after a given n... |
def convert_list_to_integer(lst):
if not lst:
return 0 # or raise ValueError("List cannot be empty")
str_lst = ''
for integer in lst:
str_lst += str(integer)
return int(str_lst) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to convert a list of integers into a single integer.\n\n```python\ndef convert_list_to_integer(lst):\n # Initialize an empty string to store the integer values as strings\n str_lst = ''\n\n # Iterate through each integer in the list\n for integer in l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7847,
"level": 1,
"question": "Write a Python function to convert a list of integers into a single integer.\n\n```python\ndef convert_list_to_integer(lst):\n # Initialize an empty string to store the integer values as strings\n str_lst = ''\n\n # Iterate through each intege... |
def count_alphanumeric_characters(s):
count = 0
for char in s:
if char.isalnum():
count += 1
return count | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string as input and returns the count of all alphanumeric characters in the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7848,
"level": 1,
"question": "Create a function that takes a string as input and returns the count of all alphanumeric characters in the string.",
"split": "train"
} |
def uniqueSubstrings(N, S, M):
substr_set = set()
for i in range(N - M + 1):
substr = S[i:i+M]
substr_set.add(substr)
return len(substr_set)
| simplelr_Taco | [
{
"content": "Question:\nYou are given a string S of length N, consisting of lowercase alphabets and an integer M. You need to find the number of unique substrings of length M in the given string S.\n\nExample 1:\nInput:\nN = 5\nS = \"ababa\"\nM = 2\nOutput:\n2\nExplanation:\nThe unique substrings of length 2 a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7849,
"level": 1,
"question": "You are given a string S of length N, consisting of lowercase alphabets and an integer M. You need to find the number of unique substrings of length M in the given string S.\n\nExample 1:\nInput:\nN = 5\nS = \"ababa\"\nM = 2\nOutput:\n2\nExplanation:\n... |
def sum_of_primes_below_1000():
n = 999
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for p in range(2, int(n ** 0.5) + 1):
if sieve[p]:
for multiple in range(p * p, n + 1, p):
sieve[multiple] = False
return sum(i for i, is_prime in enumerate(sieve) if is_p... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes no arguments and returns the sum of all prime numbers less than 1000. You should define a helper function to determine whether a number is prime. Use the Sieve of Eratosthenes algorithm to generate the list of prime numbers. The function should be optimized ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7850,
"level": 1,
"question": "Create a function that takes no arguments and returns the sum of all prime numbers less than 1000. You should define a helper function to determine whether a number is prime. Use the Sieve of Eratosthenes algorithm to generate the list of prime numbers... |
def has_pair_sum(input_list, k):
seen = set()
for num in input_list:
complement = k - num
if complement in seen:
return True
seen.add(num)
return False
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers and an integer `k`, write a function that determines if any two distinct numbers from the list add up to `k`. Return a boolean value: `True` if such a pair exists, `False` otherwise.\n\nFor example:\n- For `input_list = [10, 15, 3, 7]` and `k = 17`, the function... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7851,
"level": 1,
"question": "Given a list of integers and an integer `k`, write a function that determines if any two distinct numbers from the list add up to `k`. Return a boolean value: `True` if such a pair exists, `False` otherwise.\n\nFor example:\n- For `input_list = [10, 15... |
def union(set1, set2):
return set1 | set2 | simplelr_Filter | [
{
"content": "Question:\nDefine a function in Python to compute the union of two sets.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7852,
"level": 1,
"question": "Define a function in Python to compute the union of two sets.",
"split": "train"
} |
def is_case_sensitive_anagram(s1, s2):
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2) | simplelr_Apps | [
{
"content": "Question:\nCase-Sensitive Anagram Checker\n\nDesign a function called `is_case_sensitive_anagram(s1, s2)` that determines whether two given strings `s1` and `s2` are anagrams of each other, considering case sensitivity. \n\n### Input\n- Two strings, `s1` and `s2`, where 1 <= len(s1), len(s2) <= 10... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7853,
"level": 1,
"question": "Case-Sensitive Anagram Checker\n\nDesign a function called `is_case_sensitive_anagram(s1, s2)` that determines whether two given strings `s1` and `s2` are anagrams of each other, considering case sensitivity. \n\n### Input\n- Two strings, `s1` and `s2`... |
def balance_parentheses(s):
n = len(s)
left_include = [False] * n
right_include = [False] * n
# Left to Right pass
balance = 0
for i in range(n):
if s[i] == '(':
left_include[i] = True
balance += 1
else:
if balance > 0:
left_in... | simplelr_Taco | [
{
"content": "Question:\nMarie is a talented software engineer with a knack for balancing parentheses in programming languages. She has devised her own strategy for transforming any given string into a well-formed string with balanced parentheses. Here is how her strategy works:\n\nGiven a string consisting of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7854,
"level": 1,
"question": "Marie is a talented software engineer with a knack for balancing parentheses in programming languages. She has devised her own strategy for transforming any given string into a well-formed string with balanced parentheses. Here is how her strategy work... |
def sum_of_last_elements(matrix):
total_sum = 0
for row in matrix:
total_sum += row[-1]
return total_sum | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a matrix of numbers and returns the sum of the last elements of each row.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7855,
"level": 1,
"question": "Create a function that takes a matrix of numbers and returns the sum of the last elements of each row.",
"split": "train"
} |
def sum_of_integers_in_string(text: str) -> int:
sum_total = 0
current_num = 0
for char in text:
if char.isdigit():
current_num = current_num * 10 + int(char)
else:
sum_total += current_num
current_num = 0
sum_total += current_num # Add the last numbe... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n**Context**: Parsing and analyzing numerical data from strings is a common task in data processing. One particular operation involves extracting and summing integers from a given text.\n\n**Question**:\n\nImplement a function `sum_of_integers_in_string(... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7856,
"level": 1,
"question": "### Coding Assessment Question\n\n**Context**: Parsing and analyzing numerical data from strings is a common task in data processing. One particular operation involves extracting and summing integers from a given text.\n\n**Question**:\n\nImplement a f... |
def get_histogram(input_list: list) -> dict:
histogram = {}
for num in input_list:
if num in histogram:
histogram[num] += 1
else:
histogram[num] = 1
return histogram | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Histogram Calculation\n\nGiven an unordered list of integers, write a function `get_histogram(input_list: list) -> dict` that returns a histogram of the input list as a dictionary where the keys are the unique elements from the list, and the values are the counts of these ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7857,
"level": 1,
"question": "### Question: Histogram Calculation\n\nGiven an unordered list of integers, write a function `get_histogram(input_list: list) -> dict` that returns a histogram of the input list as a dictionary where the keys are the unique elements from the list, and ... |
def swap_dict_keys_values(d):
swapped = {}
for key, value in d.items():
if value not in swapped:
swapped[value] = key
else:
if isinstance(swapped[value], list):
swapped[value].append(key)
else:
old_value = swapped[value]
... | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a dictionary with some keys and values, and returns a new dictionary where the keys and values are swapped. If a value is not unique, append the keys to a list. For example, given the dictionary `{'a': 1, 'b': 2, 'c': 1}`, the function should return `... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7858,
"level": 1,
"question": "Create a Python function that takes a dictionary with some keys and values, and returns a new dictionary where the keys and values are swapped. If a value is not unique, append the keys to a list. For example, given the dictionary `{'a': 1, 'b': 2, 'c'... |
def get_last_n_elements(lst, n):
if n <= 0:
return []
return lst[-n:] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to retrieve the last n elements from a list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7859,
"level": 1,
"question": "Write a python function to retrieve the last n elements from a list.",
"split": "train"
} |
def count_unique_elements(elements: list) -> int:
unique = set()
for elem in elements:
if isinstance(elem, str):
elem = elem.lower()
unique.add(elem)
return len(unique) | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context\nYou are tasked to write a function that counts the number of unique elements in a given list while ignoring the case for string elements. The function should handle and preserve input types robustly, ensuring only valid inputs are processe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7860,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context\nYou are tasked to write a function that counts the number of unique elements in a given list while ignoring the case for string elements. The function should handle and preserve input types robustly, ensu... |
def tribonacci(a, b, c, n):
if n == 1:
return [a]
if n == 2:
return [a, b]
if n == 3:
return [a, b, c]
res = [a, b, c]
for i in range(3, n):
next_num = res[i-1] + res[i-2] + res[i-3]
res.append(next_num)
return res[:n] | simplelr_Apps | [
{
"content": "Question:\nConsider a modified version of the classic Fibonacci sequence problem. Instead of generating the usual Fibonacci sequence, generate a sequence where each number is the sum of the previous three numbers. This is commonly known as the Tribonacci sequence.\n\nYou will be given three initia... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7861,
"level": 1,
"question": "Consider a modified version of the classic Fibonacci sequence problem. Instead of generating the usual Fibonacci sequence, generate a sequence where each number is the sum of the previous three numbers. This is commonly known as the Tribonacci sequence... |
def largest_rectangle_area(heights):
n = len(heights)
if n == 0:
return 0
prev = [-1] * n
stack = []
for i in range(n):
while stack and heights[stack[-1]] >= heights[i]:
stack.pop()
if stack:
prev[i] = stack[-1]
else:
prev[i] =... | simplelr_Apps | [
{
"content": "Question:\nYou are given a list of non-negative integers representing the heights of vertically stacked bars of a histogram. Each bar is of fixed width 1. Compute the area of the largest possible rectangle that can be formed within the bounds of the histogram.\n\nYou should write a function that t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7862,
"level": 1,
"question": "You are given a list of non-negative integers representing the heights of vertically stacked bars of a histogram. Each bar is of fixed width 1. Compute the area of the largest possible rectangle that can be formed within the bounds of the histogram.\n\... |
import math
def cosine_similarity(A, B):
"""
Compute the cosine similarity between two vectors.
Args:
A (list): The first vector.
B (list): The second vector.
Returns:
float: The cosine similarity between A and B.
"""
if len(A) != len(B):
raise ValueErr... | simplelr_Filter | [
{
"content": "Question:\nHello, I have a question regarding the cosine similarity between two vectors. Could you provide a Python code snippet that calculates the cosine similarity between two vectors?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7863,
"level": 1,
"question": "Hello, I have a question regarding the cosine similarity between two vectors. Could you provide a Python code snippet that calculates the cosine similarity between two vectors?",
"split": "train"
} |
def final_lent_books(operations):
lent_books = []
lent_set = set()
for op in operations:
if op > 0:
book = op
if book not in lent_set:
lent_books.append(book)
lent_set.add(book)
else:
book = -op
if book in lent_s... | simplelr_Leetcode | [
{
"content": "Question:\nYou are managing a library that has a collection of books. Each book is identified by a unique ID represented as an integer. The library uses a system to lend and return books. You need to keep track of the current state of each book in the library. \n\nYou are given an integer array `o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7864,
"level": 1,
"question": "You are managing a library that has a collection of books. Each book is identified by a unique ID represented as an integer. The library uses a system to lend and return books. You need to keep track of the current state of each book in the library. \n... |
def insertion_sort(lst):
for i in range(1, len(lst)):
key = lst[i]
j = i-1
while j >= 0 and lst[j] > key:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key
return lst
# Example usage:
lst = [5, 2, 4, 6, 1, 3]
print("Original list:", lst)
print("Sorted list:", i... | simplelr_Filter | [
{
"content": "Question:\nComplete the following program to sort a list in ascending order using Insertion sort algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7865,
"level": 1,
"question": "Complete the following program to sort a list in ascending order using Insertion sort algorithm.",
"split": "train"
} |
def find_element_index(arr, target):
for index, value in enumerate(arr):
if value == target:
return index
return -1 | simplelr_Filter | [
{
"content": "Question:\nWrite a code to check if an element is present in an array and return its index. If the element is not found, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7866,
"level": 1,
"question": "Write a code to check if an element is present in an array and return its index. If the element is not found, return -1.",
"split": "train"
} |
from typing import List
def optimized_cocktail_shaker_sort(arr: List[int]) -> List[int]:
if not arr:
return []
n = len(arr)
left = 0
right = n - 1
while left < right:
# Left to Right pass
last_left_right = -1
swapped = False
for i in range(left, rig... | simplelr_Data_Structure | [
{
"content": "Question:\n**Question: Implement an Optimized Cocktail Shaker Sort**\n\nCocktail Shaker Sort is a comparison-based sorting algorithm that traverses through a list alternately from left to right and right to left, moving the largest or smallest elements to their correct positions. Your task is to i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7867,
"level": 1,
"question": "**Question: Implement an Optimized Cocktail Shaker Sort**\n\nCocktail Shaker Sort is a comparison-based sorting algorithm that traverses through a list alternately from left to right and right to left, moving the largest or smallest elements to their c... |
def nth_fibonacci(n: int) -> int:
if n == 0:
return 0
elif n == 1:
return 1
else:
a, b = 0, 1
for i in range(2, n + 1):
c = a + b
a = b
b = c
return b | simplelr_Algorithm | [
{
"content": "Question:\n**Problem Statement**:\n\nYou are required to implement a function that finds the `n`-th Fibonacci number, where `f(n)` is defined as follows:\n- `f(0) = 0`\n- `f(1) = 1`\n- `f(n) = f(n-1) + f(n-2)` for `n > 1`\n\nThe signature of the function is as follows:\n```python\ndef nth_fibonacc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7868,
"level": 1,
"question": "**Problem Statement**:\n\nYou are required to implement a function that finds the `n`-th Fibonacci number, where `f(n)` is defined as follows:\n- `f(0) = 0`\n- `f(1) = 1`\n- `f(n) = f(n-1) + f(n-2)` for `n > 1`\n\nThe signature of the function is as fo... |
def sum_of_squares(numbers):
sum_total = 0
for number in numbers:
sum_total += number ** 2
return sum_total
# Test the function with the list [1, 2, 3, 4, 5]
print(sum_of_squares([1, 2, 3, 4, 5])) # Output should be 55 | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers as input and returns the sum of the squares of the integers. Use a loop to iterate through the list and calculate the sum. Test the function with the list [1, 2, 3, 4, 5]. The output should be 55. \\n\nAnswer:\nLet's think step by st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7869,
"level": 1,
"question": "Write a Python function that takes a list of integers as input and returns the sum of the squares of the integers. Use a loop to iterate through the list and calculate the sum. Test the function with the list [1, 2, 3, 4, 5]. The output should be 55. \... |
def longest_subsequence_with_sum(nums, k):
n = len(nums)
INF = float('inf')
dp = [INF] * (n + 1)
dp[0] = 0 # base case: empty subsequence
for num in nums:
# Iterate from the current maximum possible length down to 1
for j in range(n, 0, -1):
if dp[j-1] != INF and dp... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums` and an integer `k`. Write a function to _find the length of the longest subsequence that appears in the same relative order as in `nums` and has a sum less than or equal to `k`_. A subsequence is a sequence that can be derived from the array by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7870,
"level": 1,
"question": "You are given an array of integers `nums` and an integer `k`. Write a function to _find the length of the longest subsequence that appears in the same relative order as in `nums` and has a sum less than or equal to `k`_. A subsequence is a sequence tha... |
import os
def find_max_file_size(directory):
max_size = 0
try:
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
try:
file_size = os.path.getsize(file_path)
if file_siz... | simplelr_Filter | [
{
"content": "Question:\nYou have been given a directory path containing some files and subdirectories. You need to write a Python script to find the maximum size of a file in the directory and all its subdirectories.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7871,
"level": 1,
"question": "You have been given a directory path containing some files and subdirectories. You need to write a Python script to find the maximum size of a file in the directory and all its subdirectories.",
"split": "train"
} |
import heapq
def find_mst_cost(graph: dict) -> int:
if not graph:
return 0
visited = set()
heap = []
# Choose a starting node
start_node = next(iter(graph.keys()))
visited.add(start_node)
# Initialize the heap with all edges from the start node
for edge in graph[s... | simplelr_Data_Structure | [
{
"content": "Question:\n**Question**: Implementing Prim's Algorithm with Edge Cases\n\nIn this question, you will implement Prim's Minimum Spanning Tree (MST) algorithm. You are provided with a connected, undirected graph in the form of a dictionary where the keys are node identifiers and the values are lists ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7872,
"level": 1,
"question": "**Question**: Implementing Prim's Algorithm with Edge Cases\n\nIn this question, you will implement Prim's Minimum Spanning Tree (MST) algorithm. You are provided with a connected, undirected graph in the form of a dictionary where the keys are node id... |
def count_strings_with_two_vowels(string_list):
vowels = {'a', 'e', 'i', 'o', 'u'}
count = 0
for s in string_list:
num_vowels = sum(1 for c in s.lower() if c in vowels)
if num_vowels == 2:
count += 1
return count
# Example usage
strings = ["apple", "banana", "test", "beer", ... | simplelr_Filter | [
{
"content": "Question:\nI have a list of strings, and I want to find how many strings in this list contain exactly two vowels. Can you provide a Python code to achieve this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7873,
"level": 1,
"question": "I have a list of strings, and I want to find how many strings in this list contain exactly two vowels. Can you provide a Python code to achieve this?",
"split": "train"
} |
def dot_product(vector1, vector2):
result = 0
for a, b in zip(vector1, vector2):
result += a * b
return result
# Example usage
vector_a = [1, 2, 3]
vector_b = [4, 5, 6]
print("Dot Product:", dot_product(vector_a, vector_b)) | simplelr_Filter | [
{
"content": "Question:\nWrite a computer code snippet to calculate the dot product of two 3-dimensional vectors.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7874,
"level": 1,
"question": "Write a computer code snippet to calculate the dot product of two 3-dimensional vectors.",
"split": "train"
} |
def convert_and_prefix(input_string):
return "Prefix-" + input_string.upper() | simplelr_Filter | [
{
"content": "Question:\nHow can I create a function in Python that converts a given string to uppercase and adds a prefix \"Prefix-\" to it?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7875,
"level": 1,
"question": "How can I create a function in Python that converts a given string to uppercase and adds a prefix \"Prefix-\" to it?",
"split": "train"
} |
def range_query_sums(nums, queries):
if not nums:
return [0] * len(queries)
prefix = [0]
for num in nums:
prefix.append(prefix[-1] + num)
results = []
for start, end in queries:
results.append(prefix[end + 1] - prefix[start])
return results | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that performs efficient range queries on a list of integers. The function should take as input a list of integers `nums` and a list of query ranges `queries`, where each query is a tuple `(start, end)` representing the start and end indices of the range. The func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7876,
"level": 1,
"question": "Write a Python function that performs efficient range queries on a list of integers. The function should take as input a list of integers `nums` and a list of query ranges `queries`, where each query is a tuple `(start, end)` representing the start and... |
from typing import List
def rearrange_books(n: int, titles: List[str]) -> List[str]:
return titles[1::2] + titles[0::2] | simplelr_Code_Contests | [
{
"content": "Question:\nAlice has N distinct books placed sequentially on a shelf. She wants to rearrange the books such that all even-numbered books (based on their initial position) come before the odd-numbered books. The relative order of the books within each group (even or odd) should remain unchanged. Th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7877,
"level": 1,
"question": "Alice has N distinct books placed sequentially on a shelf. She wants to rearrange the books such that all even-numbered books (based on their initial position) come before the odd-numbered books. The relative order of the books within each group (even ... |
import math
def least_prime_factor(n: int) -> int:
if n < 2:
return 0
sqrt_n = int(math.sqrt(n))
for i in range(2, sqrt_n + 1):
if n % i == 0:
return i
return n | simplelr_Algorithm | [
{
"content": "Question:\n### Least Prime Factor of a Number\n\n**Context**:\nIn number theory, the least prime factor (LPF) of a number `n` greater than 1 is the smallest prime number that divides `n`. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. \n\nG... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7878,
"level": 1,
"question": "### Least Prime Factor of a Number\n\n**Context**:\nIn number theory, the least prime factor (LPF) of a number `n` greater than 1 is the smallest prime number that divides `n`. A prime number is a natural number greater than 1 that has no positive divi... |
def find_max_value(arr):
return max(arr) if arr else None | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in an array and returns the maximum value found in that array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7879,
"level": 1,
"question": "Create a function that takes in an array and returns the maximum value found in that array.",
"split": "train"
} |
def longest_subarray(string_list):
if not string_list:
return 0 # Though the problem states output is more than 0, this case is handled.
max_length = 1
current_length = 1
for i in range(1, len(string_list)):
if string_list[i] == string_list[i - 1]:
current_length += 1
... | simplelr_Filter | [
{
"content": "Question:\nI am provided a list of strings for which I want to find the length of the longest subarray such that all strings in the subarray are equal.\n\nHere is a sample input: [\"hello\", \"world\", \"hello\", \"hello\", \"world\"]\n\nHere is the sample output: 2\n\nNote: The output will always... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7880,
"level": 1,
"question": "I am provided a list of strings for which I want to find the length of the longest subarray such that all strings in the subarray are equal.\n\nHere is a sample input: [\"hello\", \"world\", \"hello\", \"hello\", \"world\"]\n\nHere is the sample output... |
def maxSubarraySum(nums):
current_max = max_so_far = nums[0]
for num in nums[1:]:
current_max = max(num, current_max + num)
max_so_far = max(max_so_far, current_max)
return max_so_far | simplelr_Codeforces | [
{
"content": "Question:\nGiven an array of integers, you need to find the maximum sum of any non-empty subarray of the array. A subarray is defined as a contiguous part of the array. The sum of a subarray is the sum of all its elements.\n\nWrite a function `maxSubarraySum(nums: List[int]) -> int` that takes a l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7881,
"level": 1,
"question": "Given an array of integers, you need to find the maximum sum of any non-empty subarray of the array. A subarray is defined as a contiguous part of the array. The sum of a subarray is the sum of all its elements.\n\nWrite a function `maxSubarraySum(nums... |
from typing import List
def can_partition(nums: List[int]) -> bool:
total = sum(nums)
if total % 2 != 0:
return False
target = total // 2
dp = [False] * (target + 1)
dp[0] = True
for num in nums:
for i in range(target, num - 1, -1):
if dp[i - num]:
dp... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question - Partition Equal Subset Sum\n\nGiven a non-empty array `nums` containing only positive integers, determine if it can be partitioned into two subsets, such that the sum of the elements in both subsets is equal. Return a boolean value.\n\n### Function Signature\n```py... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7882,
"level": 1,
"question": "### Coding Question - Partition Equal Subset Sum\n\nGiven a non-empty array `nums` containing only positive integers, determine if it can be partitioned into two subsets, such that the sum of the elements in both subsets is equal. Return a boolean valu... |
def fibonacci(n):
# Initialize the memoization dictionary if it doesn't exist
if not hasattr(fibonacci, 'memo'):
fibonacci.memo = {0: 0, 1: 1}
# Check if the value is already in the memo
if n in fibonacci.memo:
return fibonacci.memo[n]
# If not, compute the value
result... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to compute the nth Fibonacci number using recursion. The function should also ensure that the calculation is efficient by memoizing the results of previous calculations. Explain the concept and provide the code.\nAnswer:\nLet's think step by step.\n",
"role": "user"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7883,
"level": 1,
"question": "Write a function to compute the nth Fibonacci number using recursion. The function should also ensure that the calculation is efficient by memoizing the results of previous calculations. Explain the concept and provide the code.",
"split": "train"
} |
from collections import Counter
def can_transform(str1, str2):
return Counter(str1) == Counter(str2) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings `str1` and `str2` of the same length `n`. You can swap any two characters in `str1` any number of times. Your task is to determine if it is possible to transform `str1` into `str2` using these swaps. Return `true` if it is possible to transform `str1` into `str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7884,
"level": 1,
"question": "You are given two strings `str1` and `str2` of the same length `n`. You can swap any two characters in `str1` any number of times. Your task is to determine if it is possible to transform `str1` into `str2` using these swaps. Return `true` if it is pos... |
def findWays(n):
MOD = 10**9 + 7
if n == 1:
return 1
elif n == 2:
return 2
a, b, c = 1, 1, 2 # f(0), f(1), f(2)
for i in range(3, n + 1):
next_val = (a + b + c) % MOD
a, b, c = b, c, next_val
return c | simplelr_Code_Contests | [
{
"content": "Question:\nSuppose you are given the following task: You need to write a function **findWays(n)** that determines the number of distinct ways to climb a staircase with **n** steps, where at each step you can either climb **1 step**, **2 steps**, or **3 steps**. Your function should return the numb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7885,
"level": 1,
"question": "Suppose you are given the following task: You need to write a function **findWays(n)** that determines the number of distinct ways to climb a staircase with **n** steps, where at each step you can either climb **1 step**, **2 steps**, or **3 steps**. Y... |
def flatten_list(list_of_lists):
flattened_list = []
for sublist in list_of_lists:
for element in sublist:
flattened_list.append(element)
return flattened_list | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert a list of lists into a single flattened list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7886,
"level": 1,
"question": "Write a python function to convert a list of lists into a single flattened list.",
"split": "train"
} |
def reverse_case(s):
return ''.join([char.lower() if char.isupper() else char.upper() if char.islower() else char for char in s]) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to reverse the uppercase and lowercase letters of a given string. For example, the input \"Hello World!\" should yield \"hELLO wORLD!\". How can I achieve this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7887,
"level": 1,
"question": "Write a python function to reverse the uppercase and lowercase letters of a given string. For example, the input \"Hello World!\" should yield \"hELLO wORLD!\". How can I achieve this?",
"split": "train"
} |
def is_valid_format(s):
if not s:
return False
if not s[0].isupper():
return False
if not any(c.isdigit() for c in s):
return False
if s[-1] not in ['.', '!', '?']:
return False
return True | simplelr_Evol | [
{
"content": "Question:\nDefine a function that checks if a string complies with a set of formatting rules:\n\ndef is_valid_format(s):\n \"\"\"\n This function takes a string s and returns True if it adheres to the following rules:\n 1. The string must start with a capital letter.\n 2. The string mu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7888,
"level": 1,
"question": "Define a function that checks if a string complies with a set of formatting rules:\n\ndef is_valid_format(s):\n \"\"\"\n This function takes a string s and returns True if it adheres to the following rules:\n 1. The string must start with a ca... |
def process_string(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
consonants = [c for c in s if c.lower() not in vowels]
reversed_consonants = consonants[::-1]
cons_iter = iter(reversed_consonants)
transformed = []
for c in s:
if c.lower() in vowels:
transformed.append(c.upper())
... | simplelr_Filter | [
{
"content": "Question:\nCreate a function in python that takes a string as an argument and prints out three copies of the string, but with all vowels capitalized and all consonants in reverse order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7889,
"level": 1,
"question": "Create a function in python that takes a string as an argument and prints out three copies of the string, but with all vowels capitalized and all consonants in reverse order.",
"split": "train"
} |
def isPalindromePermutation(s: str) -> bool:
# Preprocess the string: remove spaces and convert to lowercase
filtered_str = s.replace(' ', '').lower()
# Count the frequency of each character
char_count = {}
for char in filtered_str:
char_count[char] = char_count.get(char, 0) + 1
... | simplelr_Apps | [
{
"content": "Question:\nWrite a function `isPalindromePermutation` that determines if a given string is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards (ignoring spaces and punctuation), and a permutation is a rearrangement of letters. The function should... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7890,
"level": 1,
"question": "Write a function `isPalindromePermutation` that determines if a given string is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards (ignoring spaces and punctuation), and a permutation is a rearrangem... |
def compare_strings(str1, str2):
processed1 = ''.join([c.lower() for c in str1 if c.isalpha()])
processed2 = ''.join([c.lower() for c in str2 if c.isalpha()])
return processed1 == processed2 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in two string arguments, `str1` and `str2`. The function should convert both string arguments to lower case and check if they are the same. If they are the same, return True; otherwise, return False. Additionally, the function should ignore any non-alphabeti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7891,
"level": 1,
"question": "Create a function that takes in two string arguments, `str1` and `str2`. The function should convert both string arguments to lower case and check if they are the same. If they are the same, return True; otherwise, return False. Additionally, the funct... |
def check_distances(s, distance):
char_indices = {}
for i, c in enumerate(s):
if c not in char_indices:
char_indices[c] = []
char_indices[c].append(i)
for c in char_indices:
indices = char_indices[c]
if len(indices) < 2:
continue
min_dist ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters, and an array `distance` of length 26 where each element `distance[i]` represents the minimum required distance between the two occurrences of the character `'a' + i` in the string. Return `true` _if the string `s` meets... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7892,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters, and an array `distance` of length 26 where each element `distance[i]` represents the minimum required distance between the two occurrences of the character `'a' + i` in the string. Ret... |
def product_except_self(nums):
n = len(nums)
if n == 0:
return []
prefix = [0] * n
suffix = [0] * n
# Compute prefix products
prefix[0] = 1
for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]
# Compute suffix products
suffix[-1] = 1
for i in r... | simplelr_Apps | [
{
"content": "Question:\nGiven a list of integers, return a new list such that each element at index `i` of the new list is the product of all the numbers in the original list except the one at `i`.\n\nExample input:\n\n```\n[1, 2, 3, 4]\n[4, 5, 6]\n```\n\nExpected output:\n\n```\n[24, 12, 8, 6]\n[30, 24, 20]\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7893,
"level": 1,
"question": "Given a list of integers, return a new list such that each element at index `i` of the new list is the product of all the numbers in the original list except the one at `i`.\n\nExample input:\n\n```\n[1, 2, 3, 4]\n[4, 5, 6]\n```\n\nExpected output:\n\n... |
def longest_common_substring(str1: str, str2: str) -> str:
m, n = len(str1), len(str2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
longest_length = 0
end_index = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i - 1] == str2[j - 1]:
dp[i][j] = dp[i -... | simplelr_Algorithm | [
{
"content": "Question:\n### Longest Common Substring Coding Challenge\n\n#### Context\nFinding the longest common substring between two strings is a classic problem in computer science, useful in various applications such as bioinformatics, text analysis, and plagiarism detection. You are tasked with implement... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7894,
"level": 1,
"question": "### Longest Common Substring Coding Challenge\n\n#### Context\nFinding the longest common substring between two strings is a classic problem in computer science, useful in various applications such as bioinformatics, text analysis, and plagiarism detec... |
def first_blocker(arr):
stack = []
result = []
for num in arr:
while stack and stack[-1] <= num:
stack.pop()
if not stack:
result.append(-1)
else:
result.append(stack[-1])
stack.append(num)
return result | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of integers `arr` representing the heights of skyscrapers in a city. A building can receive sunlight if there are no taller buildings to its left. Return a list of integers where each element represents the height of the first building (from the left) that blocks th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7895,
"level": 1,
"question": "You are given a list of integers `arr` representing the heights of skyscrapers in a city. A building can receive sunlight if there are no taller buildings to its left. Return a list of integers where each element represents the height of the first buil... |
import re
def create_sentence_graph(file_path: str) -> dict:
try:
with open(file_path, 'r') as f:
content = f.read().strip()
except:
return {}
if not content:
return {}
sentences = re.findall(r'[^.!?]*[.!?]+', content)
sentences = [s.strip() for s in se... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\nYou are asked to implement a function that takes a text file with multiple sentences and transforms it into a system where each sentence is represented as a node in a graph. This tests your understanding of file I/O, string manipulation, and basic graph... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7896,
"level": 1,
"question": "### Coding Assessment Question\n\nYou are asked to implement a function that takes a text file with multiple sentences and transforms it into a system where each sentence is represented as a node in a graph. This tests your understanding of file I/O, s... |
def is_power_of_three(n):
if n < 1:
return False
if n != int(n):
return False
while n % 3 == 0:
n = n // 3
return n == 1 | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given number is a power of three. The function should return `True` if the number is a power of three, and `False` otherwise. A number is a power of three if it can be expressed as \\(3^k\\) for some integer \\(k\\).\nAnswer:\nLet's think step by step.\n",... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7897,
"level": 1,
"question": "Write a function to check if a given number is a power of three. The function should return `True` if the number is a power of three, and `False` otherwise. A number is a power of three if it can be expressed as \\(3^k\\) for some integer \\(k\\).",
... |
def can_form_palindrome(s):
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
odd_count = 0
for count in counts.values():
if count % 2 != 0:
odd_count += 1
return odd_count <= 1 | simplelr_Apps | [
{
"content": "Question:\nGiven a string containing only lowercase alphabetical characters, write a function that determines if the string can be rearranged to form a palindrome. A palindrome is a word that reads the same forward and backward. If the string can be rearranged into a palindrome, return true; other... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7898,
"level": 1,
"question": "Given a string containing only lowercase alphabetical characters, write a function that determines if the string can be rearranged to form a palindrome. A palindrome is a word that reads the same forward and backward. If the string can be rearranged in... |
def stoogesort(arr: list[int], l: int, h: int) -> None:
if l >= h:
return
if arr[l] > arr[h]:
arr[l], arr[h] = arr[h], arr[l]
if h - l + 1 <= 2:
return
m = (h - l + 1) // 3
stoogesort(arr, l, h - m)
stoogesort(arr, l + m, h)
stoogesort(arr, l, h - m) | simplelr_Data_Structure | [
{
"content": "Question:\n### Stooge Sort Implementation Challenge\n\n**Scenario**: \n\nYou are required to implement the Stooge Sort algorithm, a recursive sorting method characterized by its peculiar recursive steps. Stooge Sort, typically used for academic demonstrations, rearranges elements such that every s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7899,
"level": 1,
"question": "### Stooge Sort Implementation Challenge\n\n**Scenario**: \n\nYou are required to implement the Stooge Sort algorithm, a recursive sorting method characterized by its peculiar recursive steps. Stooge Sort, typically used for academic demonstrations, re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.