target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
from collections import Counter
def max_reversed_pairs(words):
word_counts = Counter(words)
processed = set()
total = 0
for word in word_counts:
if word in processed:
continue
rev_word = word[::-1]
if rev_word not in word_counts:
continue
if word... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are given a `words` list of strings, where each string consists of only lowercase English letters. Your task is to write a function that determines the maximum number of non-overlapping subsequential pairs of strings from the list such that the reversed versio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2200,
"level": 1,
"question": "### Problem Statement\nYou are given a `words` list of strings, where each string consists of only lowercase English letters. Your task is to write a function that determines the maximum number of non-overlapping subsequential pairs of strings from the... |
def intersection(list1, list2):
seen_in_first = {}
result = []
for element in list1:
if element not in seen_in_first:
seen_in_first[element] = True
for element in list2:
if element in seen_in_first:
result.append(element)
del seen_in_first[element]
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that takes two lists as arguments and returns a new list containing the elements that appear in both lists. Implement a time-efficient solution without using any built-in functions such as intersection methods or data structures like sets. Your code should only us... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2201,
"level": 1,
"question": "Write a Python program that takes two lists as arguments and returns a new list containing the elements that appear in both lists. Implement a time-efficient solution without using any built-in functions such as intersection methods or data structures ... |
def minPathSum(grid):
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
continue
elif i == 0:
grid[i][j] += grid[i][j-1]
elif j == 0:
grid[i][j... | simplelr_Evol | [
{
"content": "Question:\nGiven a grid of size m x n filled with non-negative integers, you are initially positioned at the top-left corner of the grid. You are required to traverse the grid and reach the bottom-right corner. You can only move either down or right at any point in time. Find the minimum sum of th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2202,
"level": 1,
"question": "Given a grid of size m x n filled with non-negative integers, you are initially positioned at the top-left corner of the grid. You are required to traverse the grid and reach the bottom-right corner. You can only move either down or right at any point ... |
from typing import List, Callable, Dict
import timeit
def compare_execution_times(functions: List[Callable[[], None]], number: int = 100000) -> Dict[str, float]:
result = {}
for func in functions:
func_name = func.__name__
execution_time = timeit.timeit(func, number=number)
rounded_time... | simplelr_Docs | [
{
"content": "Question:\n### Question: Measuring Code Performance with `timeit`\n\nYou are given a list of various Python functions, and you need to measure their execution times to determine their performance efficiency. Implement a Python function `compare_execution_times` that takes a list of function defini... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2203,
"level": 1,
"question": "### Question: Measuring Code Performance with `timeit`\n\nYou are given a list of various Python functions, and you need to measure their execution times to determine their performance efficiency. Implement a Python function `compare_execution_times` t... |
def first_greater_than_zero(arr):
for num in arr:
if num > 0:
return num
return None | simplelr_Filter | [
{
"content": "Question:\nTranslate the following pseudocode into a python function that takes an array as input and returns the first element in the array that is greater than zero.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2204,
"level": 1,
"question": "Translate the following pseudocode into a python function that takes an array as input and returns the first element in the array that is greater than zero.",
"split": "train"
} |
def find_missing_number(arr: list[int]) -> int:
l = len(arr)
n = l + 1
m = n - 1
# Compute total_xor using the formula based on mod 4
mod = m % 4
if mod == 0:
total_xor = m
elif mod == 1:
total_xor = 1
elif mod == 2:
total_xor = m + 1
else:
total_... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Find the Missing Number in an Array Using XOR\n\n#### Problem Statement\nYou are given an array containing `n - 1` unique numbers taken from the range `0` to `n - 1` (inclusive). This means that exactly one number is missing from the array. Your task is to write a function... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2205,
"level": 1,
"question": "### Question: Find the Missing Number in an Array Using XOR\n\n#### Problem Statement\nYou are given an array containing `n - 1` unique numbers taken from the range `0` to `n - 1` (inclusive). This means that exactly one number is missing from the arra... |
from itertools import combinations
from collections import defaultdict
def find_potential_duplicates(users: list[dict]) -> list[tuple[int, int]]:
name_map = defaultdict(list)
email_map = defaultdict(list)
pairs = set()
# Build the name and email maps
for user in users:
user_id = user['id']... | simplelr_Algorithm | [
{
"content": "Question:\n## Problem Statement\n\n### Context\nYour team is working on analyzing large datasets containing user information. One common task is to identify and extract information on potential duplicate entries based on user names and email addresses. This helps in cleansing the data and maintain... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2206,
"level": 1,
"question": "## Problem Statement\n\n### Context\nYour team is working on analyzing large datasets containing user information. One common task is to identify and extract information on potential duplicate entries based on user names and email addresses. This helps... |
import keyword
def classify_keywords(word_list: list) -> dict:
result = {
"keyword": [],
"soft keyword": [],
"identifier": []
}
soft_keywords = set(keyword.softkwlist)
for word in word_list:
if keyword.iskeyword(word):
result["keyword"].append(word)
... | simplelr_Docs | [
{
"content": "Question:\n**Coding Question:**\n\nYou are given a list of strings. Your task is to implement a function `classify_keywords(word_list)` that processes this list and returns a dictionary classifying each string into one of three categories:\n1. \"keyword\" if the string is a Python keyword.\n2. \"s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2207,
"level": 1,
"question": "**Coding Question:**\n\nYou are given a list of strings. Your task is to implement a function `classify_keywords(word_list)` that processes this list and returns a dictionary classifying each string into one of three categories:\n1. \"keyword\" if the ... |
def is_valid_ipv4(ip):
parts = ip.split('.')
if len(parts) != 4:
return False
for part in parts:
if not part or not part.isdigit():
return False
if len(part) > 1 and part[0] == '0':
return False
if not (0 <= int(part) <= 255):
return False
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check whether a string is a valid IPv4 address. A valid IPv4 address is defined as a string that consists of four decimal numbers, each number ranging from 0 to 255, separated by dots.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2208,
"level": 1,
"question": "Write a function to check whether a string is a valid IPv4 address. A valid IPv4 address is defined as a string that consists of four decimal numbers, each number ranging from 0 to 255, separated by dots.",
"split": "train"
} |
import operator
def process_student_records(students: list) -> list:
# Step 1: Filter students with grade >= 70 using operator.ge
filtered = list(filter(lambda x: operator.ge(x['grade'], 70), students))
# Step 2: Sort the filtered students by grade descending and then name ascending
sorted_student... | simplelr_Docs | [
{
"content": "Question:\n### Coding Challenge: Data Manipulation Using Operator Module\n\n**Objective**:\nWrite a Python function that processes a list of dictionaries representing student records and performs the following operations using the `operator` module functions:\n\n1. **Filter**: Filter out records w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2209,
"level": 1,
"question": "### Coding Challenge: Data Manipulation Using Operator Module\n\n**Objective**:\nWrite a Python function that processes a list of dictionaries representing student records and performs the following operations using the `operator` module functions:\n\n... |
def caesar_cipher(message, shift, mode):
effective_shift = shift if mode == 'encrypt' else -shift
result = []
for char in message:
if ('A' <= char <= 'Z') or ('a' <= char <= 'z'):
if char.islower():
base = ord('a')
else:
base = ord('A')
... | simplelr_Package | [
{
"content": "Question:\n**\n\nCreate a function that mimics simple encrypted communication using the Caesar Cipher technique. The function should be able to both encrypt and decrypt messages by shifting each letter by a specified number of positions in the alphabet.\n\n**Function Specification:**\n- Function N... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2210,
"level": 1,
"question": "**\n\nCreate a function that mimics simple encrypted communication using the Caesar Cipher technique. The function should be able to both encrypt and decrypt messages by shifting each letter by a specified number of positions in the alphabet.\n\n**Func... |
def convert_and_filter_temperatures(temperatures):
# Convert each temperature to Fahrenheit and filter out those below 0°C
return [(temp * 9/5) + 32 for temp in temperatures if temp >= 0] | simplelr_Evol | [
{
"content": "Question:\nConvert the following function written in Python to an efficient and optimized function using list comprehensions and other useful functions from the standard library. The function takes a list of temperatures in Celsius and converts them to Fahrenheit. Temperatures below 0°C should be ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2211,
"level": 1,
"question": "Convert the following function written in Python to an efficient and optimized function using list comprehensions and other useful functions from the standard library. The function takes a list of temperatures in Celsius and converts them to Fahrenheit... |
def levenshtein_distance(s1, s2):
m = len(s1)
n = len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Initialize the first row and column
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
# Fill in the rest of the matrix
for i in range(1, m + 1):
... | simplelr_Filter | [
{
"content": "Question:\nGiven 2 strings, \"Python\" and \"Programming\", write a Python function to calculate the Levenshtein distance between them. The Levenshtein distance is a string metric for measuring difference between two sequences. It is the minimum number of single-character edits (insertions, deleti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2212,
"level": 1,
"question": "Given 2 strings, \"Python\" and \"Programming\", write a Python function to calculate the Levenshtein distance between them. The Levenshtein distance is a string metric for measuring difference between two sequences. It is the minimum number of single-... |
def convert(s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = [''] * numRows
cycle = 2 * (numRows - 1)
for i, c in enumerate(s):
k = i % cycle
if k < numRows:
row = k
else:
row = cycle - k
rows[row] += c
return ''.join(rows... | simplelr_Leetcode | [
{
"content": "Question:\nWrite a function to transform a given string `s` to its zigzag conversion with a given number of rows `numRows`. The function should return the string that reads line by line. For example, the string \"PAYPALISHIRING\" with 3 rows would be transformed to:\n\n```\nP A H N\nA P L S ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2213,
"level": 1,
"question": "Write a function to transform a given string `s` to its zigzag conversion with a given number of rows `numRows`. The function should return the string that reads line by line. For example, the string \"PAYPALISHIRING\" with 3 rows would be transformed ... |
def sum_even_numbers(a, b):
if a > b:
return 0
total = 0
for num in range(a, b + 1):
if num % 2 == 0:
total += num
return total | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the sum of all even numbers between two given positive integers `a` and `b` (inclusive). If `a` is greater than `b`, the function should return 0. If there are no even numbers in the range `[a, b]`, also return 0.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2214,
"level": 1,
"question": "Write a python function to find the sum of all even numbers between two given positive integers `a` and `b` (inclusive). If `a` is greater than `b`, the function should return 0. If there are no even numbers in the range `[a, b]`, also return 0.",
"s... |
import math
def calculate_discount(amount, discount_percentage, min_discount):
"""
This function calculates the discount amount for a given transaction.
Parameters:
amount (float): The total amount of the transaction.
discount_percentage (float): The percentage of discount to be applied.
m... | simplelr_Filter | [
{
"content": "Question:\nI am trying to code an accounting system, and I want to add a discount to specific transactions. To do that, I need a function that takes an amount, discount percentage, and a minimum discount amount. The function should return the discount amount. \n\nHowever, I have a condition: if th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2215,
"level": 1,
"question": "I am trying to code an accounting system, and I want to add a discount to specific transactions. To do that, I need a function that takes an amount, discount percentage, and a minimum discount amount. The function should return the discount amount. \n\... |
def square_list(numbers):
"""Squares each number in a list."""
squared_numbers = []
for number in numbers:
squared_numbers.append(number ** 2)
return squared_numbers | simplelr_Filter | [
{
"content": "Question:\nThis is an example of a function that squares a number:\n\n```python\ndef square(number):\n \"\"\"Squares a number.\"\"\"\n return number * number\n```\n\nHow can I write a Python function that takes a list of numbers as input and returns a new list containing the squares of all the n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2216,
"level": 1,
"question": "This is an example of a function that squares a number:\n\n```python\ndef square(number):\n \"\"\"Squares a number.\"\"\"\n return number * number\n```\n\nHow can I write a Python function that takes a list of numbers as input and returns a new list ... |
def find_book(books, target):
low = 0
high = len(books) - 1
while low <= high:
mid = (low + high) // 2
if books[mid] == target:
return mid
elif books[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
| simplelr_Taco | [
{
"content": "Question:\n# Task\nAnna is a librarian in a large library. She is responsible for making sure all the books are arranged properly on the shelf. Each book has a unique identifier number. Anna needs to find a particular book as quickly as possible.\n\nWrite a function that takes in a list of unique ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2217,
"level": 1,
"question": "# Task\nAnna is a librarian in a large library. She is responsible for making sure all the books are arranged properly on the shelf. Each book has a unique identifier number. Anna needs to find a particular book as quickly as possible.\n\nWrite a funct... |
def decimal_to_roman(number: int) -> str:
if not isinstance(number, int) or number < 1 or number > 3999:
return ""
roman_numerals = [
(1000, 'M'), (900, 'CM'),
(500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'),
(50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'),
(5... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are tasked with implementing a function that converts a given decimal number into its equivalent Roman numeral representation. Roman numerals use combinations of letters from the Latin alphabet to represent values.\n\n### The context\nA software development co... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2218,
"level": 1,
"question": "### Problem Statement\nYou are tasked with implementing a function that converts a given decimal number into its equivalent Roman numeral representation. Roman numerals use combinations of letters from the Latin alphabet to represent values.\n\n### The... |
def sort_and_repeat(lst):
sorted_list = sorted(lst)
result = []
for index, num in enumerate(sorted_list):
repeats = index + 1
result.extend([str(num)] * repeats)
return ' '.join(result)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns a string containing those integers sorted in non-decreasing order, with each element repeated a number of times corresponding to its final sorted position + 1 (1-based index). Each group of repeated integers should be represente... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2219,
"level": 1,
"question": "Write a function that takes a list of integers and returns a string containing those integers sorted in non-decreasing order, with each element repeated a number of times corresponding to its final sorted position + 1 (1-based index). Each group of rep... |
from collections import Counter
def can_form_palindrome(s: str) -> str:
freq = Counter(s)
odd_count = 0
for count in freq.values():
if count % 2 != 0:
odd_count += 1
n = len(s)
if n % 2 == 0:
return "YES" if odd_count == 0 else "NO"
else:
return "YES" if odd_... | simplelr_Taco | [
{
"content": "Question:\nWrite a program to determine if any anagram of a given string is a palindrome. \n\nA palindrome is a word or phrase that reads the same forwards and backwards, ignoring spaces, punctuation, and capitalization. An anagram is a reordering of the letters of one word or phrase to form anoth... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2220,
"level": 1,
"question": "Write a program to determine if any anagram of a given string is a palindrome. \n\nA palindrome is a word or phrase that reads the same forwards and backwards, ignoring spaces, punctuation, and capitalization. An anagram is a reordering of the letters ... |
def two_sum(nums, target):
num_dict = {}
for index, num in enumerate(nums):
complement = target - num
if complement in num_dict:
return [num_dict[complement], index]
num_dict[num] = index
return [] | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code to solve the LeetCode problem \"Two Sum\"? The problem states that given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. You may assume that each input would have exactly one solution... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2221,
"level": 1,
"question": "Can you provide a Python code to solve the LeetCode problem \"Two Sum\"? The problem states that given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. You may assume that each in... |
def longest_arith_seq_length(arr):
n = len(arr)
if n < 2:
return 0
max_length = 2
prev_dp = {}
for i in range(1, n):
current_d = arr[i] - arr[i-1]
current_dp = {}
if current_d in prev_dp:
current_dp[current_d] = prev_dp[current_d] + 1
else:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array `arr` of integers, return the length of the longest arithmetic subarray in `arr`. An arithmetic subarray is a subarray that contains at least two integers and the difference between any two consecutive elements is the same across the subarray.\nAnswer:\nLet's think step b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2222,
"level": 1,
"question": "Given an array `arr` of integers, return the length of the longest arithmetic subarray in `arr`. An arithmetic subarray is a subarray that contains at least two integers and the difference between any two consecutive elements is the same across the sub... |
import bisect
def length_of_LIS(arr):
tails = []
for num in arr:
idx = bisect.bisect_left(tails, num)
if idx == len(tails):
tails.append(num)
else:
tails[idx] = num
return len(tails) | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of integers `arr`, return the length of the longest subsequence that can be derived from `arr` such that all elements of the subsequence are in strictly increasing order. The subsequence does not need to be contiguous, and the order of the elements in the subsequence should... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2223,
"level": 1,
"question": "Given a list of integers `arr`, return the length of the longest subsequence that can be derived from `arr` such that all elements of the subsequence are in strictly increasing order. The subsequence does not need to be contiguous, and the order of the... |
def calculate_fibonacci(n):
"""
Generates the first n numbers in the Fibonacci sequence.
Args:
n (int): The number of Fibonacci numbers to generate.
Returns:
list: A list containing the first n Fibonacci numbers. Returns an empty list if n is less than or equal to 0.
Examples:
... | simplelr_Evol | [
{
"content": "Question:\nDesign a Python function named `calculate_fibonacci(n)` that receives a single integer parameter `n` and returns the first `n` numbers in the Fibonacci sequence as a list. Ensure the function handles the base cases where `n` is less than or equal to 1 correctly, and returns an empty lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2224,
"level": 1,
"question": "Design a Python function named `calculate_fibonacci(n)` that receives a single integer parameter `n` and returns the first `n` numbers in the Fibonacci sequence as a list. Ensure the function handles the base cases where `n` is less than or equal to 1 ... |
def findShortestPath(grid, startX, startY, endX, endY):
# Check if the start or end is an obstacle
if grid[startX][startY] != 0 or grid[endX][endY] != 0:
return -1
# If start and end are the same point
if startX == endX and startY == endY:
return 0
rows = len(grid)
cols... | simplelr_Taco | [
{
"content": "Question:\nYou are designing a game where you need to navigate through a grid to reach a destination while avoiding obstacles. The grid is represented by a 2D array `grid`, where '0' represents an open cell and '1' represents an obstacle. You are given the starting point `(startX, startY)` and the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2225,
"level": 1,
"question": "You are designing a game where you need to navigate through a grid to reach a destination while avoiding obstacles. The grid is represented by a 2D array `grid`, where '0' represents an open cell and '1' represents an obstacle. You are given the starti... |
def sort_intervals(intervals):
return sorted(intervals, key=lambda x: x[0]) | simplelr_Filter | [
{
"content": "Question:\nYou have been tasked with writing a function that will sort a list of intervals based on their start values. The list of intervals is represented as a list of lists, where each sublist contains two integers representing the start and end values of an interval. The function should return... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2226,
"level": 1,
"question": "You have been tasked with writing a function that will sort a list of intervals based on their start values. The list of intervals is represented as a list of lists, where each sublist contains two integers representing the start and end values of an i... |
from collections import Counter
def can_form_from_rearrangement(s, substring):
len_s = len(s)
len_sub = len(substring)
# If the substring is empty, it's trivially True
if len_sub == 0:
return True
# If the substring is longer than the main string, it's impossible
if len_sub > len_s... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if a string and a substring of the same length can be formed by rearranging the characters of the string. For example, if the string is \"hello\" and the substring is \"oleh\", the function should return True because the characters can be rearranged to form... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2227,
"level": 1,
"question": "Create a function that checks if a string and a substring of the same length can be formed by rearranging the characters of the string. For example, if the string is \"hello\" and the substring is \"oleh\", the function should return True because the c... |
def canReachZero(arr):
return 0 in arr | simplelr_Codeforces | [
{
"content": "Question:\nYou are given an array of integers of length n. You can move through the array starting from any given position i, but the only allowed moves are jumps to index i+arr[i] or i-arr[i]. Your task is to determine if there is a way to reach the value 0 in the array by starting from any locat... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2228,
"level": 1,
"question": "You are given an array of integers of length n. You can move through the array starting from any given position i, but the only allowed moves are jumps to index i+arr[i] or i-arr[i]. Your task is to determine if there is a way to reach the value 0 in t... |
from typing import List
def find_single_number(nums: List[int]) -> int:
result = 0
for num in nums:
result ^= num
return result | simplelr_Data_Structure | [
{
"content": "Question:\nFinding the Single Unique Number Using XOR\n\n### Description\nYou are provided with an array of integers where every element appears exactly twice, except for one element that appears only once. Your task is to implement a function that identifies and returns this single element. The f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2229,
"level": 1,
"question": "Finding the Single Unique Number Using XOR\n\n### Description\nYou are provided with an array of integers where every element appears exactly twice, except for one element that appears only once. Your task is to implement a function that identifies and... |
def h(L):
if not L:
return 0 # though the problem states non-empty, handle edge case
binaries = [bin(x)[2:] for x in L]
max_len = max(len(b) for b in binaries)
padded = [b.zfill(max_len) for b in binaries]
new_bin = []
for i in range(max_len):
bits = [s[i] for s in pad... | simplelr_Taco | [
{
"content": "Question:\nYou are given n integers a1, a2, ..., an. Denote this list of integers as T.\n\nDefine a function h(L) that takes in a non-empty list of integers L.\n\nThe function will output another integer as follows:\n\n* First, convert each integer in L to its binary representation and pad them wi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2230,
"level": 1,
"question": "You are given n integers a1, a2, ..., an. Denote this list of integers as T.\n\nDefine a function h(L) that takes in a non-empty list of integers L.\n\nThe function will output another integer as follows:\n\n* First, convert each integer in L to its bi... |
def most_frequent_words(words, k):
# Count the frequency of each word
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# Sort the words by frequency (descending) and lexicographically (ascending fo... | simplelr_Taco | [
{
"content": "Question:\n# Task\nYou are given a list of strings `words` and an integer `k`. Your task is to find and return the `k` most frequent words from the list. The output words should be sorted by their frequency in descending order, and if two words have the same frequency, they should be sorted lexico... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2231,
"level": 1,
"question": "# Task\nYou are given a list of strings `words` and an integer `k`. Your task is to find and return the `k` most frequent words from the list. The output words should be sorted by their frequency in descending order, and if two words have the same freq... |
from collections import Counter
def find_duplicates(nums):
counts = Counter(nums)
return [num for num, count in counts.items() if count == 2] | simplelr_Filter | [
{
"content": "Question:\nGiven a non-empty list of integers, write a Python function that returns a new list containing the elements that appear twice in the original list. The function should handle duplicate entries and empty lists.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2232,
"level": 1,
"question": "Given a non-empty list of integers, write a Python function that returns a new list containing the elements that appear twice in the original list. The function should handle duplicate entries and empty lists.",
"split": "train"
} |
import numpy as np
def generate_and_sum_diagonal():
matrix = np.random.randint(1, 101, (10, 10))
diagonal_sum = np.trace(matrix)
return matrix, diagonal_sum | simplelr_Package | [
{
"content": "Question:\nWrite a function that generates a 10x10 matrix with random integers between 1 and 100. Then, calculate the sum of all the elements in the main diagonal (top-left to bottom-right). Use numpy for creating the matrix and computing the sum. Return the generated matrix and the sum of the mai... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2233,
"level": 1,
"question": "Write a function that generates a 10x10 matrix with random integers between 1 and 100. Then, calculate the sum of all the elements in the main diagonal (top-left to bottom-right). Use numpy for creating the matrix and computing the sum. Return the gene... |
from collections import deque
def minSteps(grid):
n = len(grid)
if n == 0:
return -1
visited = [[False for _ in range(n)] for _ in range(n)]
queue = deque()
queue.append((0, 0, 0))
visited[0][0] = True
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while queue:
i, ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an `n x n` grid containing integers, where each cell represents the maximum number of steps you can move from that cell in the four directions (up, down, left, right) to another cell, determine the minimum number of steps required to move from the top-left cell to the bottom-right... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2234,
"level": 1,
"question": "Given an `n x n` grid containing integers, where each cell represents the maximum number of steps you can move from that cell in the four directions (up, down, left, right) to another cell, determine the minimum number of steps required to move from th... |
import pandas as pd
def process_csv(input_file, output_file):
try:
# Read the input CSV file
df = pd.read_csv(input_file)
# Check if the 'Price' column exists
if 'Price' in df.columns:
# Double the values in the 'Price' column
df['Price'] = df['Price... | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python script that processes a CSV file? I need to read a CSV file, modify some data, and then write it back to a new CSV file. Specifically, I want to read the file `input.csv`, double the values in the 'Price' column, and save the result to `output.csv`.\nAnswer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2235,
"level": 1,
"question": "Can you help me with a Python script that processes a CSV file? I need to read a CSV file, modify some data, and then write it back to a new CSV file. Specifically, I want to read the file `input.csv`, double the values in the 'Price' column, and save ... |
def findAnagrams(s, p):
len_p = len(p)
len_s = len(s)
result = []
if len_p > len_s:
return result
# Initialize frequency counts
p_count = [0] * 26
s_count = [0] * 26
for i in range(len_p):
p_count[ord(p[i]) - ord('a')] += 1
s_count[ord(s[i]) - ord('... | simplelr_Taco | [
{
"content": "Question:\nGiven a string s, your goal is to find the starting and ending positions of every substring in s that is an anagram of a given string p. Return these positions as a list of tuples representing the (start, end) index of each anagram.\n\nAn anagram is a word formed by rearranging the lett... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2236,
"level": 1,
"question": "Given a string s, your goal is to find the starting and ending positions of every substring in s that is an anagram of a given string p. Return these positions as a list of tuples representing the (start, end) index of each anagram.\n\nAn anagram is a ... |
import random
def roll_dice():
"""Simulates rolling two six-sided dice and returns their sum."""
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return die1 + die2 | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to simulate the rolling of a pair of six-sided dice and return the sum of the two dice. The function should take no parameters and should use the `random` module to simulate the dice roll. Use an appropriate docstring to describe what the function does.\nAnswer:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2237,
"level": 1,
"question": "Write a Python function to simulate the rolling of a pair of six-sided dice and return the sum of the two dice. The function should take no parameters and should use the `random` module to simulate the dice roll. Use an appropriate docstring to describ... |
def is_palindrome(s: str) -> bool:
# Extract only alphanumeric characters and convert to lowercase
filtered = [c.lower() for c in s if c.isalnum()]
# Join into a string
filtered_str = ''.join(filtered)
# Check if the string is equal to its reverse
return filtered_str == filtered_str[::-1]
# Exa... | simplelr_Filter | [
{
"content": "Question:\nYou have been tasked with determining whether a given string is a valid palindrome or not. A palindrome is a word, phrase, number, or other sequences of characters which reads the same backward as forward. Here are the rules:\n1. Only alphanumeric characters are considered, i.e., alphab... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2238,
"level": 1,
"question": "You have been tasked with determining whether a given string is a valid palindrome or not. A palindrome is a word, phrase, number, or other sequences of characters which reads the same backward as forward. Here are the rules:\n1. Only alphanumeric char... |
def sieve_of_eratosthenes(n: int) -> list:
"""
Generate all primes less than n using the Sieve of Eratosthenes algorithm.
Parameters:
n (int): The upper limit (non-inclusive) for prime generation
Returns:
list: List of prime numbers less than n
Examples:
>>> sieve_of_eratosthe... | simplelr_Algorithm | [
{
"content": "Question:\n### Task\n\nImplement a function that generates all the prime numbers less than a given integer `n` using the Sieve of Eratosthenes algorithm.\n\n### Requirements\nWrite a function `sieve_of_eratosthenes` that takes a single integer input `n` and returns a list of all prime numbers less... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2239,
"level": 1,
"question": "### Task\n\nImplement a function that generates all the prime numbers less than a given integer `n` using the Sieve of Eratosthenes algorithm.\n\n### Requirements\nWrite a function `sieve_of_eratosthenes` that takes a single integer input `n` and retur... |
def no_vowels(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
return [''.join([c for c in word if c.lower() not in vowels]) for word in s.split()] | simplelr_Filter | [
{
"content": "Question:\nYou've been tasked with creating a function that will convert a string into a list of words, and remove all vowels from the words. \n\nThe function will be called `no_vowels` and it will take a string as an argument. \n\nCan you create a function that fulfills this task?\nAnswer:\nLet's... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2240,
"level": 1,
"question": "You've been tasked with creating a function that will convert a string into a list of words, and remove all vowels from the words. \n\nThe function will be called `no_vowels` and it will take a string as an argument. \n\nCan you create a function that ... |
def move_zeroes(arr):
pos = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[pos], arr[i] = arr[i], arr[pos]
pos += 1
return arr
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, write a function to move all zeroes to the end of the list while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the list.\n\n```python\nmove_zeroes([0, 1, 0, 3, 12]) ==> [1, 3, 12, 0, 0]\n\nmove_zeroe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2241,
"level": 1,
"question": "Given a list of integers, write a function to move all zeroes to the end of the list while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the list.\n\n```python\nmove_zeroes([0, 1, 0, 3, 12])... |
def partition_labels(s):
last_occurrence = {}
for idx, char in enumerate(s):
last_occurrence[char] = idx # overwriting the index to keep the last occurrence
result = []
start = 0
current_end = 0
for i in range(len(s)):
current_end = max(current_end, last_occurrence[s[i]])
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` containing only lowercase letters. You need to partition `s` into one or more substrings such that each letter appears in at most one substring. Return _a list of integers representing the lengths of these substrings._ The partition should be done in a way tha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2242,
"level": 1,
"question": "You are given a string `s` containing only lowercase letters. You need to partition `s` into one or more substrings such that each letter appears in at most one substring. Return _a list of integers representing the lengths of these substrings._ The pa... |
def reverse_words(s):
words = s.split()
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to reverse the words in a string. The function should maintain the order of words but reverse each word individually. For example, if the input string is \"Hello World\", the output should be \"olleH dlroW\". Ensure to use list comprehensions for the solution.\nA... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2243,
"level": 1,
"question": "Write a Python function to reverse the words in a string. The function should maintain the order of words but reverse each word individually. For example, if the input string is \"Hello World\", the output should be \"olleH dlroW\". Ensure to use list ... |
def compute_binomial_coefficient(n: int, k: int) -> int:
if k == 0 or k == n:
return 1
if k > n - k:
k = n - k
return compute_binomial_coefficient(n, k - 1) * (n - k + 1) // k | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Compute Binomial Coefficient\n\nYou are given two non-negative integers n and k. Your task is to compute the binomial coefficient C(n, k), which denotes the number of ways to choose k elements from a set of n elements. You should implement the function using a recursive me... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2244,
"level": 1,
"question": "### Question: Compute Binomial Coefficient\n\nYou are given two non-negative integers n and k. Your task is to compute the binomial coefficient C(n, k), which denotes the number of ways to choose k elements from a set of n elements. You should implemen... |
import math
def list_operation(lst, operation):
operations = {
'sum': sum,
'product': math.prod,
'maximum': max,
'minimum': min
}
if operation not in operations:
raise ValueError("Invalid operation")
return operations[operation](lst) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python function that takes a list of integers and an operation as input. The function should perform the specified operation on all elements of the list and return the result. The operations include: sum, product, maximum, minimum.\nAnswer:\nLet's think step by step.\n",
"r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2245,
"level": 1,
"question": "Create a Python function that takes a list of integers and an operation as input. The function should perform the specified operation on all elements of the list and return the result. The operations include: sum, product, maximum, minimum.",
"split"... |
def balance_parentheses(s):
left_needed = 0
right_needed = 0
balance = 0
for c in s:
if c == '(':
balance += 1
else:
balance -= 1
if balance < 0:
left_needed += 1
balance = 0 # Reset balance as we've added a '('
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert a string of parentheses into a balanced string by adding the minimum number of parentheses. The goal is to make sure that every opening parenthesis has a corresponding closing parenthesis and vice versa.\nAnswer:\nLet's think step by step.\n",
"rol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2246,
"level": 1,
"question": "Write a python function to convert a string of parentheses into a balanced string by adding the minimum number of parentheses. The goal is to make sure that every opening parenthesis has a corresponding closing parenthesis and vice versa.",
"split": ... |
def is_palindrome(text):
"""
Checks if a given string is a palindrome, ignoring spaces, punctuation, and capitalization.
Args:
text: The string to check.
Returns:
True if the string is a palindrome, False otherwise.
"""
processed = ''.join([c for c in text.lower() if c.... | simplelr_Filter | [
{
"content": "Question:\nThe problem is:\n\nA palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward, ignoring spaces, punctuation, and capitalization.\n\nGiven a string, write a function that checks if it is a palindrome.\n\nHere's what I have so far:\n\n`... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2247,
"level": 1,
"question": "The problem is:\n\nA palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward, ignoring spaces, punctuation, and capitalization.\n\nGiven a string, write a function that checks if it is a palindrome.... |
def is_palindrome(S: str) -> bool:
# Process the string by converting to lowercase and keeping only alphanumeric characters
processed = [c.lower() for c in S if c.isalnum()]
processed_str = ''.join(processed)
# Check if the processed string is a palindrome
return processed_str == processed_str[::-1] | simplelr_Code_Contests | [
{
"content": "Question:\nA palindrome is a word, number, phrase, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, \"A man, a plan, a canal, Panama!\" is considered a palindrome, despite its spaces, punctuation, and capital ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2248,
"level": 1,
"question": "A palindrome is a word, number, phrase, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, \"A man, a plan, a canal, Panama!\" is considered a palindrome, despite it... |
def are_brackets_balanced(s):
stack = []
bracket_map = {')': '(', '}': '{', ']': '[', '>': '<'}
for char in s:
if char in bracket_map.values():
stack.append(char)
elif char in bracket_map:
if not stack:
return False
top = stack.pop()
... | simplelr_Filter | [
{
"content": "Question:\nWrite a function to check if the parentheses, curly brackets, and square brackets in a given expression are balanced or not. Additionally, the function should also check if the angle brackets (<>) in the expression are balanced or not. The function should return True if all types of bra... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2249,
"level": 1,
"question": "Write a function to check if the parentheses, curly brackets, and square brackets in a given expression are balanced or not. Additionally, the function should also check if the angle brackets (<>) in the expression are balanced or not. The function sho... |
def find_min_length_word(s, words):
unique_words = set(words)
# Sort the words by their length, so we check shorter words first
for word in sorted(unique_words, key=lambda x: (len(x), x)):
if word in s:
return len(word)
return 0 | simplelr_Filter | [
{
"content": "Question:\nYou are given a string `s` and a list of strings `words`. Find the length of the shortest word that is not in the dictionary or is a substring of one of the words in the list.\n\nExample 1:\n\n Input: `s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]`\n Output: `0` (because \"foo\"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2250,
"level": 1,
"question": "You are given a string `s` and a list of strings `words`. Find the length of the shortest word that is not in the dictionary or is a substring of one of the words in the list.\n\nExample 1:\n\n Input: `s = \"barfoothefoobarman\", words = [\"foo\",\"bar... |
def longest_palindrome(s):
n = len(s)
if n == 0:
return ""
dp = [[False] * n for _ in range(n)]
longest = s[0] # Initializing with the first character
# Mark all substrings of length 1 as palindromes
for i in range(n):
dp[i][i] = True
# Check for substrings of length 2
... | simplelr_Filter | [
{
"content": "Question:\nThe problem statement is as follows:\n\n**Problem Statement:**\n\nYou are given a string consisting of lowercase English letters. Your task is to find the longest palindromic substring within this string.\n\n**Example:**\n\n* **Input:** \"bananas\"\n* **Output:** \"anana\"\n\n\nHere's a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2251,
"level": 1,
"question": "The problem statement is as follows:\n\n**Problem Statement:**\n\nYou are given a string consisting of lowercase English letters. Your task is to find the longest palindromic substring within this string.\n\n**Example:**\n\n* **Input:** \"bananas\"\n* ... |
def proc_special_string(special_string: str) -> tuple:
letters = []
digits = []
for c in special_string:
if c.isalpha():
letters.append(c)
else:
digits.append(int(c))
reversed_letters = ''.join(reversed(letters))
sum_digits = sum(digits)
return (reversed_l... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function named `proc_special_string` that processes a special string according to specific rules. A \"special string\" consists of alphabetical characters and digits, where characters are always in lower case, and digits can be from 0 to 9. The function shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2252,
"level": 1,
"question": "You are required to write a function named `proc_special_string` that processes a special string according to specific rules. A \"special string\" consists of alphabetical characters and digits, where characters are always in lower case, and digits can... |
def analyze_list(int_list):
if not int_list:
return None
total = sum(int_list)
average = total / len(int_list)
minimum = min(int_list)
maximum = max(int_list)
return {
'sum': total,
'avg': average,
'min': minimum,
'max': maximum
} | simplelr_Package | [
{
"content": "Question:\nThis function takes a list of integers and returns a dictionary with the following keys:\n - 'sum': the sum of all integers\n - 'avg': the average of all integers\n - 'min': the minimum integer\n - 'max': the maximum integer\nMake sure to handle the case where the list is em... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2253,
"level": 1,
"question": "This function takes a list of integers and returns a dictionary with the following keys:\n - 'sum': the sum of all integers\n - 'avg': the average of all integers\n - 'min': the minimum integer\n - 'max': the maximum integer\nMake sure to h... |
def student_performance(names, scores):
if len(names) == 0:
return ('', [], [], [])
# Find the student with the highest score
max_score = max(scores)
index = scores.index(max_score)
highest_scorer = names[index]
# Sort the names and scores in descending order of scores
pair... | simplelr_Docs | [
{
"content": "Question:\n### Question: List Manipulations and String Formatting\n\n#### Problem Statement\n\nYou are given a list of strings representing names of students along with their scores stored in a separate list. You have to perform multiple tasks using Python. Complete the following function as per t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2254,
"level": 1,
"question": "### Question: List Manipulations and String Formatting\n\n#### Problem Statement\n\nYou are given a list of strings representing names of students along with their scores stored in a separate list. You have to perform multiple tasks using Python. Compl... |
def remove_whitespace(s):
return s.strip() | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove leading and trailing whitespaces from a string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2255,
"level": 1,
"question": "Write a python function to remove leading and trailing whitespaces from a string.",
"split": "train"
} |
def reorder_even_first(nums):
evens = []
odds = []
for num in nums:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens + odds | simplelr_Code_Contests | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns the list reordered such that all the even numbers come before all the odd numbers, preserving the original relative order of the even and odd numbers.\n\nExample\n\nInput\n\n[3, 1, 2, 4, 5]\n\nOutput\n\n[2, 4, 3, 1, 5]\n\nInput... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2256,
"level": 1,
"question": "Create a function that takes a list of integers and returns the list reordered such that all the even numbers come before all the odd numbers, preserving the original relative order of the even and odd numbers.\n\nExample\n\nInput\n\n[3, 1, 2, 4, 5]\n\... |
def actual_games(n, restricted):
unique_restricted = set()
for a, b in restricted:
if a > b:
a, b = b, a
unique_restricted.add((a, b))
total = n * (n - 1) // 2
return total - len(unique_restricted)
| simplelr_Taco | [
{
"content": "Question:\nThe local chess club holds a yearly round-robin tournament where each participant plays one game with every other participant. However, due to certain scheduling constraints, there are specific pairings that cannot be scheduled. Given a list of these restricted pairings, determine how m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2257,
"level": 1,
"question": "The local chess club holds a yearly round-robin tournament where each participant plays one game with every other participant. However, due to certain scheduling constraints, there are specific pairings that cannot be scheduled. Given a list of these r... |
def max_area(heights):
left = 0
right = len(heights) - 1
max_area = 0
while left < right:
width = right - left
height = min(heights[left], heights[right])
current_area = width * height
if current_area > max_area:
max_area = current_area
if heights[left... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `heights` representing the heights of buildings, return the maximum area of a rectangle formed by two buildings and the water line. You must place the water line horizontally between two buildings, such that the rectangle's width is the horizontal distance bet... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2258,
"level": 1,
"question": "Given an array of integers `heights` representing the heights of buildings, return the maximum area of a rectangle formed by two buildings and the water line. You must place the water line horizontally between two buildings, such that the rectangle's w... |
def find_max_and_min(lst):
if not lst:
return (None, None)
max_val = min_val = lst[0]
for num in lst[1:]:
if num > max_val:
max_val = num
if num < min_val:
min_val = num
return (max_val, min_val) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum and minimum values of a list using the for loop.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2259,
"level": 1,
"question": "Write a python function to find the maximum and minimum values of a list using the for loop.",
"split": "train"
} |
def find_even_pairs(vectors):
return [(a, b) for a in vectors[0] for b in vectors[1] if a % 2 == 0 or b % 2 == 0] | simplelr_Filter | [
{
"content": "Question:\nI am given a vector of vectors of integers. The task is to find all distinct pairs of elements, where the first element of the pair is from the first vector, and the second element is from the second vector, such that their product is even.\n\nHere is an example:\n\nInput: [[1, 3, 5], [... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2260,
"level": 1,
"question": "I am given a vector of vectors of integers. The task is to find all distinct pairs of elements, where the first element of the pair is from the first vector, and the second element is from the second vector, such that their product is even.\n\nHere is ... |
def generate_string(length, char):
return char * length | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that generates a string of a specified length filled with a specified character.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2261,
"level": 1,
"question": "Create a function that generates a string of a specified length filled with a specified character.",
"split": "train"
} |
def move_zeros_inplace(array: list) -> None:
write_pointer = 0
for read_pointer in range(len(array)):
current = array[read_pointer]
if not (type(current) is int and current == 0):
array[write_pointer] = current
write_pointer += 1
for i in range(write_pointer, len(arra... | simplelr_Data_Structure | [
{
"content": "Question:\n**Context**: You're working on a comment filtering system that removes spam while preserving important comments. An important task in this system involves moving flagged spam comments (represented by zero) to the end of the list, while preserving the order of other comments. The order o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2262,
"level": 1,
"question": "**Context**: You're working on a comment filtering system that removes spam while preserving important comments. An important task in this system involves moving flagged spam comments (represented by zero) to the end of the list, while preserving the o... |
def reverse_string(s):
stripped_s = s.strip()
return stripped_s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string input and returns the string in reverse order. For instance, if the input is \"Hello, World!\", the function should return \"!dlroW ,olleH\". Additionally, ensure that the function ignores any leading or trailing whitespace And handles special chara... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2263,
"level": 1,
"question": "Create a function that takes a string input and returns the string in reverse order. For instance, if the input is \"Hello, World!\", the function should return \"!dlroW ,olleH\". Additionally, ensure that the function ignores any leading or trailing w... |
def unique_paths_with_obstacles(grid):
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
# Check if start or end is blocked
if grid[0][0] == 1 or grid[m-1][n-1] == 1:
return 0
# Initialize DP table
dp = [[0 for _ in range(n)] for _ in range(m)]
dp[0][0] = 1 # ... | simplelr_Apps | [
{
"content": "Question:\nA new question that matches the style, length, difficulty level, and topic alignment of the given sample question is as follows:\n\nA robot is located at the top-left corner of a m x n grid (marked 'Start' in the grid below). The robot can only move either down or right at any point in ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2264,
"level": 1,
"question": "A new question that matches the style, length, difficulty level, and topic alignment of the given sample question is as follows:\n\nA robot is located at the top-left corner of a m x n grid (marked 'Start' in the grid below). The robot can only move ei... |
from typing import List
def pigeonhole_sort(arr: List[int]) -> List[int]:
if not arr:
return []
if len(arr) == 1:
return arr
min_val = min(arr)
max_val = max(arr)
# Create the pigeonholes
pigeonholes = [0] * (max_val - min_val + 1)
# Fill the pigeonholes
f... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a collection of integer elements in an array. Your task is to implement the Pigeonhole Sort to sort this array in ascending order.\n\n### Function Signature\n```python\ndef pigeonhole_sort(arr: List[int]) -> List[int]:\n pass\n```\n\n### Input\n- `arr`: A list of intege... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2265,
"level": 1,
"question": "You are given a collection of integer elements in an array. Your task is to implement the Pigeonhole Sort to sort this array in ascending order.\n\n### Function Signature\n```python\ndef pigeonhole_sort(arr: List[int]) -> List[int]:\n pass\n```\n\n#... |
def list_intersection(list1: list[int], list2: list[int]) -> list[int]:
set1 = set(list1)
set2 = set(list2)
common = set1 & set2
return sorted(common) | simplelr_Algorithm | [
{
"content": "Question:\n### List Intersection\n\nYou are part of a team working on a system that processes large datasets. One of your tasks is to find the common elements (intersection) between two lists of integers. The lists might not be sorted, and the approach should efficiently handle large inputs.\n\nIm... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2266,
"level": 1,
"question": "### List Intersection\n\nYou are part of a team working on a system that processes large datasets. One of your tasks is to find the common elements (intersection) between two lists of integers. The lists might not be sorted, and the approach should eff... |
def longest_unique_substring(s):
left = 0
max_len = 0
start = 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 - le... | simplelr_Apps | [
{
"content": "Question:\nDesign a function `longest_unique_substring(s)` that takes a string `s` and returns the longest substring without repeating characters. The function should return the substring itself and not its length.\n\nExamples:\n```python\nlongest_unique_substring(\"abcabcbb\") == \"abc\"\nlongest... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2267,
"level": 1,
"question": "Design a function `longest_unique_substring(s)` that takes a string `s` and returns the longest substring without repeating characters. The function should return the substring itself and not its length.\n\nExamples:\n```python\nlongest_unique_substrin... |
import math
def simplify_fractions(fractions):
result = []
for a, b in fractions:
if b == 0:
result.append("Undefined")
else:
if a == 0:
result.append((0, 1))
else:
g = math.gcd(abs(a), abs(b))
simplified_a = a ... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with designing a function `simplify_fractions(fractions)` which takes a single argument:\n- `fractions`: a list of tuples, where each tuple contains two integers representing the numerator and denominator of a fraction.\n\nYour function should:\n1. Simplify each fraction ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2268,
"level": 1,
"question": "You are tasked with designing a function `simplify_fractions(fractions)` which takes a single argument:\n- `fractions`: a list of tuples, where each tuple contains two integers representing the numerator and denominator of a fraction.\n\nYour function ... |
def sum_2d_array(arr):
return sum(sum(row) for row in arr) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the sum of all elements in a given 2D array. The array is represented as a list of lists in Python. Each inner list represents a row in the 2D array. The function should handle an array of any size.\nAnswer:\nLet's think step by step.\n",
"role": "u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2269,
"level": 1,
"question": "Create a function that calculates the sum of all elements in a given 2D array. The array is represented as a list of lists in Python. Each inner list represents a row in the 2D array. The function should handle an array of any size.",
"split": "train... |
def binary_search(arr, target, find_first):
"""
Searches for the target in a sorted array using binary search.
If find_first is True, returns the index of the first occurrence.
If find_first is False, returns the index of the last occurrence.
Returns -1 if the target is not found.
Args:
... | simplelr_Filter | [
{
"content": "Question:\nDevise a code structure that carries out a binary search within a sorted, one-dimensional array of integers. Additionally, the function should include functionality to find either the first or last occurrence of a duplicate number if the array contains duplicates, based on an input flag... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2270,
"level": 1,
"question": "Devise a code structure that carries out a binary search within a sorted, one-dimensional array of integers. Additionally, the function should include functionality to find either the first or last occurrence of a duplicate number if the array contains... |
from typing import List
def remove_duplicates_preserve_order(elements: List[int]) -> List[int]:
seen = set()
result = []
for element in elements:
if element not in seen:
seen.add(element)
result.append(element)
return result | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\nYou are tasked with writing a function `remove_duplicates_preserve_order(elements: List[int]) -> List[int]` that takes a list of integers and returns a new list with duplicate elements removed while preserving the order of their first occurrence.\n\n#### Input\n- A list ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2271,
"level": 1,
"question": "### Question\n\nYou are tasked with writing a function `remove_duplicates_preserve_order(elements: List[int]) -> List[int]` that takes a list of integers and returns a new list with duplicate elements removed while preserving the order of their first o... |
def reverse_words(s):
words = s.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a string containing a sentence and reverses the order of the words. Each word in the sentence is separated by a single space and there are no leading or trailing spaces. Ensure that the punctuation and capitalization in the words are retained in their origina... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2272,
"level": 1,
"question": "Write a function that takes a string containing a sentence and reverses the order of the words. Each word in the sentence is separated by a single space and there are no leading or trailing spaces. Ensure that the punctuation and capitalization in the ... |
def remove_adjacent_duplicates(s):
stack = []
for char in s:
if stack and stack[-1] == char:
stack.pop()
else:
stack.append(char)
return ''.join(stack) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` consisting of lowercase English letters. A **duplicate removal operation** will be performed on `s` until no adjacent duplicate letters remain. During each duplicate removal operation, any pair of adjacent letters that are the same will be removed. The process... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2273,
"level": 1,
"question": "You are given a string `s` consisting of lowercase English letters. A **duplicate removal operation** will be performed on `s` until no adjacent duplicate letters remain. During each duplicate removal operation, any pair of adjacent letters that are th... |
def max_activities(activities):
if not activities:
return 0
# Sort activities by their end times
activities.sort(key=lambda x: x[1])
count = 0
last_end = 0
for start, end in activities:
if start >= last_end:
count += 1
last_end = end
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of activities with their start and end times. Your task is to select the maximum number of activities that a single person can attend, assuming they can only participate in one activity at a time. The activities are given as a list of tuples, where each tuple contai... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2274,
"level": 1,
"question": "You are given a list of activities with their start and end times. Your task is to select the maximum number of activities that a single person can attend, assuming they can only participate in one activity at a time. The activities are given as a list... |
def string_frequencies(strings):
counts = {}
for s in strings:
counts[s] = counts.get(s, 0) + 1
return list(counts.items()) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of strings as input and returns a list of tuples. Each tuple should contain the original string from the input list and its corresponding frequency of occurrence in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2275,
"level": 1,
"question": "Write a Python function that takes a list of strings as input and returns a list of tuples. Each tuple should contain the original string from the input list and its corresponding frequency of occurrence in the list.",
"split": "train"
} |
def is_subsequence(s1, s2):
i = j = 0
n, m = len(s1), len(s2)
while i < n and j < m:
if s1[i] == s2[j]:
i += 1
j += 1
return i == n | simplelr_Filter | [
{
"content": "Question:\nCreate a function which receives two strings and checks if the characters in the first string appear in the same order as in the second string. The function should have a time complexity of O(n+m), where n and m are the lengths of the two strings respectively.\nAnswer:\nLet's think step... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2276,
"level": 1,
"question": "Create a function which receives two strings and checks if the characters in the first string appear in the same order as in the second string. The function should have a time complexity of O(n+m), where n and m are the lengths of the two strings respe... |
import re
def is_valid_float_number(s):
pattern = r'^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$'
return bool(re.fullmatch(pattern, s))
# Example usage:
if __name__ == "__main__":
test_cases = [
"123.456", # Valid
"1.5E2", # Valid
"123.456.789",# Invalid
"abc", # ... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python program that not only verifies if a given string can be a valid floating-point number but also checks the precision of the floating-point number and validates the input based on scientific notation. For instance, the program should be able to correctly identify whether th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2277,
"level": 1,
"question": "Write a Python program that not only verifies if a given string can be a valid floating-point number but also checks the precision of the floating-point number and validates the input based on scientific notation. For instance, the program should be ab... |
from pathlib import Path
from typing import List, Tuple
def find_largest_files(directory: str, ignore_exts: List[str], n: int) -> List[Tuple[Path, int]]:
directory_path = Path(directory)
if not directory_path.exists() or not directory_path.is_dir():
return []
files = []
for file ... | simplelr_Docs | [
{
"content": "Question:\n### Question\n\nYou are given a directory structure and a requirement to find the top `n` largest files within it, but you need to ignore certain file types based on their extensions. Using the `pathlib` module, write a Python function that performs the following tasks:\n\n1. Accepts a ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2278,
"level": 1,
"question": "### Question\n\nYou are given a directory structure and a requirement to find the top `n` largest files within it, but you need to ignore certain file types based on their extensions. Using the `pathlib` module, write a Python function that performs th... |
from datetime import datetime
from typing import List, Tuple
def calculate_overdue_books(current_date: datetime, borrowed_books: List[Tuple[str, datetime, datetime]]) -> Tuple[List[str], float]:
"""
Calculates the list of overdue books and the total penalty.
Args:
current_date (datetime): The curr... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario:\nYou are building a library system that keeps track of books that users borrow and return. The library management software needs a feature to generate a list of books that are overdue based on the current date and provide the total penalt... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2279,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario:\nYou are building a library system that keeps track of books that users borrow and return. The library management software needs a feature to generate a list of books that are overdue based on the curren... |
def sum_of_two_numbers(num1, num2):
return num1 + num2 | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to calculate the sum of two numbers. The function should take two parameters and return their sum.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2280,
"level": 1,
"question": "Write a Python function to calculate the sum of two numbers. The function should take two parameters and return their sum.",
"split": "train"
} |
def custom_sort_string(order: str, s: str) -> str:
order_map = {char: idx for idx, char in enumerate(order)}
group_a = [c for c in s if c in order_map]
group_b = [c for c in s if c not in order_map]
group_a_sorted = sorted(group_a, key=lambda x: order_map[x])
return ''.join(group_a_sorted + group_b) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings, `order` and `str`. All the characters of `order` are unique, and `order` was sorted in some custom order previously. Convert the string `str` to match the custom order defined in `order`. More precisely, the characters of `str` should be sorted such that if `a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2281,
"level": 1,
"question": "You are given two strings, `order` and `str`. All the characters of `order` are unique, and `order` was sorted in some custom order previously. Convert the string `str` to match the custom order defined in `order`. More precisely, the characters of `st... |
def calculate_bill(items):
return sum(price * quantity for name, price, quantity in items)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function called `calculateBill`/`calculate_bill` that takes a list of tuples as input, where each tuple contains the name of an item, the price per unit, and the quantity of that item purchased. The function should return the total bill amount.\n\nFor example, given the input:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2282,
"level": 1,
"question": "Write a function called `calculateBill`/`calculate_bill` that takes a list of tuples as input, where each tuple contains the name of an item, the price per unit, and the quantity of that item purchased. The function should return the total bill amount.... |
def length_of_longest_substring(s):
char_index = {}
max_length = 0
left = 0
for right in range(len(s)):
current_char = s[right]
if current_char in char_index and char_index[current_char] >= left:
left = char_index[current_char] + 1
char_index[current_char] = right
... | simplelr_Filter | [
{
"content": "Question:\nA user is given a string containing only lowercase English letters and they are tasked with finding the length of the longest substring without repeating characters.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2283,
"level": 1,
"question": "A user is given a string containing only lowercase English letters and they are tasked with finding the length of the longest substring without repeating characters.",
"split": "train"
} |
def remove_consecutive_duplicates(s):
result = []
for char in s:
if not result or char != result[-1]:
result.append(char)
return ''.join(result) | simplelr_Filter | [
{
"content": "Question:\nIn Python, how can I remove consecutive duplicate characters from a string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2284,
"level": 1,
"question": "In Python, how can I remove consecutive duplicate characters from a string?",
"split": "train"
} |
def next_bigger(num: int) -> int:
digits = list(map(int, str(num)))
n = len(digits)
# Step 1: Find the pivot
pivot = -1
for i in range(n - 2, -1, -1):
if digits[i] < digits[i + 1]:
pivot = i
break
if pivot == -1:
return -1 # No next permutation possi... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with finding the next higher number that has the same set of digits as a given number. If no such number exists, return -1. This problem tests your understanding of permutations and the ability to manipulate arrays efficiently.\n\n### Function Signature\n```python\ndef ne... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2285,
"level": 1,
"question": "You are tasked with finding the next higher number that has the same set of digits as a given number. If no such number exists, return -1. This problem tests your understanding of permutations and the ability to manipulate arrays efficiently.\n\n### Fu... |
def findUnique(nums):
seen = set()
for num in nums:
if num in seen:
seen.remove(num)
else:
seen.add(num)
return seen.pop() | simplelr_Codeforces | [
{
"content": "Question:\nYou are given an array of integers where each integer appears exactly twice, except for one integer which appears only once. Your task is to find the integer that appears only once.\n\nWrite a function `findUnique` that accepts a list of integers and returns the integer that appears exa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2286,
"level": 1,
"question": "You are given an array of integers where each integer appears exactly twice, except for one integer which appears only once. Your task is to find the integer that appears only once.\n\nWrite a function `findUnique` that accepts a list of integers and r... |
def transform_sets(set1: set, set2: set) -> frozenset:
# Step 1: Compute the union by adding all elements of set1 and set2 to a new set
union_set = set()
for item in set1:
union_set.add(item)
for item in set2:
union_set.add(item)
# Step 2: Filter out non-integer elements
fil... | simplelr_Docs | [
{
"content": "Question:\nImplement a Python function that takes in two sets and performs a series of operations to produce a final transformed set. You need to demonstrate your comprehension of fundamental set operations using the provided API. The function should work in the following way:\n\n1. **Union** the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2287,
"level": 1,
"question": "Implement a Python function that takes in two sets and performs a series of operations to produce a final transformed set. You need to demonstrate your comprehension of fundamental set operations using the provided API. The function should work in the ... |
def reverse_middle(lst):
if len(lst) <= 1:
return lst.copy() # or simply return lst[:] to ensure a copy is returned
middle = lst[1:-1]
reversed_middle = middle[::-1]
return [lst[0]] + reversed_middle + [lst[-1]] | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and returns a new list with the elements in reversed order, except for the first and last elements which should remain in their original positions. For example, given the list [10, 20, 30, 40, 50], the function should return [10, 40,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2288,
"level": 1,
"question": "Write a Python function that takes a list of integers and returns a new list with the elements in reversed order, except for the first and last elements which should remain in their original positions. For example, given the list [10, 20, 30, 40, 50], ... |
from collections import deque
def shortest_path(adj_list, start_node, target_node):
if start_node == target_node:
return [start_node]
if start_node not in adj_list or target_node not in adj_list:
return []
queue = deque([start_node])
visited = {start_node}
parent = {}
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Summary\nYou are given an undirected graph represented as an adjacency list. Your task is to write a function that determines the shortest path from a given start node to a target node using Breadth-First Search (BFS).\n\n### Function Definition\nWrite a function `shortest_p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2289,
"level": 1,
"question": "### Problem Summary\nYou are given an undirected graph represented as an adjacency list. Your task is to write a function that determines the shortest path from a given start node to a target node using Breadth-First Search (BFS).\n\n### Function Defin... |
def search_matrix(matrix, target):
if not matrix or not matrix[0]:
return False
n = len(matrix)
m = len(matrix[0])
row, col = 0, m - 1
while row < n and col >= 0:
if matrix[row][col] == target:
return True
elif target < matrix[row][col]:
col -= 1
... | simplelr_Filter | [
{
"content": "Question:\nI have a matrix of size `n x m` filled with integers, and I want to write a program to check if a given target integer exists in the matrix. The matrix has the following properties:\n- The integers in each row are sorted in ascending order.\n- The integers in each column are sorted in a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2290,
"level": 1,
"question": "I have a matrix of size `n x m` filled with integers, and I want to write a program to check if a given target integer exists in the matrix. The matrix has the following properties:\n- The integers in each row are sorted in ascending order.\n- The inte... |
def findFirstRow(grid):
for i, row in enumerate(grid):
if all(cell == 1 for cell in row):
return i
return -1 | simplelr_Filter | [
{
"content": "Question:\nI have a 2D grid where the width is the number of columns and the length is the number of rows, and each cell contains a 0 or a 1. My goal is to write a Python function that starts at the top left corner of a grid and finds the first row where every cell is a 1, and returns the row numb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2291,
"level": 1,
"question": "I have a 2D grid where the width is the number of columns and the length is the number of rows, and each cell contains a 0 or a 1. My goal is to write a Python function that starts at the top left corner of a grid and finds the first row where every ce... |
import torch
def xpu_matrix_multiplication(matrix_a: torch.Tensor, matrix_b: torch.Tensor, seed: int) -> torch.Tensor:
"""
Perform matrix multiplication using PyTorch XPU devices, optimizing memory usage and ensuring reproducibility.
:param matrix_a: A 2D tensor (matrix) to be multiplied.
:param matri... | simplelr_Docs | [
{
"content": "Question:\n### PyTorch XPU Device Management and Computation\n\n#### Objective:\nYou are required to write a function in PyTorch that utilizes the `torch.xpu` functionalities for device and stream management, as well as for managing random number generators for reproducibility. This function shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2292,
"level": 1,
"question": "### PyTorch XPU Device Management and Computation\n\n#### Objective:\nYou are required to write a function in PyTorch that utilizes the `torch.xpu` functionalities for device and stream management, as well as for managing random number generators for r... |
def reverse_words_in_place(s):
if not s:
return s
arr = list(s)
n = len(arr)
i = 0
while i < n:
if arr[i] != ' ':
start = i
# Find the end of the word
while i < n and arr[i] != ' ':
i += 1
end = i - 1
# Rever... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s`, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Consider the string to be a sequence of words separated by spaces. A word is defined as a contiguous sequence of non-space characters.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2293,
"level": 1,
"question": "Given a string `s`, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Consider the string to be a sequence of words separated by spaces. A word is defined as a contiguou... |
def delete_reoccurring_characters(string: str) -> str:
seen = set()
result = []
for char in string:
if char not in seen:
result.append(char)
seen.add(char)
return ''.join(result) | simplelr_Data_Structure | [
{
"content": "Question:\n### Task\nWrite a function named `delete_reoccurring_characters` that takes a string as input and returns a new string with all the reoccurring characters removed while retaining the order of first occurrences of each character.\n\n### Function Signature\n```python\ndef delete_reoccurri... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2294,
"level": 1,
"question": "### Task\nWrite a function named `delete_reoccurring_characters` that takes a string as input and returns a new string with all the reoccurring characters removed while retaining the order of first occurrences of each character.\n\n### Function Signatu... |
def maximum_product_of_three(nums):
nums.sort()
candidate1 = nums[-1] * nums[-2] * nums[-3]
candidate2 = nums[0] * nums[1] * nums[-1]
return max(candidate1, candidate2) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum product of three distinct numbers in a list. The list can contain both positive and negative numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2295,
"level": 1,
"question": "Write a python function to find the maximum product of three distinct numbers in a list. The list can contain both positive and negative numbers.",
"split": "train"
} |
from collections import Counter
def can_make_palindrome(s):
count = Counter(s)
odd_count = 0
for char in count:
if char != 'a' and count[char] % 2 != 0:
odd_count += 1
return odd_count <= 1
| simplelr_Taco | [
{
"content": "Question:\nGiven a string s, you are allowed to convert it to a new string by rearranging its letters and/or inserting any number of the character 'a' in any positions. Your task is to determine if it's possible to make the new string a palindrome.\n\nA palindrome is a string that reads the same f... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2296,
"level": 1,
"question": "Given a string s, you are allowed to convert it to a new string by rearranging its letters and/or inserting any number of the character 'a' in any positions. Your task is to determine if it's possible to make the new string a palindrome.\n\nA palindrom... |
def isValidSerialization(preorder: str) -> bool:
nodes = preorder.split(',')
if not nodes:
return False
if nodes[0] == '#':
return len(nodes) == 1
slots = 2
for i in range(1, len(nodes)):
if slots == 0:
return False
slots -= 1
if nodes[i] != '#':
... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that determines if a given string is a valid serialization of a binary tree. You are given a string consisting of integers and the character '#' separated by commas, where each integer represents a node's value, and '#' signifies a null pointer (a leaf node). A valid bi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2297,
"level": 1,
"question": "Write a function that determines if a given string is a valid serialization of a binary tree. You are given a string consisting of integers and the character '#' separated by commas, where each integer represents a node's value, and '#' signifies a nul... |
def sort_colors(nums: list[int]) -> None:
low = 0
high = len(nums) - 1
i = 0
while i <= high:
if nums[i] == 0:
nums[i], nums[low] = nums[low], nums[i]
low += 1
i += 1
elif nums[i] == 2:
nums[i], nums[high] = nums[high], nums[i]
... | simplelr_Algorithm | [
{
"content": "Question:\n### Sorting Colors in Linear Time\n\n#### Problem Statement:\nYou are given an array `nums` containing `n` objects colored red, white, or blue, represented by integers `0`, `1`, and `2` respectively. Your task is to sort the array in-place so that objects of the same color are adjacent ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2298,
"level": 1,
"question": "### Sorting Colors in Linear Time\n\n#### Problem Statement:\nYou are given an array `nums` containing `n` objects colored red, white, or blue, represented by integers `0`, `1`, and `2` respectively. Your task is to sort the array in-place so that obje... |
def count_passing_failing(grades):
passing_count = sum(1 for grade in grades if grade >= 60)
failing_count = sum(1 for grade in grades if grade < 60)
return (passing_count, failing_count)
grades = [88, 55, 76, 92, 45, 65, 71, 82, 49, 67]
print(count_passing_failing(grades)) | simplelr_Filter | [
{
"content": "Question:\nI have an array of integers, where each integer represents a grade (0-100). I want to write a function that will take this array and return the number of students who got a passing grade (60 or above) and the number of students who got a failing grade (below 60).\n\nHere is the code I h... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2299,
"level": 1,
"question": "I have an array of integers, where each integer represents a grade (0-100). I want to write a function that will take this array and return the number of students who got a passing grade (60 or above) and the number of students who got a failing grade ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.