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 count_alphabets_and_numbers(s):
alphabet_count = 0
number_count = 0
for char in s:
if char.isalpha():
alphabet_count += 1
elif char.isdigit():
number_count += 1
return {'alphabet_count': alphabet_count, 'number_count': number_count} | simplelr_Evol | [
{
"content": "Question:\nCreate a function in Python that takes a string as input and returns a dictionary with two keys: 'alphabet_count' and 'number_count'. The value of 'alphabet_count' should be the total number of alphabetic characters (both uppercase and lowercase) in the string, and the value of 'number_... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9500,
"level": 1,
"question": "Create a function in Python that takes a string as input and returns a dictionary with two keys: 'alphabet_count' and 'number_count'. The value of 'alphabet_count' should be the total number of alphabetic characters (both uppercase and lowercase) in th... |
from typing import List
def diagonal_traversal(matrix: List[List[int]]) -> List[List[int]]:
if not matrix:
return []
m = len(matrix)
n = len(matrix[0]) if m > 0 else 0
result = []
max_k = m + n - 2
for k in range(max_k + 1):
diag = []
for i in range(m):
j = k... | simplelr_Taco | [
{
"content": "Question:\n## Task\n\nConsider a **diagonal traversal** of a matrix starting from the top left corner. In diagonal traversal, we start with the first column and then move diagonally up-right to the end until the matrix is fully traversed. \n\nGiven a matrix of size `m x n`, an element at position ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9501,
"level": 1,
"question": "## Task\n\nConsider a **diagonal traversal** of a matrix starting from the top left corner. In diagonal traversal, we start with the first column and then move diagonally up-right to the end until the matrix is fully traversed. \n\nGiven a matrix of si... |
def extract_variables(filename):
variable_dict = {}
try:
with open(filename, 'r') as file:
for line in file:
line = line.strip()
if not line or '=' not in line:
continue
# Split the line at the first '='
var,... | simplelr_Filter | [
{
"content": "Question:\nGiven a file with the following content:\n```\nvariable1 = Hello\nvariable2 = World\n```\nHow would someone write the code to extract the variable names and their corresponding values using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9502,
"level": 1,
"question": "Given a file with the following content:\n```\nvariable1 = Hello\nvariable2 = World\n```\nHow would someone write the code to extract the variable names and their corresponding values using Python?",
"split": "train"
} |
def is_in_between(a, b, c):
return (a - b) * (a - c) <= 0 | simplelr_Filter | [
{
"content": "Question:\nFinish the code for a function that checks if a whole number is in-between two other numbers (inclusive). The function should also handle cases where the first number is larger than the second number and the input numbers are not in sorted order. Additionally, the function should only u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9503,
"level": 1,
"question": "Finish the code for a function that checks if a whole number is in-between two other numbers (inclusive). The function should also handle cases where the first number is larger than the second number and the input numbers are not in sorted order. Addit... |
def average(lst):
total = 0
count = 0
for x in lst:
if type(x) in (int, float):
total += x
count += 1
if count == 0:
return None
return total / count | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to calculate the average of a list of numbers. The function should be able to handle an empty list by returning `None`. Additionally, ensure the function can handle non-numeric types in the list by ignoring them and calculating the average of the remaining number... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9504,
"level": 1,
"question": "Write a Python function to calculate the average of a list of numbers. The function should be able to handle an empty list by returning `None`. Additionally, ensure the function can handle non-numeric types in the list by ignoring them and calculating ... |
def sum_between(a, b):
start = min(a, b)
end = max(a, b)
num_terms = end - start + 1
return num_terms * (start + end) // 2 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two integers as input and returns the sum of all integers between them, inclusive. For example, if the input numbers are 1 and 5, the function should return 15 because the sum of all integers from 1 to 5 is 15 (1+2+3+4+5=15).\nAnswer:\nLet's think step by st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9505,
"level": 1,
"question": "Create a function that takes two integers as input and returns the sum of all integers between them, inclusive. For example, if the input numbers are 1 and 5, the function should return 15 because the sum of all integers from 1 to 5 is 15 (1+2+3+4+5=15... |
def doses(X, Y):
return min(X // 2, Y // 3)
| simplelr_Taco | [
{
"content": "Question:\nGeek and Nerd are scientists working on a new chemical experiment. They have two chemicals A and B with initial quantities X and Y milliliters respectively. The goal is to determine how many doses of a special neutralizer can be made using A and B. The total volume of one dose of the ne... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9506,
"level": 1,
"question": "Geek and Nerd are scientists working on a new chemical experiment. They have two chemicals A and B with initial quantities X and Y milliliters respectively. The goal is to determine how many doses of a special neutralizer can be made using A and B. The... |
def sum_of_numbers(n):
"""
Calculate the sum of all numbers from 1 to n using the arithmetic series formula.
Args:
n (int): A positive integer.
Returns:
int: The sum of numbers from 1 to n.
"""
return n * (n + 1) // 2 | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum of all numbers between 1 and n, where n is a positive integer. This function should be efficient and should not use any loops or recursion. You can use mathematical formulas to achieve this.\nAnswer:\nLet's think step by step.\n",
"role": "user"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9507,
"level": 1,
"question": "Write a function to calculate the sum of all numbers between 1 and n, where n is a positive integer. This function should be efficient and should not use any loops or recursion. You can use mathematical formulas to achieve this.",
"split": "train"
} |
def sum_even_numbers(nums):
return sum(num for num in nums if num % 2 == 0) | simplelr_Filter | [
{
"content": "Question:\nThis is a coding challenge. I would like solutions in Python.\n\n**The Challenge:**\n\nYou are given an array of numbers. Return the sum of all even numbers in the array. \n\n**Input:**\n\nA list of integers\n\n**Output:**\n\nAn integer representing the sum of all even numbers in the in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9508,
"level": 1,
"question": "This is a coding challenge. I would like solutions in Python.\n\n**The Challenge:**\n\nYou are given an array of numbers. Return the sum of all even numbers in the array. \n\n**Input:**\n\nA list of integers\n\n**Output:**\n\nAn integer representing th... |
from collections import deque
from typing import List
def max_in_subarray(arr: List[int], k: int) -> List[int]:
n = len(arr)
if k > n:
return []
deq = deque()
result = []
for i in range(n):
# Remove indices outside the current window
while deq and deq[0] < i - k + 1:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\nYou are required to implement a function `max_in_subarray` that takes an integer array and a window size. The goal is to find the maximum element in every subarray of the given size that can be formed from the array. If the subarray size is larger than the array itself, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9509,
"level": 1,
"question": "### Question\n\nYou are required to implement a function `max_in_subarray` that takes an integer array and a window size. The goal is to find the maximum element in every subarray of the given size that can be formed from the array. If the subarray siz... |
def add_numbers(a, b):
"""Return the sum of two numbers."""
return a + b | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that adds two numbers and returns the result. The function should handle both integers and floating-point numbers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9510,
"level": 1,
"question": "Create a function that adds two numbers and returns the result. The function should handle both integers and floating-point numbers.",
"split": "train"
} |
def factorial(n):
if n < 0 or n > 10:
raise ValueError("Input must be between 0 and 10 inclusive.")
result = 1
for i in range(1, n + 1):
result *= i
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as its input and returns the factorial of that number. The function should be able to handle inputs in the range 0 to 10. Additionally, implement error handling to manage inputs outside of this range.\nAnswer:\nLet's think step by step.\n",
"r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9511,
"level": 1,
"question": "Create a function that takes an integer as its input and returns the factorial of that number. The function should be able to handle inputs in the range 0 to 10. Additionally, implement error handling to manage inputs outside of this range.",
"split"... |
def increment_large_integer(A):
carry = 1
for i in range(len(A) - 1, -1, -1):
total = A[i] + carry
if total > 9:
carry = 1
total = 0
else:
carry = 0
A[i] = total
if carry == 0:
break
if carry:
A.insert(0, 1)
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of digits `A` representing a large integer, increment the large integer by one and return the resulting array of digits. The digits in the input array are in non-decreasing order, and the input array can be of arbitrary length. Ensure that your solution handles the digit ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9512,
"level": 1,
"question": "Given an array of digits `A` representing a large integer, increment the large integer by one and return the resulting array of digits. The digits in the input array are in non-decreasing order, and the input array can be of arbitrary length. Ensure th... |
import sys
def remove_duplicate_lines(input_file, output_file):
if input_file == output_file:
# Read all lines first to avoid truncation issues
with open(input_file, 'r') as f:
lines = f.readlines()
seen = set()
unique_lines = []
for line in lines:
if... | simplelr_Filter | [
{
"content": "Question:\nHow can I write a Python program to remove duplicate lines from a text file?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9513,
"level": 1,
"question": "How can I write a Python program to remove duplicate lines from a text file?",
"split": "train"
} |
def compare_versions(version1, version2):
parts1 = list(map(int, version1.split('.')))
parts2 = list(map(int, version2.split('.')))
max_len = max(len(parts1), len(parts2))
for i in range(max_len):
p1 = parts1[i] if i < len(parts1) else 0
p2 = parts2[i] if i < len(parts2) else 0
... | simplelr_Taco | [
{
"content": "Question:\nGiven two strings version1 and version2, compare them to determine if one is a higher version number than the other. Version numbers are formatted as a string of numbers joined by dots like \"1.0.0\", \"1.0.1\", etc. Return 1 if version1 > version2, -1 if version1 < version2, or 0 if th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9514,
"level": 1,
"question": "Given two strings version1 and version2, compare them to determine if one is a higher version number than the other. Version numbers are formatted as a string of numbers joined by dots like \"1.0.0\", \"1.0.1\", etc. Return 1 if version1 > version2, -1... |
def is_magic_number(num):
return num != 0 and num % 9 == 1 | simplelr_Data_Structure | [
{
"content": "Question:\n#### Scenario\nYou are developing an application that involves validating user input based on specific numerical properties. One of the properties you need to verify is if a given number is a magic number. You need to implement a function following the rules provided.\n\n#### Task\nWrit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9515,
"level": 1,
"question": "#### Scenario\nYou are developing an application that involves validating user input based on specific numerical properties. One of the properties you need to verify is if a given number is a magic number. You need to implement a function following the... |
import re
def split_string(input_string, separator):
if not input_string:
return []
pattern = re.escape(separator) + '+'
parts = re.split(pattern, input_string)
result = []
for part in parts:
stripped = part.strip()
if stripped:
result.append(stripped)
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes in a string and a separator, then splits the string on the separator and returns a list of the resulting substrings. The function should ignore contiguous separators, treating them as a single separator, and it should also remove leading and trailing w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9516,
"level": 1,
"question": "Write a Python function that takes in a string and a separator, then splits the string on the separator and returns a list of the resulting substrings. The function should ignore contiguous separators, treating them as a single separator, and it should... |
def maxArea(heights):
max_area = 0
left = 0
right = len(heights) - 1
while left < right:
current_area = min(heights[left], heights[right]) * (right - left)
if current_area > max_area:
max_area = current_area
if heights[left] < heights[right]:
left += 1
... | simplelr_Taco | [
{
"content": "Question:\nYou are given an array of integers where each element represents a height. We want to calculate the maximum area of a rectangle formed by any two heights from the array, where the width of the rectangle is the distance between those two heights.\n\nExample 1:\nInput:\nheights = [1, 8, 6... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9517,
"level": 1,
"question": "You are given an array of integers where each element represents a height. We want to calculate the maximum area of a rectangle formed by any two heights from the array, where the width of the rectangle is the distance between those two heights.\n\nExa... |
def most_common_word(sentence: str) -> str:
words = sentence.split()
processed_words = []
for word in words:
clean_word = ''.join([c.lower() for c in word if c.isalpha()])
if clean_word:
processed_words.append(clean_word)
if not processed_words:
return ''
... | simplelr_Package | [
{
"content": "Question:\nIn this problem, you will work with Python's dictionary data structure to perform data manipulation based on word occurrences. The objective is to practice using Python dictionaries for counting frequencies and finding the most common elements, an essential skill for data analysis tasks... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9518,
"level": 1,
"question": "In this problem, you will work with Python's dictionary data structure to perform data manipulation based on word occurrences. The objective is to practice using Python dictionaries for counting frequencies and finding the most common elements, an esse... |
def findAnagramIndices(s, p):
len_p = len(p)
len_s = len(s)
result = []
if len_p > len_s:
return result
count_p = [0] * 26
count_s = [0] * 26
for i in range(len_p):
count_p[ord(p[i]) - ord('a')] += 1
count_s[ord(s[i]) - ord('a')] += 1
if count_p == ... | simplelr_Apps | [
{
"content": "Question:\nWrite a function `findAnagramIndices` that takes two strings `s` and `p` as arguments. The function should return a list of starting indices of the anagram substrings of `p` in `s`. An anagram substring contains the same characters as the original string `p`, but in any order. The order... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9519,
"level": 1,
"question": "Write a function `findAnagramIndices` that takes two strings `s` and `p` as arguments. The function should return a list of starting indices of the anagram substrings of `p` in `s`. An anagram substring contains the same characters as the original stri... |
def sum_of_even_numbers(numbers):
total = 0
for num in numbers:
if num % 2 == 0:
total += num
return total | simplelr_Filter | [
{
"content": "Question:\nIs it possible to use Qwen to generate a piece of Python code that solves the following problem: Given a list of integers, return the sum of all the even numbers in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9520,
"level": 1,
"question": "Is it possible to use Qwen to generate a piece of Python code that solves the following problem: Given a list of integers, return the sum of all the even numbers in the list.",
"split": "train"
} |
def sum_of_digits(n):
total = 0
while n > 0:
total += n % 10
n = n // 10
return total | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to return the sum of the digits of a given non-negative integer. For example, if the input is 123, the function should return 6 (1 + 2 + 3).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9521,
"level": 1,
"question": "Write a function to return the sum of the digits of a given non-negative integer. For example, if the input is 123, the function should return 6 (1 + 2 + 3).",
"split": "train"
} |
def max_non_decreasing_subarrays(a, k):
n = len(a)
if k == 1:
return n
if n < k:
return 0
increasing = []
for i in range(n-1):
if a[i] <= a[i+1]:
increasing.append(True)
else:
increasing.append(False)
current_run = 0
count = 0
requi... | simplelr_Filter | [
{
"content": "Question:\nHere is a problem that should be fun: Write a code snippet to solve the following problem: Given a 1D array of size n, find the maximum number of non-decreasing subarrays (contiguous subarray where every element is greater than or equal to the previous one) of size k within the given ar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9522,
"level": 1,
"question": "Here is a problem that should be fun: Write a code snippet to solve the following problem: Given a 1D array of size n, find the maximum number of non-decreasing subarrays (contiguous subarray where every element is greater than or equal to the previous... |
def iterative_binomial_coefficient(n, k):
# Handle the case where k is greater than n
if k > n:
raise ValueError('Invalid Inputs, ensure that n >= k')
# Create a 2D table to store values of the binomial coefficients
# Each row has (k + 1) elements because we only need to compute up to min(i... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Optimizing the Calculation of Binomial Coefficients\n\nYou are tasked with optimizing the calculation of binomial coefficients C(n, k) using a bottom-up dynamic programming approach. Given two non-negative integers `n` and `k`, compute the binomial coefficient efficiently.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9523,
"level": 1,
"question": "### Question: Optimizing the Calculation of Binomial Coefficients\n\nYou are tasked with optimizing the calculation of binomial coefficients C(n, k) using a bottom-up dynamic programming approach. Given two non-negative integers `n` and `k`, compute th... |
def add(num1, num2):
return num1 + num2 | simplelr_Filter | [
{
"content": "Question:\nI want you to act as a programming tutor for me. I will ask you questions about my code and you will answer them in simple terms that I can understand. Do not give me the answers outright, but guide me through the process of finding the solution myself. You should only reply with a brie... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9524,
"level": 1,
"question": "I want you to act as a programming tutor for me. I will ask you questions about my code and you will answer them in simple terms that I can understand. Do not give me the answers outright, but guide me through the process of finding the solution myself... |
def find_perfect_square(n):
if n < 0:
return None # Assuming n is non-negative as per problem statement
low = 0
high = n
while low <= high:
mid = (low + high) // 2
square = mid * mid
if square == n:
return square
elif square < n:
low = mid... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that finds a perfect square number less than or equal to a given number `n`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9525,
"level": 1,
"question": "Create a function that finds a perfect square number less than or equal to a given number `n`.",
"split": "train"
} |
def balanceChecker(expression):
stack = []
closing_bracket_map = {')': '(', '}': '{', ']': '['}
for char in expression:
if char in closing_bracket_map:
if not stack:
return False
if stack.pop() != closing_bracket_map[char]:
return False
... | simplelr_Apps | [
{
"content": "Question:\nWrite a function named **balanceChecker** that takes in a single argument - **expression** - which is a string containing various brackets: '(', ')', '{', '}', '[' and ']'.\n\nThe function should return **true** if the string contains balanced brackets and **false** otherwise. A set of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9526,
"level": 1,
"question": "Write a function named **balanceChecker** that takes in a single argument - **expression** - which is a string containing various brackets: '(', ')', '{', '}', '[' and ']'.\n\nThe function should return **true** if the string contains balanced brackets... |
def merge_intervals(intervals):
if not intervals:
return []
# Sort intervals based on the start time
sorted_intervals = sorted(intervals, key=lambda x: x[0])
# Initialize merged list with the first interval
merged = [sorted_intervals[0]]
for current in sorted_intervals[1:]... | simplelr_Filter | [
{
"content": "Question:\nHello, I need help with a Python code snippet. I have a list of tuples representing time intervals in the format (start, end). I want to merge overlapping intervals. For example, given `[(1, 4), (3, 5), (7, 8)]`, the merged list should be `[(1, 5), (7, 8)]`. How can I achieve this?\nAns... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9527,
"level": 1,
"question": "Hello, I need help with a Python code snippet. I have a list of tuples representing time intervals in the format (start, end). I want to merge overlapping intervals. For example, given `[(1, 4), (3, 5), (7, 8)]`, the merged list should be `[(1, 5), (7,... |
def filter_greater_than(numbers, threshold):
result = []
for num in numbers:
if num > threshold:
result.append(num)
return result
| simplelr_Taco | [
{
"content": "Question:\nYou are given an integer array `numbers` and an integer `threshold`. Your task is to return a new array containing only the numbers from the original array that are greater than the `threshold`. If no numbers are greater than the `threshold`, return an empty array.\n\n```\nfilter_greate... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9528,
"level": 1,
"question": "You are given an integer array `numbers` and an integer `threshold`. Your task is to return a new array containing only the numbers from the original array that are greater than the `threshold`. If no numbers are greater than the `threshold`, return an... |
def maxProfit(prices):
if len(prices) < 2:
return 0
min_price = prices[0]
max_profit = 0
for price in prices[1:]:
if price < min_price:
min_price = price
current_profit = price - min_price
if current_profit > max_profit:
max_profit = current_profit... | simplelr_Taco | [
{
"content": "Question:\n### Task: Stock Price Fluctuation\n\nYou are given an array consisting of daily stock prices for a particular company over a certain number of days. Your objective is to write a function that calculates the maximum possible profit that could have been made by buying and then later selli... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9529,
"level": 1,
"question": "### Task: Stock Price Fluctuation\n\nYou are given an array consisting of daily stock prices for a particular company over a certain number of days. Your objective is to write a function that calculates the maximum possible profit that could have been ... |
import socket
import argparse
def check_port_open(host, port):
try:
# Create a socket object
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# Set a timeout of 5 seconds
s.settimeout(5)
# Attempt to connect to the host and port
s.connect(... | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python script to check if a port is open on a specific host using the `socket` module?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9530,
"level": 1,
"question": "How can I create a Python script to check if a port is open on a specific host using the `socket` module?",
"split": "train"
} |
def matrix_diagonal_sum(matrix):
n = len(matrix)
sum_primary = 0
sum_secondary = 0
for i in range(n):
sum_primary += matrix[i][i]
sum_secondary += matrix[i][n - 1 - i]
total = sum_primary + sum_secondary
if n % 2 == 1:
mid = n // 2
total -= matrix[mid][mid]
... | simplelr_Taco | [
{
"content": "Question:\n*** Matrix Diagonal Sum***\n\nGiven a square matrix `n x n` (2D list), write a function that calculates the sum of both the primary and secondary diagonals, excluding the center element if the matrix size is odd.\n\nFor example:\n\n```python\nmatrix_diagonal_sum([[1, 2, 3],\n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9531,
"level": 1,
"question": "*** Matrix Diagonal Sum***\n\nGiven a square matrix `n x n` (2D list), write a function that calculates the sum of both the primary and secondary diagonals, excluding the center element if the matrix size is odd.\n\nFor example:\n\n```python\nmatrix_di... |
def find_key_in_matrix(matrix, key):
for i in range(len(matrix)):
row = matrix[i]
low = 0
high = len(row) - 1
while low <= high:
mid = (low + high) // 2
if row[mid] == key:
return (i + 1, mid + 1)
elif row[mid] < key:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question\n\nGiven a 2D matrix where each row and column is sorted in non-decreasing order, write a function `find_key_in_matrix(matrix, key)` that returns the position (row, column) of the given key if it is present in the matrix. If the key is not present, the function should retur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9532,
"level": 1,
"question": "### Question\n\nGiven a 2D matrix where each row and column is sorted in non-decreasing order, write a function `find_key_in_matrix(matrix, key)` that returns the position (row, column) of the given key if it is present in the matrix. If the key is not... |
def sum_of_positives(numbers):
return sum(num for num in numbers if num > 0)
| simplelr_Taco | [
{
"content": "Question:\n# Sum of Positive Numbers\n\nCreate a function that takes an array of numbers as an input and returns the sum of all positive numbers in the array. If there are no positive numbers, the function should return 0.\n\n### Example\n```python\nsum_of_positives([1, -2, 3, 4, -5]) # Returns 8... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9533,
"level": 1,
"question": "# Sum of Positive Numbers\n\nCreate a function that takes an array of numbers as an input and returns the sum of all positive numbers in the array. If there are no positive numbers, the function should return 0.\n\n### Example\n```python\nsum_of_positi... |
def evaluate_postfix(expression: str) -> float:
tokens = expression.split()
stack = []
for token in tokens:
if token in '+-/*':
a = stack.pop()
b = stack.pop()
if token == '+':
stack.append(b + a)
elif token == '-':
stac... | simplelr_Algorithm | [
{
"content": "Question:\n### **Evaluate Postfix Expression**\n\nYour task is to evaluate a given postfix expression and return the final result. A postfix expression (also known as Reverse Polish notation) is a mathematical notation in which every operator follows all of its operands. This makes it easy to proc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9534,
"level": 1,
"question": "### **Evaluate Postfix Expression**\n\nYour task is to evaluate a given postfix expression and return the final result. A postfix expression (also known as Reverse Polish notation) is a mathematical notation in which every operator follows all of its o... |
def find_first_non_repeating_char(s: str) -> str:
"""
Function to find the first non-repeating character in a string.
"""
if not s:
return ""
# Dictionary to keep track of character counts
char_count = {}
# First pass: count each character's occurrences
for char in s:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Objective\nImplement a function to find the first non-repeating character in a given string. Your implementation should efficiently handle scenarios with frequent repetitions and large input strings.\n\n#### Task\nWrite a function `find_first_non_r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9535,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Objective\nImplement a function to find the first non-repeating character in a given string. Your implementation should efficiently handle scenarios with frequent repetitions and large input strings.\n\n#### Task\... |
def rotate_matrix(matrix: list[list[int]]) -> list[list[int]]:
"""
Rotates a square 2D list (matrix) by 90 degrees clockwise and returns the result.
:param matrix: A square 2D list of integers.
:return: The 90-degree clockwise rotated matrix.
Requirements:
- If the matrix is empty, return an e... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\nYou are tasked with implementing a function that rotates a square 2D list (matrix) by 90 degrees clockwise. Given the constraints and requirements outlined below, write a function that adheres to the described behavior.\n\n### Function Signature\n```python\ndef ro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9536,
"level": 1,
"question": "### Problem Statement\nYou are tasked with implementing a function that rotates a square 2D list (matrix) by 90 degrees clockwise. Given the constraints and requirements outlined below, write a function that adheres to the described behavior.\n\n### Fu... |
def insertion_sort(input_list):
sorted_list = input_list[:] # Create a copy of the input list
for i in range(1, len(sorted_list)):
current = sorted_list[i]
position = i
# Shift elements greater than current to the right
while position > 0 and sorted_list[position - 1] > current:... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that implements the insertion sort algorithm. The function should take a list of integers as an argument and return a new list that is sorted in ascending order. Make sure to handle cases when the input list is empty or has only a single element.\nAnswer:\nLet's think ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9537,
"level": 1,
"question": "Create a function that implements the insertion sort algorithm. The function should take a list of integers as an argument and return a new list that is sorted in ascending order. Make sure to handle cases when the input list is empty or has only a sin... |
def count_vowels(s):
return sum(1 for char in s.lower() if char in {'a', 'e', 'i', 'o', 'u'}) | simplelr_Filter | [
{
"content": "Question:\nHey, can you write a Python function that takes a string as input and returns the number of vowels in the string?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9538,
"level": 1,
"question": "Hey, can you write a Python function that takes a string as input and returns the number of vowels in the string?",
"split": "train"
} |
def count_case(s):
uppercase = 0
lowercase = 0
for c in s:
if c.isupper():
uppercase += 1
elif c.islower():
lowercase += 1
return (uppercase, lowercase) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a string as input and returns the count of uppercase and lowercase letters in the string. The function should be named `count_case` and should return a tuple where the first element is the count of uppercase letters and the second element is the count ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9539,
"level": 1,
"question": "Write a Python function that takes a string as input and returns the count of uppercase and lowercase letters in the string. The function should be named `count_case` and should return a tuple where the first element is the count of uppercase letters a... |
def maxOccurrence(S):
from collections import defaultdict
freq = defaultdict(int)
for c in S:
freq[c] += 1
max_freq = max(freq.values())
candidates = [char for char, count in freq.items() if count == max_freq]
candidates.sort()
return candidates[0]
| simplelr_Taco | [
{
"content": "Question:\nGiven a string S consisting of uppercase and lowercase alphabets. The task is to find the maximum occurring character in the string.\nExample 1:\nInput:\nS = \"sample\"\nOutput: \"a\"\nExplanation: \"a\", \"e\", \"l\", \"m\", \"p\", \"s\" all occur with frequency 1. The lexicographicall... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9540,
"level": 1,
"question": "Given a string S consisting of uppercase and lowercase alphabets. The task is to find the maximum occurring character in the string.\nExample 1:\nInput:\nS = \"sample\"\nOutput: \"a\"\nExplanation: \"a\", \"e\", \"l\", \"m\", \"p\", \"s\" all occur wit... |
def smallest_supersequence(str_a: str, str_b: str) -> int:
m = len(str_a)
n = len(str_b)
# Create a DP table with (m+1) rows and (n+1) columns initialized to 0
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Fill the DP table
for i in range(1, m + 1):
for j in range(1, n + 1):
... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\nYou are given two strings, `str_a` and `str_b`. Your task is to implement the function `smallest_supersequence` that finds the length of the smallest supersequence of the given two strings. A supersequence of a group of sequences is a sequence that contains all those seq... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9541,
"level": 1,
"question": "### Question\n\nYou are given two strings, `str_a` and `str_b`. Your task is to implement the function `smallest_supersequence` that finds the length of the smallest supersequence of the given two strings. A supersequence of a group of sequences is a s... |
def sum_list(lst):
"""
Returns the sum of all integers in the given list.
Args:
lst (list): A list of integers.
Returns:
int: The sum of all integers in the list. If the list is empty, returns 0.
"""
return sum(lst)
# Test cases
assert sum_list([1, 2, 3]) == 6, "Test c... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of integers as input and returns the sum of all the integers in the list. The function should be named `sum_list` and should have a docstring that describes its purpose, parameters, and return value. Additionally, the function should handle the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9542,
"level": 1,
"question": "Write a Python function that takes a list of integers as input and returns the sum of all the integers in the list. The function should be named `sum_list` and should have a docstring that describes its purpose, parameters, and return value. Additional... |
def reverse_words(sentence: str) -> str:
words = sentence.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Algorithm | [
{
"content": "Question:\nReverse Words in a Sentence\n\nYou are given a string representing a sentence. Your task is to implement a function that reverses the order of words in the sentence without altering the order of characters within each word. \n\n#### Problem Statement:\n\n1. **Objective**: Implement a fu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9543,
"level": 1,
"question": "Reverse Words in a Sentence\n\nYou are given a string representing a sentence. Your task is to implement a function that reverses the order of words in the sentence without altering the order of characters within each word. \n\n#### Problem Statement:\... |
def word_break(text: str, wordDict: set) -> bool:
if not wordDict:
return False
max_len = max(len(word) for word in wordDict)
n = len(text)
dp = [False] * (n + 1)
dp[0] = True # empty string can be segmented
for i in range(1, n + 1):
# Check up to the maximum word leng... | simplelr_Data_Structure | [
{
"content": "Question:\n### Word Segmentation Problem\n\nYou are provided with a non-empty string `text` and a set `wordDict` containing a list of non-empty words. Implement a function `word_break(text, wordDict)` that returns `True` if the string `text` can be segmented into a space-separated sequence of one ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9544,
"level": 1,
"question": "### Word Segmentation Problem\n\nYou are provided with a non-empty string `text` and a set `wordDict` containing a list of non-empty words. Implement a function `word_break(text, wordDict)` that returns `True` if the string `text` can be segmented into... |
def next_bigger(n: int) -> int:
s = list(map(int, str(n)))
i = len(s) - 2
# Find the first digit that is smaller than its next digit
while i >= 0 and s[i] >= s[i+1]:
i -= 1
if i == -1:
return -1 # No such number, highest permutation
# Find the smallest digit large... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a number `n` represented as an integer. Your task is to write a function `next_bigger(n)` that finds the next higher number which has the exact same set of digits as `n`. If no such number exists, return `-1`.\n\nThe input and output for your function are specified as foll... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9545,
"level": 1,
"question": "You are given a number `n` represented as an integer. Your task is to write a function `next_bigger(n)` that finds the next higher number which has the exact same set of digits as `n`. If no such number exists, return `-1`.\n\nThe input and output for ... |
import bisect
def find_closest_number(arr, target):
pos = bisect.bisect_left(arr, target)
if pos == 0:
return arr[pos]
if pos == len(arr):
return arr[-1]
before = arr[pos - 1]
after = arr[pos]
if target - before <= after - target:
return before
else:
return a... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `arr` of **unique** integers sorted in **increasing order** and an integer `target`, return _the integer in the array that is **closest** to the target_. If there are two numbers in the array equally close to the target, return the smaller number.\nAnswer:\nLet's ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9546,
"level": 1,
"question": "Given an integer array `arr` of **unique** integers sorted in **increasing order** and an integer `target`, return _the integer in the array that is **closest** to the target_. If there are two numbers in the array equally close to the target, return t... |
from typing import List
def max_value_difference(mat: List[List[int]]) -> int:
if not mat or len(mat) < 2 or len(mat[0]) < 2:
return None
rows = len(mat)
cols = len(mat[0])
min_table = [[0 for _ in range(cols)] for _ in range(rows)]
# Initialize the first cell
min_table[0][0] ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a 2D matrix `mat` of integers, find the maximum value of `mat[c][d] - mat[a][b]` where `c > a` and `d > b`. Return the maximum value, or `null` if no such elements exist.\n\nWrite a function:\n\n```python\ndef max_value_difference(mat: List[List[int]]) -> int:\n # Your code her... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9547,
"level": 1,
"question": "Given a 2D matrix `mat` of integers, find the maximum value of `mat[c][d] - mat[a][b]` where `c > a` and `d > b`. Return the maximum value, or `null` if no such elements exist.\n\nWrite a function:\n\n```python\ndef max_value_difference(mat: List[List[... |
def transform_json_object(json_list):
return [{'text': item} if isinstance(item, str) else item for item in json_list] | simplelr_Filter | [
{
"content": "Question:\nI have a JSON object that contains a list of items, each item being either a string or a dictionary with a key named 'text'. If the item is a string, I want to replace it with a dictionary with the key 'text' and the string as its value. What's the best way to do this in Python?\nAnswer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9548,
"level": 1,
"question": "I have a JSON object that contains a list of items, each item being either a string or a dictionary with a key named 'text'. If the item is a string, I want to replace it with a dictionary with the key 'text' and the string as its value. What's the bes... |
def sieve_of_eratosthenes(n):
if n < 2:
return []
sieve_list = [True] * (n + 1)
sieve_list[0], sieve_list[1] = False, False
for i in range(2, int(n ** 0.5) + 1):
if sieve_list[i]:
sieve_list[i*i : n+1 : i] = [False] * len(sieve_list[i*i : n+1 : i])
return [i for i, is_pri... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to generate all prime numbers up to a given number using the Sieve of Eratosthenes algorithm. The function should take an integer `n` as input and return a list of all prime numbers less than or equal to `n`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9549,
"level": 1,
"question": "Write a function to generate all prime numbers up to a given number using the Sieve of Eratosthenes algorithm. The function should take an integer `n` as input and return a list of all prime numbers less than or equal to `n`.",
"split": "train"
} |
def find_first_occurrence(arr, target):
low = 0
high = len(arr) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
result = mid
high = mid - 1 # Continue searching left for earlier occurrences
elif arr[mid] < target:
... | simplelr_Filter | [
{
"content": "Question:\nGiven a sorted array of strings, implement a function to find the first occurrence of a given string. The function should return the index of the string if found, otherwise -1.\n\nExample 1:\nInput: arr = [\"apple\", \"banana\", \"cherry\", \"date\", \"elderberry\"], target = \"cherry\"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9550,
"level": 1,
"question": "Given a sorted array of strings, implement a function to find the first occurrence of a given string. The function should return the index of the string if found, otherwise -1.\n\nExample 1:\nInput: arr = [\"apple\", \"banana\", \"cherry\", \"date\", \... |
def int_to_binary(n: int, format: str = 'compact') -> str:
if not isinstance(n, int) or n < 0:
raise ValueError("Input must be a non-negative integer.")
if format not in ['compact', 'readable']:
raise ValueError("Invalid format. Format must be either 'compact' or 'readable'.")
binary = ... | simplelr_Filter | [
{
"content": "Question:\nHere is the problem I am trying to solve: \nCreate a function that takes an integer as input and returns a string representing the integer as a binary number. The function should take an optional string argument, format, which can be either 'compact' or 'readable'. If the format is 'com... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9551,
"level": 1,
"question": "Here is the problem I am trying to solve: \nCreate a function that takes an integer as input and returns a string representing the integer as a binary number. The function should take an optional string argument, format, which can be either 'compact' o... |
def is_anagram_of_substring(s1: str, s2: str) -> bool:
m = len(s1)
n = len(s2)
if m == 0:
return True
if m > n:
return False
# Initialize frequency arrays for s1 and the sliding window
s1_freq = [0] * 26
for c in s1:
s1_freq[ord(c) - ord('a')] += 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question: String Pattern Anagram Check\n\n#### Objective:\nYou are given two strings and your task is to determine if one string is an anagram of a substring of the other. Write a function to achieve this.\n\n#### Problem Statement:\nWrite a function `is_anagram_of_substring(... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9552,
"level": 1,
"question": "### Coding Question: String Pattern Anagram Check\n\n#### Objective:\nYou are given two strings and your task is to determine if one string is an anagram of a substring of the other. Write a function to achieve this.\n\n#### Problem Statement:\nWrite a... |
def reverse_strings(lst):
return lst[::-1] | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that takes a list of strings and returns a new list with the strings in reverse order?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9553,
"level": 1,
"question": "How can I create a Python function that takes a list of strings and returns a new list with the strings in reverse order?",
"split": "train"
} |
def min_cost_to_collect_balls(nums, costs):
total = 0
for i in range(1, len(nums)):
total += nums[i] * costs[i]
return total | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` representing the number of balls in each box. You have another array `costs` where `costs[i]` is the cost to move one ball from the `ith` box to another box. You need to move all balls from each box to the `0-th` index box. Return the minimum cost t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9554,
"level": 1,
"question": "You are given an integer array `nums` representing the number of balls in each box. You have another array `costs` where `costs[i]` is the cost to move one ball from the `ith` box to another box. You need to move all balls from each box to the `0-th` i... |
def longest_subarray_with_sum_k(arr, k):
sum_map = {0: -1}
current_sum = 0
max_length = 0
for j in range(len(arr)):
current_sum += arr[j]
# Check if (current_sum - k) exists in the map
if (current_sum - k) in sum_map:
length = j - sum_map[current_sum - k]
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `arr` and an integer `k`. You need to find the length of the longest contiguous subarray whose sum is equal to `k`. If there is no such subarray, return `0`. \n\nFor example, given the array `arr = [1, -1, 5, -2, 3]` and `k = 3`, the function should return... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9555,
"level": 1,
"question": "You are given an integer array `arr` and an integer `k`. You need to find the length of the longest contiguous subarray whose sum is equal to `k`. If there is no such subarray, return `0`. \n\nFor example, given the array `arr = [1, -1, 5, -2, 3]` and ... |
def gcd(a, b):
"""
Calculate the greatest common divisor (GCD) of two integers using the Euclidean algorithm.
Parameters:
a (int): The first integer.
b (int): The second integer.
Returns:
int: The greatest common divisor of a and b.
Example:
>>> gcd(48, 18)
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to calculate the greatest common divisor (GCD) of two integers using the Euclidean algorithm. Ensure your function is well-documented and includes a docstring explaining the purpose, parameters, and return value of the function. Additionally, provide a simple exa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9556,
"level": 1,
"question": "Write a Python function to calculate the greatest common divisor (GCD) of two integers using the Euclidean algorithm. Ensure your function is well-documented and includes a docstring explaining the purpose, parameters, and return value of the function.... |
def is_valid_calculation(calculation: str) -> bool:
if not calculation:
return False
if calculation[0] in '+-*/' or calculation[-1] in '+-*/':
return False
for i in range(1, len(calculation)):
prev = calculation[i-1]
curr = calculation[i]
if prev in '+-*/' and curr in... | simplelr_Algorithm | [
{
"content": "Question:\n### String Calculation Validity Checker\n\nYou are required to write a function `is_valid_calculation` that checks whether a given string is a valid calculation string. The function should parse and validate a string that contains non-negative integers and the operators `+`, `-`, `*`, o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9557,
"level": 1,
"question": "### String Calculation Validity Checker\n\nYou are required to write a function `is_valid_calculation` that checks whether a given string is a valid calculation string. The function should parse and validate a string that contains non-negative integers... |
def is_mountain_element(nums, target):
n = len(nums)
for i in range(n):
if nums[i] == target:
if i == 0 or i == n - 1:
continue
if nums[i-1] < target and nums[i+1] < target:
return True
return False | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` sorted in **non-decreasing** order, and an integer `target`. Your goal is to determine if `target` is a **mountain element** in `nums`. An element `nums[i]` is considered a **mountain element** if it is larger than its immediate neighbors, i.e., `nu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9558,
"level": 1,
"question": "You are given an integer array `nums` sorted in **non-decreasing** order, and an integer `target`. Your goal is to determine if `target` is a **mountain element** in `nums`. An element `nums[i]` is considered a **mountain element** if it is larger than... |
def get_distinct_elements(list1, list2):
seen = set()
result = []
for elem in list1:
if isinstance(elem, dict):
key = tuple(sorted(elem.items()))
else:
key = elem
if key not in seen:
seen.add(key)
result.append(elem)
for elem in lis... | simplelr_Filter | [
{
"content": "Question:\nWrite an efficient Python code that produces a list which includes only the distinct elements from two given lists, but the elements in the resulting list must be in the order of their appearance in the first list. Both the input lists might contain strings, numbers and dictionaries. If... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9559,
"level": 1,
"question": "Write an efficient Python code that produces a list which includes only the distinct elements from two given lists, but the elements in the resulting list must be in the order of their appearance in the first list. Both the input lists might contain st... |
def first_non_repeated_character(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char in s:
if char_count[char] == 1:
return char
return None | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to get the first non-repeated character in a string. If there is no non-repeated character, the function should return `None`. For example, given the string \"programming\", the function should return \"p\" because \"p\" is the first character that does not repea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9560,
"level": 1,
"question": "Write a python function to get the first non-repeated character in a string. If there is no non-repeated character, the function should return `None`. For example, given the string \"programming\", the function should return \"p\" because \"p\" is the ... |
def calculate_discounted_price(original_price, discount_percentage):
"""
Calculate the total price of a product after applying a discount.
Args:
original_price (float): The original price of the product before any discount.
discount_percentage (float): The percentage discount to be applied ... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to calculate the total price of a product after applying a discount. The function should take the original price and the discount percentage as arguments and return the final price after the discount. Ensure the function is well-documented and includes a docstrin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9561,
"level": 1,
"question": "Write a Python function to calculate the total price of a product after applying a discount. The function should take the original price and the discount percentage as arguments and return the final price after the discount. Ensure the function is well... |
def secure_modular_exponentiation(base: int, exponent: int, mod: int) -> int:
if exponent == 0:
return 1 % mod
result = 1
current_base = base % mod
exponent_remaining = exponent
while exponent_remaining > 0:
if exponent_remaining % 2 == 1:
result = (result * current_base)... | simplelr_Data_Structure | [
{
"content": "Question:\n### Problem: Secure Communication Setup\n\nIn the field of information security, one common problem is to securely establish a communication channel between two parties. One way to do this is through the Diffie-Hellman key exchange protocol, which relies on computing large powers with a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9562,
"level": 1,
"question": "### Problem: Secure Communication Setup\n\nIn the field of information security, one common problem is to securely establish a communication channel between two parties. One way to do this is through the Diffie-Hellman key exchange protocol, which reli... |
from typing import List
def enhanced_counting_sort(arr: List[int]) -> List[int]:
if not arr:
return []
min_val = min(arr)
max_val = max(arr)
shift = -min_val
count_size = max_val - min_val + 1
buckets = [[] for _ in range(count_size)]
for num in arr:
shifted =... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Enhanced Counting Sort for Mixed Numbers\n\n#### Context\nYou have been given an array of integers that may contain both negative and positive numbers. Your task is to implement an enhanced version of the Counting Sort algorithm that can handle this mixed range of integers... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9563,
"level": 1,
"question": "### Question: Enhanced Counting Sort for Mixed Numbers\n\n#### Context\nYou have been given an array of integers that may contain both negative and positive numbers. Your task is to implement an enhanced version of the Counting Sort algorithm that can ... |
def canPickGiftBoxes(M, V, A):
if V == 0:
return "Yes"
prev_not = [False] * (V + 1)
prev_yes = [False] * (V + 1)
prev_not[0] = True
if A[0] <= V:
prev_yes[A[0]] = True
for i in range(1, M):
a = A[i]
current_not = [False] * (V + 1)
current_ye... | simplelr_Taco | [
{
"content": "Question:\nKate is putting together a special gift for her friend. She has a collection of M gift boxes each with a certain value of goodies. She wants to select some of these boxes such that their combined value matches exactly her desired value V. However, from the selection of these boxes, ther... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9564,
"level": 1,
"question": "Kate is putting together a special gift for her friend. She has a collection of M gift boxes each with a certain value of goodies. She wants to select some of these boxes such that their combined value matches exactly her desired value V. However, from... |
def greet(name=None, age=None):
"""Returns a personalized greeting message."""
if name:
greeting = f"Hello, {name}!"
if age is not None:
greeting += f" You are {age} years old."
return greeting
return "Hello, stranger!" | simplelr_Filter | [
{
"content": "Question:\ndef greet(name, age=None):\n \"\"\"Returns a personalized greeting message.\"\"\"\n if name:\n greeting = f\"Hello, {name}!\"\n if age:\n greeting += f\" You are {age} years old.\"\n return greeting\n return \"Hello, stranger!\"\nAnswer:\nLet's t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9565,
"level": 1,
"question": "def greet(name, age=None):\n \"\"\"Returns a personalized greeting message.\"\"\"\n if name:\n greeting = f\"Hello, {name}!\"\n if age:\n greeting += f\" You are {age} years old.\"\n return greeting\n return \"H... |
def min_coins(amount, coins):
if amount < 0:
return -1
# Remove non-positive denominations and duplicates
coins = [c for c in set(coins) if c > 0]
if not coins:
return 0 if amount == 0 else -1
# Initialize dp array
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for i in ran... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to return the minimum number of coins needed to make up a given amount with a given set of coin denominations. You should consider all possible combinations of coin denominations.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9566,
"level": 1,
"question": "Write a python function to return the minimum number of coins needed to make up a given amount with a given set of coin denominations. You should consider all possible combinations of coin denominations.",
"split": "train"
} |
def transform_point(matrix, point):
# Validate the transformation matrix
if not isinstance(matrix, list) or len(matrix) != 2:
raise Exception("Invalid transformation matrix")
for row in matrix:
if not isinstance(row, list) or len(row) != 2:
raise Exception("Invalid transformation... | simplelr_Algorithm | [
{
"content": "Question:\n### Context:\nIn computer graphics, mapping points from one coordinate space to another is a fundamental task, especially in transformations and rendering. This involves various linear algebra operations, which are central to graphics programming.\n\n### Objective:\nImplement a function... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9567,
"level": 1,
"question": "### Context:\nIn computer graphics, mapping points from one coordinate space to another is a fundamental task, especially in transformations and rendering. This involves various linear algebra operations, which are central to graphics programming.\n\n#... |
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
# Swap elements
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break... | simplelr_Filter | [
{
"content": "Question:\nCreate a program that sorts an array of numbers in ascending order using the bubble sort algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9568,
"level": 1,
"question": "Create a program that sorts an array of numbers in ascending order using the bubble sort algorithm.",
"split": "train"
} |
def decompose_sparse_matrix(A):
I = []
J = []
V = []
for i in range(len(A)):
row = A[i]
for j in range(len(row)):
val = row[j]
if val != 0:
I.append(i)
J.append(j)
V.append(val)
return I, J, V | simplelr_Filter | [
{
"content": "Question:\n### Decomposing Sparse Matrices\nFor a sparse matrix \\( A \\) with \\( m \\) rows and \\( n \\) columns, where most elements are zero, we can decompose it into three vectors, \\( I \\), \\( J \\), and \\( V \\), of the same length. In these vectors, \\( I \\) contains the row indices, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9569,
"level": 1,
"question": "### Decomposing Sparse Matrices\nFor a sparse matrix \\( A \\) with \\( m \\) rows and \\( n \\) columns, where most elements are zero, we can decompose it into three vectors, \\( I \\), \\( J \\), and \\( V \\), of the same length. In these vectors, \... |
def strip_values(s):
values = s.split(";")
result = ';'.join(values[::2])
return result | simplelr_Filter | [
{
"content": "Question:\nI have a string that contains a number of values separated by semicolons. I want to write a Python function that will strip out every other line from this string, starting from the first value.\n\nHere is an example string:\n```\n\"dog;cat;elephant;giraffe;lion;monkey\"\n```\nThe outpu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9570,
"level": 1,
"question": "I have a string that contains a number of values separated by semicolons. I want to write a Python function that will strip out every other line from this string, starting from the first value.\n\nHere is an example string:\n```\n\"dog;cat;elephant;gi... |
def remove_duplicates(lst):
seen = set()
result = []
for num in lst:
if num not in seen:
result.append(num)
seen.add(num)
return result | simplelr_Apps | [
{
"content": "Question:\nGiven a list of integers `lst`, write a function that returns a new list containing all the elements of the original list, but with all duplicate elements removed and the order of the remaining elements preserved.\n\nFor example:\n```python\nremove_duplicates([1, 2, 2, 3, 4, 4, 5]) == [... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9571,
"level": 1,
"question": "Given a list of integers `lst`, write a function that returns a new list containing all the elements of the original list, but with all duplicate elements removed and the order of the remaining elements preserved.\n\nFor example:\n```python\nremove_dup... |
def min_platforms_needed(arr, dep):
# Convert arrival times to minutes
arr_times = []
for t in arr:
h, m = map(int, t.split(':'))
arr_times.append(h * 60 + m)
# Convert departure times to minutes
dep_times = []
for t in dep:
h, m = map(int, t.split(':'))
dep_... | simplelr_Apps | [
{
"content": "Question:\nYou are given a list of trains arriving at a railway station and each train has an arrival time and departure time. Your task is to find the minimum number of platforms required at the railway station so that no train has to wait.\n\nEach train will arrive and depart on the same day, an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9572,
"level": 1,
"question": "You are given a list of trains arriving at a railway station and each train has an arrival time and departure time. Your task is to find the minimum number of platforms required at the railway station so that no train has to wait.\n\nEach train will ar... |
def remove_reoccurring_characters(string):
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#### Scenario\nYou have been tasked with writing a function for cleaning up a list of products by eliminating all duplicates while maintaining the original order. This function is crucial for preprocessing product lists before performing further analysis.\n\n#### Task\nWrite a function ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9573,
"level": 1,
"question": "#### Scenario\nYou have been tasked with writing a function for cleaning up a list of products by eliminating all duplicates while maintaining the original order. This function is crucial for preprocessing product lists before performing further analys... |
def largest_substring(s, length):
# Handle cases where the input is invalid
if s is None or length < 1 or len(s) < length:
return ""
max_substring = ""
for i in range(len(s) - length + 1):
substring = s[i:i + length]
if substring > max_substring:
max_substring = ... | simplelr_Filter | [
{
"content": "Question:\nGiven a string, find the lexicographically largest substring of a given length.\n\nExample:\n\nInput: \nstring = \"apple\"\nlength = 2\n\nOutput: \"pp\"\n\nExplanation: \nThe lexicographically largest substring of length 2 is \"pp\".\n\nExample:\n\nInput: \nstring = \"example\"\nlength ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9574,
"level": 1,
"question": "Given a string, find the lexicographically largest substring of a given length.\n\nExample:\n\nInput: \nstring = \"apple\"\nlength = 2\n\nOutput: \"pp\"\n\nExplanation: \nThe lexicographically largest substring of length 2 is \"pp\".\n\nExample:\n\nInp... |
from typing import List
def trap_rain_water(heights: List[int]) -> int:
if not heights:
return 0
left = 0
right = len(heights) - 1
left_max = right_max = 0
result = 0
while left <= right:
if heights[left] <= heights[right]:
if heights[left] >= left_max:
... | simplelr_Taco | [
{
"content": "Question:\nA box has a row of water containers, each with different heights. The heights of containers are represented by an array of positive integers. The amount of water that can be trapped between these containers when it rains is calculated by the amount of water each container can hold based... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9575,
"level": 1,
"question": "A box has a row of water containers, each with different heights. The heights of containers are represented by an array of positive integers. The amount of water that can be trapped between these containers when it rains is calculated by the amount of ... |
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that implements a bubble sort algorithm. Bubble sort is a simple comparison-based algorithm that iterates over the list, compares adjacent elements, and swaps them if they are in the wrong order. The process is repeated until the list is sorted. In this function, you s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9576,
"level": 1,
"question": "Create a function that implements a bubble sort algorithm. Bubble sort is a simple comparison-based algorithm that iterates over the list, compares adjacent elements, and swaps them if they are in the wrong order. The process is repeated until the list... |
def filter_non_divisible_by_3(numbers):
return [num for num in numbers if num % 3 != 0] | simplelr_Filter | [
{
"content": "Question:\nI have a simple test case. I will provide you with a list of numbers and you need to write a function that returns the numbers that are not divisible by 3. \n\nFor example, if I give you the list `[1, 2, 3, 4, 5, 6]` the function should return `[1, 2, 4, 5]`. \n\nCan you please write th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9577,
"level": 1,
"question": "I have a simple test case. I will provide you with a list of numbers and you need to write a function that returns the numbers that are not divisible by 3. \n\nFor example, if I give you the list `[1, 2, 3, 4, 5, 6]` the function should return `[1, 2, ... |
import json
def parse_nested_list(s):
return json.loads(f'[{s}]')
# Example usage:
s = "1,2,[3,4],[5,6,[7,8]]"
result = parse_nested_list(s)
print(result) # Output: [1, 2, [3, 4], [5, 6, [7, 8]]] | simplelr_Filter | [
{
"content": "Question:\nI have a string that represents a nested list. It looks something like this: \"1,2,[3,4],[5,6,[7,8]]\". How would I go about parsing it into an actual nested list in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9578,
"level": 1,
"question": "I have a string that represents a nested list. It looks something like this: \"1,2,[3,4],[5,6,[7,8]]\". How would I go about parsing it into an actual nested list in Python?",
"split": "train"
} |
import os
import shutil
from pathlib import Path
def manage_files_and_directories(base_dir, backup_dir):
# Ensure backup directory exists
try:
os.makedirs(backup_dir, exist_ok=True)
except Exception as e:
print(f"Error creating backup directory: {e}")
return # Exit if backup direct... | simplelr_Docs | [
{
"content": "Question:\n## File and Directory Management\n\n### Objective\nYou are tasked to design a function that manages files and directories in a given directory subtree. The function will perform various operations like listing files, copying files to a backup directory, and deleting files based on speci... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9579,
"level": 1,
"question": "## File and Directory Management\n\n### Objective\nYou are tasked to design a function that manages files and directories in a given directory subtree. The function will perform various operations like listing files, copying files to a backup directory... |
from typing import List, Dict, Any
def analyze_data(data: List[Dict[str, Any]]) -> Dict[str, Any]:
total_value_per_category = {}
unique_tags = set()
max_value = -float('inf')
highest_item = None
for item in data:
# Calculate total value per category
category = item['category']
... | simplelr_Docs | [
{
"content": "Question:\n### Complex Data Analysis with Lists and Dictionaries in Python\n\n#### Objective:\nCreate a function `analyze_data` that takes a list of dictionaries as input and returns an aggregated analysis based on specified criteria. Each dictionary in the input list represents a record containin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9580,
"level": 1,
"question": "### Complex Data Analysis with Lists and Dictionaries in Python\n\n#### Objective:\nCreate a function `analyze_data` that takes a list of dictionaries as input and returns an aggregated analysis based on specified criteria. Each dictionary in the input... |
def unique_substrings(s):
substrings = set()
n = len(s)
for l in range(1, n + 1):
for i in range(n - l + 1):
substring = s[i:i+l]
substrings.add(substring)
return substrings | simplelr_Filter | [
{
"content": "Question:\nThis problem asks you to create a function that can find all the unique substrings from a given string. A substring is a string that can be formed from another string by deleting some (can be none) of the characters without disturbing the order of the remaining characters. (e.g. \"abc\"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9581,
"level": 1,
"question": "This problem asks you to create a function that can find all the unique substrings from a given string. A substring is a string that can be formed from another string by deleting some (can be none) of the characters without disturbing the order of the ... |
def first_missing_positive(nums):
positives = set()
for num in nums:
if num > 0:
positives.add(num)
i = 1
while True:
if i not in positives:
return i
i += 1 | simplelr_Code_Contests | [
{
"content": "Question:\nYou are given a list of integers. Your task is to find the smallest missing positive integer from this list. A positive integer is defined as any integer greater than 0.\n\nWrite a function that receives a list of integers and returns the smallest missing positive integer.\n\nInput\n\nT... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9582,
"level": 1,
"question": "You are given a list of integers. Your task is to find the smallest missing positive integer from this list. A positive integer is defined as any integer greater than 0.\n\nWrite a function that receives a list of integers and returns the smallest miss... |
def find_anagram_substrings(file_path):
from collections import Counter
try:
with open(file_path, 'r') as file:
main_string = file.readline().strip()
target_word = file.readline().strip()
target_len = len(target_word)
main_len = len(main_string)
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question: Substring Anagram Finder\n\nYou are given a text file `input.txt` that contains a string of lowercase letters and a target word. Your task is to write a Python function `find_anagram_substrings(file_path)` that reads the file, processes the string and the target wor... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9583,
"level": 1,
"question": "### Coding Question: Substring Anagram Finder\n\nYou are given a text file `input.txt` that contains a string of lowercase letters and a target word. Your task is to write a Python function `find_anagram_substrings(file_path)` that reads the file, proc... |
def balance_parentheses(s):
min_open = 0
max_open = 0
for c in s:
if c == '(':
min_open += 1
max_open += 1
elif c == ')':
min_open = max(min_open - 1, 0)
max_open -= 1
else:
min_open = max(min_open - 1, 0)
max_op... | simplelr_Package | [
{
"content": "Question:\nYou are given a task to write a function named `balance_parentheses` that takes a string consisting of only three types of characters: '(', ')', and '*'. This function should determine if it is possible to balance the parentheses in the string by treating each '*' as either an opening p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9584,
"level": 1,
"question": "You are given a task to write a function named `balance_parentheses` that takes a string consisting of only three types of characters: '(', ')', and '*'. This function should determine if it is possible to balance the parentheses in the string by treat... |
def update_dict_with_tuples(dictionary, tuple_list):
ignored_updates = 0
for key, value in tuple_list:
if key in dictionary:
ignored_updates += 1
else:
dictionary[key] = value
return dictionary, ignored_updates | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function that takes a dictionary and a list of tuples, where each tuple contains two elements: a key and a value. The function should update the dictionary by adding the key-value pairs from the list, but only if the key does not already exist in the dictionary. If the k... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9585,
"level": 1,
"question": "Design a Python function that takes a dictionary and a list of tuples, where each tuple contains two elements: a key and a value. The function should update the dictionary by adding the key-value pairs from the list, but only if the key does not alread... |
import heapq
def trapRainWater(matrix):
if not matrix or len(matrix) < 3 or len(matrix[0]) < 3:
return 0
m = len(matrix)
n = len(matrix[0])
visited = [[False for _ in range(n)] for _ in range(m)]
heap = []
# Push all boundary cells into the heap and mark as visited
fo... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a **matrix** of integers, where each cell represents the elevation at that point, design an algorithm to compute the **maximum water volume** trapped in the matrix after raining. The water can only be trapped in valleys and cannot leak off the edge of the matrix. Each cell can hol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9586,
"level": 1,
"question": "Given a **matrix** of integers, where each cell represents the elevation at that point, design an algorithm to compute the **maximum water volume** trapped in the matrix after raining. The water can only be trapped in valleys and cannot leak off the ed... |
def min_operations(initial, final):
if len(initial) != len(final):
return -1
from collections import Counter
if Counter(initial) != Counter(final):
return -1
n = len(initial)
if n == 0:
return 0
reversed_initial = initial[::-1]
reversed_final = final[::-1]
i = j =... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings `initialState` and `finalState`, both consisting of lowercase letters. Your task is to determine if you can transform `initialState` into `finalState` by following a specific set of operations. An operation consists of selecting any character in the current str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9587,
"level": 1,
"question": "You are given two strings `initialState` and `finalState`, both consisting of lowercase letters. Your task is to determine if you can transform `initialState` into `finalState` by following a specific set of operations. An operation consists of selecti... |
import os
def get_existing_files(paths):
return [path for path in paths if os.path.isfile(path)] | simplelr_Filter | [
{
"content": "Question:\nI'm a new Python programmer. I've got a list of strings where each string represents a path to a file. I want to write a function that takes this list of paths as an argument and returns a list of the paths that correspond to existing files.\n\nHere's a code snippet that I came up with:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9588,
"level": 1,
"question": "I'm a new Python programmer. I've got a list of strings where each string represents a path to a file. I want to write a function that takes this list of paths as an argument and returns a list of the paths that correspond to existing files.\n\nHere's ... |
import heapq
from typing import List
def find_kth_smallest(arr: List[int], k: int) -> int:
heap = arr.copy()
heapq.heapify(heap)
for _ in range(k):
result = heapq.heappop(heap)
return result | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nTom is developing a logistics application that deals with scheduling and task prioritization. To optimize the task execution order, he needs to implement a sorting system using the heap sort algorithm. Tom has access to both max-heap and min-heap sort versions, but he need... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9589,
"level": 1,
"question": "### Scenario\nTom is developing a logistics application that deals with scheduling and task prioritization. To optimize the task execution order, he needs to implement a sorting system using the heap sort algorithm. Tom has access to both max-heap and ... |
def print_reverse(lst):
for i in range(len(lst)-1, -1, -1):
print(lst[i]) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to print the elements of a list in reverse order. The function should not use any built-in reverse functions or slicing.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9590,
"level": 1,
"question": "Write a Python function to print the elements of a list in reverse order. The function should not use any built-in reverse functions or slicing.",
"split": "train"
} |
import linecache
from typing import Dict, List
def batch_get_lines(files: Dict[str, List[int]]) -> Dict[str, List[str]]:
result = {}
for filename, line_nums in files.items():
file_result = []
for num in line_nums:
if num < 1:
file_result.append("")
co... | simplelr_Docs | [
{
"content": "Question:\n**Objective**: Implement and utilize the `linecache` module to achieve efficient access to lines from a text file by implementing a function that returns lines from multiple files based on line numbers provided.\n\n#### Problem Description\n\nYou are required to implement a function tha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9591,
"level": 1,
"question": "**Objective**: Implement and utilize the `linecache` module to achieve efficient access to lines from a text file by implementing a function that returns lines from multiple files based on line numbers provided.\n\n#### Problem Description\n\nYou are r... |
import math
def softmax(numbers):
"""
Compute the softmax of a list of numbers.
The softmax function transforms a list of numbers into a probability distribution.
Parameters:
numbers (list): A list of real numbers.
Returns:
list: A list of probabilities that sum up to 1.
... | simplelr_Filter | [
{
"content": "Question:\nCould you provide a Python function to calculate the softmax of a given list of numbers? The softmax function is used in machine learning to convert a list of numbers into a probability distribution. It is often used as the activation function in the output layer of a neural network for... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9592,
"level": 1,
"question": "Could you provide a Python function to calculate the softmax of a given list of numbers? The softmax function is used in machine learning to convert a list of numbers into a probability distribution. It is often used as the activation function in the o... |
import string
def count_words_in_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
words = content.split()
# Remove punctuation and convert to lowercase
words = [word.strip(string.punctuation).lower() for word in words if word.strip... | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python script that reads a text file and counts the number of words in it? I want to make sure it handles punctuation and capitalization correctly.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9593,
"level": 1,
"question": "How can I create a Python script that reads a text file and counts the number of words in it? I want to make sure it handles punctuation and capitalization correctly.",
"split": "train"
} |
from collections import Counter
import string
def get_lexicographically_largest_string(text):
counts = Counter(text)
result = []
for c in reversed(string.ascii_lowercase):
if c in counts:
result.append(c * counts[c])
return ''.join(result) | simplelr_Leetcode | [
{
"content": "Question:\n**[Question 4]:** Given a string `text` consisting of lowercase English letters, you can perform the following operation as many times as desired: Pick any two adjacent characters in the string and swap them. Return _the lexicographically largest string_ that can be obtained by performi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9594,
"level": 1,
"question": "**[Question 4]:** Given a string `text` consisting of lowercase English letters, you can perform the following operation as many times as desired: Pick any two adjacent characters in the string and swap them. Return _the lexicographically largest strin... |
def count_buildings_with_sunlight(arr):
if not arr:
return 0
count = 1
max_height = arr[0]
for h in arr[1:]:
if h > max_height:
count += 1
max_height = h
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` representing the heights of buildings. A building with a height `h` will get sunlight if there are no taller buildings to its left. In other words, building `i` will get sunlight if for all `j < i`, `arr[j] < arr[i]`. Return the number of buildi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9595,
"level": 1,
"question": "You are given an array of integers `arr` representing the heights of buildings. A building with a height `h` will get sunlight if there are no taller buildings to its left. In other words, building `i` will get sunlight if for all `j < i`, `arr[j] < ar... |
def triangle_area(base, height):
return (base * height) / 2
area = triangle_area(10, 5)
print("The area of the triangle is:", area) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the area of a triangle, given its base and height. Then, call this function with base = 10, height = 5 and print the area.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9596,
"level": 1,
"question": "Write a python function to calculate the area of a triangle, given its base and height. Then, call this function with base = 10, height = 5 and print the area.",
"split": "train"
} |
def can_be_separated(n, diff):
return (n - diff) >= 0 and (n + diff) % 2 == 0 | simplelr_Filter | [
{
"content": "Question:\nWrite a response to the following prompt:\n\nI am working on a project where I need to determine if there is a way to separate an integer into two integers whose sum is equal to the original integer and whose difference is equal to a given difference. \n\nFor example, if I provide the i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9597,
"level": 1,
"question": "Write a response to the following prompt:\n\nI am working on a project where I need to determine if there is a way to separate an integer into two integers whose sum is equal to the original integer and whose difference is equal to a given difference. ... |
import numpy as np
def normalize_vector(vector: np.ndarray) -> np.ndarray:
norm = np.linalg.norm(vector)
return vector / norm | simplelr_Algorithm | [
{
"content": "Question:\n### Question\n\n#### Objective\nYou need to implement a function called `normalize_vector`. This function normalizes the vector such that its norm (magnitude) is `1`. This technique is often used in machine learning and data preprocessing to make sure features have a standard range.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9598,
"level": 1,
"question": "### Question\n\n#### Objective\nYou need to implement a function called `normalize_vector`. This function normalizes the vector such that its norm (magnitude) is `1`. This technique is often used in machine learning and data preprocessing to make sure ... |
def longest_subarray_with_sum(nums, target):
prefix_sum = {0: -1}
current_sum = 0
max_length = 0
start = 0
end = 0
for i, num in enumerate(nums):
current_sum += num
if (current_sum - target) in prefix_sum:
length = i - prefix_sum[current_sum - target]
... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns the longest contiguous subarray that sums to a given target integer. If multiple subarrays have the same length, return the first one found. If no such subarray exists, return an empty list.\nAnswer:\nLet's think step by step.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9599,
"level": 1,
"question": "Write a function that takes a list of integers and returns the longest contiguous subarray that sums to a given target integer. If multiple subarrays have the same length, return the first one found. If no such subarray exists, return an empty list.",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.