target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
import numpy as np
def compute_matrix_rank(matrix: np.ndarray) -> int:
# Check if all elements are integers
if matrix.dtype.kind not in ('i', 'u'):
for elem in matrix.flatten():
if not isinstance(elem, (int, np.integer)):
if not (isinstance(elem, float) and elem.is_integer()... | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Implement Matrix Rank Calculation with Integer Check\n\nGiven a square matrix of integers, your task is to write a function that computes the rank of the matrix. To ensure the correctness of input, your function should first verify that all entries of the matrix are intege... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5800,
"level": 1,
"question": "### Question: Implement Matrix Rank Calculation with Integer Check\n\nGiven a square matrix of integers, your task is to write a function that computes the rank of the matrix. To ensure the correctness of input, your function should first verify that a... |
def first_non_repeating_character(s):
if not s:
return None
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
r... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python program that takes a string and returns the first non-repeating character. If all characters are repeating or the string is empty, the program should return None. Ensure your solution is optimized for performance and can handle edge cases, such as strings with varying cap... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5801,
"level": 1,
"question": "Write a Python program that takes a string and returns the first non-repeating character. If all characters are repeating or the string is empty, the program should return None. Ensure your solution is optimized for performance and can handle edge case... |
import xml.etree.ElementTree as ET
def is_valid_xml(xml_string):
try:
ET.fromstring(xml_string)
return True
except ET.ParseError:
return False | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function to check if a given string is a valid XML document?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5802,
"level": 1,
"question": "How can I create a Python function to check if a given string is a valid XML document?",
"split": "train"
} |
from typing import List
def check_animal_grid(grid: List[str]) -> str:
# Check if the grid has exactly 10 rows
if len(grid) != 10:
return "Invalid"
# Check each row is exactly 10 characters long
for row in grid:
if len(row) != 10:
return "Invalid"
# Count the t... | simplelr_Taco | [
{
"content": "Question:\nThe zoo has recently introduced ten new animals and decided to place them in a new 10 × 10 grid enclosure having exactly 10 units along both width and height. The plan is to place each animal in an unoccupied cell of the grid. You are tasked to write a program that will verify if an arr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5803,
"level": 1,
"question": "The zoo has recently introduced ten new animals and decided to place them in a new 10 × 10 grid enclosure having exactly 10 units along both width and height. The plan is to place each animal in an unoccupied cell of the grid. You are tasked to write a... |
def two_sum(nums, target):
seen = {}
for index, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], index]
seen[num] = index
return None | simplelr_Filter | [
{
"content": "Question:\nGiven an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target.\n\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n\nYou can return the answer in any order.\n\nExam... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5804,
"level": 1,
"question": "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target.\n\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n\nYou can retu... |
from typing import List
def highest_binary_value(binaries: List[str]) -> str:
max_val = -1
max_str = "0"
for binary in binaries:
current = int(binary, 2)
if current > max_val:
max_val = current
max_str = binary
return max_str | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given a list of strings where each string represents a binary number. The task is to find the binary number in the list that has the highest decimal value and return it in binary format without any leading zeros.\n\n### Function Signature\n```python\ndef... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5805,
"level": 1,
"question": "### Problem Statement\n\nYou are given a list of strings where each string represents a binary number. The task is to find the binary number in the list that has the highest decimal value and return it in binary format without any leading zeros.\n\n###... |
from collections import Counter
def count_characters(words, chars):
chars_counter = Counter(chars)
total = 0
for word in words:
word_counter = Counter(word)
valid = True
for char, count in word_counter.items():
if chars_counter.get(char, 0) < count:
valid... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of **0-indexed** strings `words` and a string `chars`. Each string in `words` consists of lowercase English letters, and `chars` is a string of distinct lowercase English letters. You need to form new strings from the strings in `words` by using the characters from ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5806,
"level": 1,
"question": "You are given a list of **0-indexed** strings `words` and a string `chars`. Each string in `words` consists of lowercase English letters, and `chars` is a string of distinct lowercase English letters. You need to form new strings from the strings in `w... |
def find_first_duplicate(arr):
seen = set()
for num in arr:
if num in seen:
return num
seen.add(num)
return None | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to identify whether all the elements of a list are unique. If not, return the first duplicate element found. If all elements are unique, return None.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5807,
"level": 1,
"question": "Write a python function to identify whether all the elements of a list are unique. If not, return the first duplicate element found. If all elements are unique, return None.",
"split": "train"
} |
def countPalindromicPermutations(w):
from math import factorial
# Step 1: Compute frequency of each character
freq = {}
for c in w:
if c in freq:
freq[c] += 1
else:
freq[c] = 1
n = len(w)
even_length = (n % 2 == 0)
# Check for palindrome conditions
... | simplelr_Taco | [
{
"content": "Question:\nGiven a word w, output the count of words that can be formed by re-arranging its letters such that they are palindrome. A palindrome is a word that reads the same backward as forward.\n\nExample 1:\nInput:\nw = \"aabb\"\nOutput:\n2\nExplanation:\nThere are 2 palindromic permutations of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5808,
"level": 1,
"question": "Given a word w, output the count of words that can be formed by re-arranging its letters such that they are palindrome. A palindrome is a word that reads the same backward as forward.\n\nExample 1:\nInput:\nw = \"aabb\"\nOutput:\n2\nExplanation:\nThere... |
def fibonacci(n: int) -> int:
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for i in range(2, n + 1):
current = a + b
a, b = b, current
return b | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes an integer `n` as input and returns the `n`-th number in the Fibonacci sequence using iterative approach. The Fibonacci sequence is defined as follows:\n- The first number in the sequence is 0,\n- The second number in the sequence is 1,\n- Each subsequ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5809,
"level": 1,
"question": "Write a Python function that takes an integer `n` as input and returns the `n`-th number in the Fibonacci sequence using iterative approach. The Fibonacci sequence is defined as follows:\n- The first number in the sequence is 0,\n- The second number in... |
import numpy as np
from numpy.lib.stride_tricks import as_strided
def sliding_window_1d_to_2d(arr, window_size, step_size):
"""
Convert a 1D numpy array into a 2D array with sliding windows.
Parameters:
arr (numpy.ndarray): The input 1D array.
window_size (int): Size of each sliding window.
st... | simplelr_Filter | [
{
"content": "Question:\nDesign a function in Python that converts a 1D numpy array into a 2D numpy array where each row represents a sliding window of the 1D array, with the window size and step size as inputs. The function should return the 2D array without any padding, and stop before the sliding window fall... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5810,
"level": 1,
"question": "Design a function in Python that converts a 1D numpy array into a 2D numpy array where each row represents a sliding window of the 1D array, with the window size and step size as inputs. The function should return the 2D array without any padding, and ... |
def longest_substring_without_repeating_characters(s: str) -> int:
max_len = 0
left = 0
last_occurrence = {}
for right in range(len(s)):
char = s[right]
if char in last_occurrence and last_occurrence[char] >= left:
left = last_occurrence[char] + 1
last_occurrence[char... | simplelr_Apps | [
{
"content": "Question:\nImplement a function `longest_substring_without_repeating_characters(s: str) -> int` that takes a string `s` and returns the length of the longest substring without repeating characters.\n\nIf the input string is empty, return `0`.\n\n# Examples:\n\nInput 1 \n\n \"abcabcbb\"\n\nOutpu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5811,
"level": 1,
"question": "Implement a function `longest_substring_without_repeating_characters(s: str) -> int` that takes a string `s` and returns the length of the longest substring without repeating characters.\n\nIf the input string is empty, return `0`.\n\n# Examples:\n\nIn... |
from typing import List
def find_target_index(array: List[int], target: int) -> int:
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == target:
return mid
elif array[mid] < target:
low = mid + 1
else:
... | simplelr_Data_Structure | [
{
"content": "Question:\n**Title**: Efficient Element Lookup using Binary Search in a Sorted Array\n\n**Problem Statement**:\nYou are given a sorted array of integers and a target value. Write an efficient search algorithm using Binary Search to find the target value in the array. If the target value exists in ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5812,
"level": 1,
"question": "**Title**: Efficient Element Lookup using Binary Search in a Sorted Array\n\n**Problem Statement**:\nYou are given a sorted array of integers and a target value. Write an efficient search algorithm using Binary Search to find the target value in the ar... |
def bubble_sort(nums):
# Get the length of the list
n = len(nums)
for i in range(n):
# Create a flag that will allow the function to terminate early if there's nothing left to sort
swapped = False
# Start looking at each element, starting from the beginning
for ... | simplelr_Filter | [
{
"content": "Question:\nWrite a detailed guide on sorting a list of numbers using the bubble sort technique in Python. Include code snippets and explanations for each step. Additionally, discuss the time complexity of the algorithm and suggest improvements for efficiency.\nAnswer:\nLet's think step by step.\n"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5813,
"level": 1,
"question": "Write a detailed guide on sorting a list of numbers using the bubble sort technique in Python. Include code snippets and explanations for each step. Additionally, discuss the time complexity of the algorithm and suggest improvements for efficiency.",
... |
def min_deletions_to_palindrome(s):
n = len(s)
if n == 0:
return 0
dp = [[0] * n for _ in range(n)]
# Fill the table for substrings of length 1
for i in range(n):
dp[i][i] = 1
# Fill the table for substrings of length 2
for i in range(n - 1):
if s[i] == s[i ... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string S of length N (2 <= N <= 100), consisting of lowercase alphabets from a to z. The function should return the minimum number of deletions required to ensure that the remaining string is a palindrome. A palindrome is a string that reads the same forwa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5814,
"level": 1,
"question": "Create a function that takes a string S of length N (2 <= N <= 100), consisting of lowercase alphabets from a to z. The function should return the minimum number of deletions required to ensure that the remaining string is a palindrome. A palindrome is... |
def reverse_string(s):
if not s:
return ""
return s[::-1] | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse a string. The function should take a single string as an input and return the reversed version of that string. If the input string is empty or null, the function should return an empty string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5815,
"level": 1,
"question": "Write a function to reverse a string. The function should take a single string as an input and return the reversed version of that string. If the input string is empty or null, the function should return an empty string.",
"split": "train"
} |
def extract_and_sort_unique_numbers(numbers: list[int]) -> list[int]:
unique_numbers = set(numbers)
sorted_numbers = sorted(unique_numbers)
return sorted_numbers | simplelr_Algorithm | [
{
"content": "Question:\n## Problem Statement\n\n### Context\nAs part of a data processing pipeline, you need to perform some transformations and filtering to prepare the data for further analysis. One of the tasks is to extract all unique numbers from a list and sort them in ascending order. This is a common p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5816,
"level": 1,
"question": "## Problem Statement\n\n### Context\nAs part of a data processing pipeline, you need to perform some transformations and filtering to prepare the data for further analysis. One of the tasks is to extract all unique numbers from a list and sort them in ... |
def build_char_count(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to build a dictionary where the keys are the characters in a string and the values are the counts of their occurrences in the string. How should I approach this problem?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5817,
"level": 1,
"question": "Write a function to build a dictionary where the keys are the characters in a string and the values are the counts of their occurrences in the string. How should I approach this problem?",
"split": "train"
} |
import wave
import struct
def modify_wav_file(input_filename: str, output_filename: str) -> None:
with wave.open(input_filename, 'rb') as wav:
nchannels, sampwidth, framerate, nframes, comptype, compname = wav.getparams()
if sampwidth not in (1, 2):
raise wave.Error("Sample wid... | simplelr_Docs | [
{
"content": "Question:\nYou are given a WAV file named `input.wav`. Your task is to write a Python function that reads the file and creates a new WAV file named `output.wav` with some modifications. The new WAV file should meet the following requirements:\n\n1. **Change the Sample Width**: If the input sample ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5818,
"level": 1,
"question": "You are given a WAV file named `input.wav`. Your task is to write a Python function that reads the file and creates a new WAV file named `output.wav` with some modifications. The new WAV file should meet the following requirements:\n\n1. **Change the S... |
from collections import defaultdict
def group_anagrams(words):
anagrams = defaultdict(list)
for word in words:
key = ''.join(sorted(word))
anagrams[key].append(word)
groups = []
for group in anagrams.values():
sorted_group = sorted(group)
groups.append(sorted_group)
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of strings `words`, you need to group the anagrams together. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. You should return a list of lists, where each list contains al... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5819,
"level": 1,
"question": "Given a list of strings `words`, you need to group the anagrams together. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. You should return a list of... |
from collections import defaultdict
def mostFrequentChar(S):
freq = defaultdict(int)
for char in S:
freq[char] += 1
return max(freq.values()) if freq else 0
| simplelr_Taco | [
{
"content": "Question:\nGiven a string S consisting of lowercase and uppercase alphabet characters. Your task is to calculate the frequency of the most occurring character in the string. Note that the string can contain both uppercase and lowercase letters, and they will be considered distinct characters.\n\nE... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5820,
"level": 1,
"question": "Given a string S consisting of lowercase and uppercase alphabet characters. Your task is to calculate the frequency of the most occurring character in the string. Note that the string can contain both uppercase and lowercase letters, and they will be c... |
def enhanced_reverse(s: str) -> str:
reversed_list = []
for i in range(len(s)-1, -1, -1):
reversed_list.append(s[i])
return ''.join(reversed_list) | simplelr_Data_Structure | [
{
"content": "Question:\nIn the era of digital communication, ensuring data integrity by reversing strings is a common operation. You are tasked with implementing a string reversal function that must adhere to a specific format and constraints.\n\n### Requirements\nImplement a function `enhanced_reverse(s: str)... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5821,
"level": 1,
"question": "In the era of digital communication, ensuring data integrity by reversing strings is a common operation. You are tasked with implementing a string reversal function that must adhere to a specific format and constraints.\n\n### Requirements\nImplement a... |
import os
def configure_pytorch_cuda_environment():
"""
Configures the PyTorch and CUDA environment by setting various environment variables.
This function performs the following configurations:
1. Limits CUDA to use only the first two GPUs.
2. Disables memory caching for CUDA.
3. Sets cus... | simplelr_Docs | [
{
"content": "Question:\n### PyTorch and CUDA Environment Configuration\n\nYou are given a machine with multiple GPUs available, and you are tasked with configuring the PyTorch environment to handle various scenarios. Specifically, you need to:\n\n1. Ensure that the code uses only the first two GPUs available.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5822,
"level": 1,
"question": "### PyTorch and CUDA Environment Configuration\n\nYou are given a machine with multiple GPUs available, and you are tasked with configuring the PyTorch environment to handle various scenarios. Specifically, you need to:\n\n1. Ensure that the code uses ... |
def find_kth_largest(nums, k):
n = len(nums)
if n == 0:
raise ValueError("Array is empty")
if k < 1 or k > n:
raise ValueError("k is out of range")
sorted_nums = sorted(nums, reverse=True)
return sorted_nums[k-1] | simplelr_Filter | [
{
"content": "Question:\nImplement a function `find_kth_largest` that accepts an array of integers `nums` and an integer `k`, and returns the k-th largest element in the array. The function should not modify the original array and should have a time complexity of O(n log n) or better when `k` is not extremely s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5823,
"level": 1,
"question": "Implement a function `find_kth_largest` that accepts an array of integers `nums` and an integer `k`, and returns the k-th largest element in the array. The function should not modify the original array and should have a time complexity of O(n log n) or... |
def minStepsToAnagram(s1, s2):
if len(s1) != len(s2):
return -1 # Impossible to make anagrams if lengths differ
count1 = [0] * 26
count2 = [0] * 26
for c in s1:
count1[ord(c) - ord('a')] += 1
for c in s2:
count2[ord(c) - ord('a')] += 1
total = 0
for i ... | simplelr_Taco | [
{
"content": "Question:\nGiven two strings s1 and s2, find the minimum number of steps required to make s1 and s2 anagrams of each other. In each step, you can replace any character in s1 with any other character.\n\nExample 1:\nInput:\ns1 = \"anagram\"\ns2 = \"mangaar\"\nOutput: 0\nExplanation: Both strings ar... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5824,
"level": 1,
"question": "Given two strings s1 and s2, find the minimum number of steps required to make s1 and s2 anagrams of each other. In each step, you can replace any character in s1 with any other character.\n\nExample 1:\nInput:\ns1 = \"anagram\"\ns2 = \"mangaar\"\nOutp... |
def process_number(num):
if num % 2 != 0:
return num * 3
else:
return num | simplelr_Filter | [
{
"content": "Question:\nWrite a function that takes a number as an argument. If the number is odd, return the number multiplied by 3. If it's even, return the original number. To make the task more challenging, there is a piece of erroneous code provided below. Find the error, fix it, and then write your own c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5825,
"level": 1,
"question": "Write a function that takes a number as an argument. If the number is odd, return the number multiplied by 3. If it's even, return the original number. To make the task more challenging, there is a piece of erroneous code provided below. Find the error... |
def has_alternating_bits(n: int) -> bool:
x = n ^ (n >> 1)
return (x & (x + 1)) == 0 | simplelr_Data_Structure | [
{
"content": "Question:\nAs a software engineer, you are often required to work with binary representations of numbers for various optimizations and checks. One common problem is determining whether a given number has an alternating bit pattern, i.e., two adjacent bits must always have different values.\n\n####... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5826,
"level": 1,
"question": "As a software engineer, you are often required to work with binary representations of numbers for various optimizations and checks. One common problem is determining whether a given number has an alternating bit pattern, i.e., two adjacent bits must al... |
def remove_vowels(str):
vowels = 'aeiouAEIOU'
return ''.join([c for c in str if c not in vowels]) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a string `str` as input and returns the string with all the vowels removed.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5827,
"level": 1,
"question": "Create a function that takes a string `str` as input and returns the string with all the vowels removed.",
"split": "train"
} |
def min_path_sum(matrix):
m = len(matrix)
if m == 0:
return 0
n = len(matrix[0])
if n == 0:
return 0
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
continue
elif i == 0:
matrix[i][j] += matrix[i][j-1]
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a 2D integer array `matrix` representing a `m x n` grid where `matrix[i][j]` is the number of obstacles in the cell. You need to find a path from the top-left corner `(0, 0)` to the bottom-right corner `(m-1, n-1)` such that the sum of the obstacles encountered along the p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5828,
"level": 1,
"question": "You are given a 2D integer array `matrix` representing a `m x n` grid where `matrix[i][j]` is the number of obstacles in the cell. You need to find a path from the top-left corner `(0, 0)` to the bottom-right corner `(m-1, n-1)` such that the sum of th... |
import heapq
def shortest_paths(num_nodes, connections):
if num_nodes == 0:
return []
# Build adjacency list
adj = [[] for _ in range(num_nodes)]
for u, v, w in connections:
adj[u].append((v, w))
adj[v].append((u, w))
# Initialize distances
distances = [-1] * n... | simplelr_Taco | [
{
"content": "Question:\n## Your task\nAlice is a network administrator and she manages a computer network represented as an undirected graph. Each node in the graph represents a computer and each edge represents a direct connection between two computers. Due to security policies, she needs to ensure that sensi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5829,
"level": 1,
"question": "## Your task\nAlice is a network administrator and she manages a computer network represented as an undirected graph. Each node in the graph represents a computer and each edge represents a direct connection between two computers. Due to security polic... |
import math
def degrees_to_radians(degrees):
"""
Converts an angle from degrees to radians.
Args:
degrees (float): The angle in degrees.
Returns:
float: The angle in radians.
"""
return degrees * math.pi / 180.0
# Example usage:
print(degrees_to_radians(90.0)) # Outp... | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that converts angles from degrees to radians?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5830,
"level": 1,
"question": "How can I create a Python function that converts angles from degrees to radians?",
"split": "train"
} |
import heapq
def k_sorted_array_sort(arr, k):
n = len(arr)
if n == 0:
return []
heap = []
# Initialize the heap with the first min(k+1, n) elements
for i in range(min(k + 1, n)):
heapq.heappush(heap, arr[i])
result = []
current_index = min(k + 1, n)
while ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a `k`-sorted array `arr` where every element is at most `k` positions away from its target position in the sorted order. Write a function to sort this array in ascending order in an efficient manner. Return the sorted array.\n\nFor example, given `arr = [6, 5, 3, 2, 8, 10,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5831,
"level": 1,
"question": "You are given a `k`-sorted array `arr` where every element is at most `k` positions away from its target position in the sorted order. Write a function to sort this array in ascending order in an efficient manner. Return the sorted array.\n\nFor exampl... |
def knapsack(values, weights, capacity):
n = len(values)
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(1, capacity + 1):
weight = weights[i-1]
value = values[i-1]
if weight > w:
dp[i][w]... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to implement the Knapsack problem using dynamic programming in Python. The function should accept a list of item values, a list of item weights, and the maximum weight capacity of the knapsack as parameters. The function should return the maximum value that can be obtai... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5832,
"level": 1,
"question": "Write a function to implement the Knapsack problem using dynamic programming in Python. The function should accept a list of item values, a list of item weights, and the maximum weight capacity of the knapsack as parameters. The function should return ... |
def length_of_longest_substring(s):
char_index = {}
left = 0
max_len = 0
for right in range(len(s)):
char = s[right]
if char in char_index and char_index[char] >= left:
left = char_index[char] + 1
char_index[char] = right
current_len = right - left + 1
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the length of the longest substring without repeating characters in a given string `s`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5833,
"level": 1,
"question": "Write a python function to find the length of the longest substring without repeating characters in a given string `s`.",
"split": "train"
} |
from typing import List
def ternary_search(left: int, right: int, key: int, arr: List[int]) -> int:
if left > right:
return -1
n = len(arr)
if n == 0:
return -1
# Ensure the right index does not exceed the array bounds
right = min(right, n - 1)
left = max(left, 0)
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Ternary Search Implementation\n\nYou are tasked with implementing the `ternary_search` function, which searches for a target value within a sorted array. Unlike binary search, ternary search splits the array into three segments. \n\n**Function Signature**:\n```python\ndef ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5834,
"level": 1,
"question": "### Question: Ternary Search Implementation\n\nYou are tasked with implementing the `ternary_search` function, which searches for a target value within a sorted array. Unlike binary search, ternary search splits the array into three segments. \n\n**Fun... |
import ipaddress
from typing import List, Tuple, Dict
def validate_and_report(ip_network_pairs: List[Tuple[str, str]]) -> Dict:
valid_pairs = []
invalid_entries = []
network_sizes = {}
added_networks = set()
for ip_str, network_str in ip_network_pairs:
# Process IP address
try:
... | simplelr_Docs | [
{
"content": "Question:\nYou have been assigned a task to manage and validate network configurations for a diverse set of devices. Using the `ipaddress` module, write a function that takes a list of IP address and network pairs, validates them, and returns a detailed report. The function should:\n\n1. Validate ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5835,
"level": 1,
"question": "You have been assigned a task to manage and validate network configurations for a diverse set of devices. Using the `ipaddress` module, write a function that takes a list of IP address and network pairs, validates them, and returns a detailed report. T... |
def my_map(func, lst):
result = []
for item in lst:
result.append(func(item))
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that mimics the behavior of the built-in `map()` function in Python. The `my_map()` function should take a function and a list as parameters and return a new list with the function applied to each element of the input list.\nAnswer:\nLet's think step by step.\n",
"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5836,
"level": 1,
"question": "Create a function that mimics the behavior of the built-in `map()` function in Python. The `my_map()` function should take a function and a list as parameters and return a new list with the function applied to each element of the input list.",
"split... |
def sum_squares_of_evens(lst):
return sum(x**2 for x in lst if x % 2 == 0)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `sum_squares_of_evens` that:\n\n* Accepts a list of integers, and\n* Returns the sum of squares of all even integers in the list.\n\nIf the list is empty or contains no even integers, the function should return 0.\n\n```python\n# Example Usage\nsum_squares_of_evens([1, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5837,
"level": 1,
"question": "Write a function `sum_squares_of_evens` that:\n\n* Accepts a list of integers, and\n* Returns the sum of squares of all even integers in the list.\n\nIf the list is empty or contains no even integers, the function should return 0.\n\n```python\n# Examp... |
import pandas as pd
import matplotlib.pyplot as plt
def process_sales_data(file_path: str) -> pd.DataFrame:
# Read the CSV file into a DataFrame
df = pd.read_csv(file_path)
# Fill missing 'Total' values with Quantity multiplied by Price
df['Total'] = df['Total'].fillna(df['Quantity'] * df['Price']... | simplelr_Docs | [
{
"content": "Question:\n### Pandas Coding Assessment\n\n#### Objective\n\nWrite a function that processes a CSV file containing sales data and generates a few key insights. The function should demonstrate your understanding of various pandas functionalities including data manipulation, handling missing values,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5838,
"level": 1,
"question": "### Pandas Coding Assessment\n\n#### Objective\n\nWrite a function that processes a CSV file containing sales data and generates a few key insights. The function should demonstrate your understanding of various pandas functionalities including data man... |
from collections import Counter
def task_scheduler(tasks: str) -> bool:
counts = Counter(tasks)
max_count = max(counts.values(), default=0)
return len(tasks) >= 2 * max_count - 1 | simplelr_Algorithm | [
{
"content": "Question:\n**Scenario**: You are given a string where each character represents a type of task. Some tasks are repeatable, and some tasks must be completed only once. The tasks must be completed in one go without breaks. However, if a task appears more than once in the given string, you must leave... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5839,
"level": 1,
"question": "**Scenario**: You are given a string where each character represents a type of task. Some tasks are repeatable, and some tasks must be completed only once. The tasks must be completed in one go without breaks. However, if a task appears more than once ... |
def count_increasing_temperatures(temps):
count = 0
for i in range(1, len(temps)):
if temps[i] > temps[i-1]:
count += 1
return count | simplelr_Evol | [
{
"content": "Question:\nYou are given an array of integers representing the daily temperatures in a week. Implement a function `count_increasing_temperatures` that returns the number of days where the temperature was higher than the previous day's temperature. For example, given the array `[71, 73, 75, 74, 72,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5840,
"level": 1,
"question": "You are given an array of integers representing the daily temperatures in a week. Implement a function `count_increasing_temperatures` that returns the number of days where the temperature was higher than the previous day's temperature. For example, gi... |
def crush_string(s):
if not s:
return s
stack = []
for char in s:
if not stack or char != stack[-1]:
stack.append(char)
return ''.join(stack) | simplelr_Filter | [
{
"content": "Question:\n### Crush a String\n#### Problem Description\nGiven a string with two types of elements: alphabet characters and \"**\" (asterisks), crush those consecutive sequences of the same non-asterisk character and replace them with a single character using a stack.\n\n#### Sample Input\n```\naa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5841,
"level": 1,
"question": "### Crush a String\n#### Problem Description\nGiven a string with two types of elements: alphabet characters and \"**\" (asterisks), crush those consecutive sequences of the same non-asterisk character and replace them with a single character using a s... |
import math
def findPrimes(n):
if n <= 2:
return []
sieve = [True] * n
sieve[0] = sieve[1] = False
for i in range(2, int(math.sqrt(n)) + 1):
if sieve[i]:
sieve[i*i : n : i] = [False] * len(sieve[i*i : n : i])
primes = [i for i, is_prime in enumerate(sieve) if is_prime]
... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes an integer `n` as input and returns a list of all prime numbers less than `n`. If `n` is less than or equal to 2, the function should return an empty list.\n\nExamples:\n\n`findPrimes(10)` returns `[2, 3, 5, 7]`\n\n`findPrimes(20)` returns `[2, 3, 5, 7, 11, 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5842,
"level": 1,
"question": "Write a function that takes an integer `n` as input and returns a list of all prime numbers less than `n`. If `n` is less than or equal to 2, the function should return an empty list.\n\nExamples:\n\n`findPrimes(10)` returns `[2, 3, 5, 7]`\n\n`findPrim... |
def longest_substring_two_distinct(S):
freq = {}
left = 0
max_len = 0
for right in range(len(S)):
char = S[right]
if char in freq:
freq[char] += 1
else:
freq[char] = 1
# If there are more than two distinct characters, move left
whi... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a string S consisting only of characters 'a', 'b', and 'c'. Your task is to find and return the length of the longest substring that contains at most two distinct characters.\n\nThe input string S has a length of at most 100 characters.\n\nWrite a function `longest_substri... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5843,
"level": 1,
"question": "You are given a string S consisting only of characters 'a', 'b', and 'c'. Your task is to find and return the length of the longest substring that contains at most two distinct characters.\n\nThe input string S has a length of at most 100 characters.\n... |
def remove_duplicates(input_list):
seen = set()
result = []
for item in input_list:
if item not in seen:
seen.add(item)
result.append(item)
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to remove duplicates from a list of integers, maintaining the original order. The function should return a new list with all duplicates removed, preserving the order of elements as they first appeared in the input list.\nAnswer:\nLet's think step by step.\n",
"role"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5844,
"level": 1,
"question": "Write a function to remove duplicates from a list of integers, maintaining the original order. The function should return a new list with all duplicates removed, preserving the order of elements as they first appeared in the input list.",
"split": "t... |
def merge_dictionaries(dict1, dict2):
merged = {}
for key in dict1:
merged[key] = dict1[key]
for key in dict2:
if key not in merged:
merged[key] = dict2[key]
else:
if isinstance(merged[key], dict) and isinstance(dict2[key], dict):
merged[key] =... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a function that merges two dictionaries recursively. The function should take two dictionaries as input and merge them into one dictionary. If there are overlapping keys and both keys point to dictionaries, it should recursively merge them. Otherwise, the value... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5845,
"level": 1,
"question": "You are required to write a function that merges two dictionaries recursively. The function should take two dictionaries as input and merge them into one dictionary. If there are overlapping keys and both keys point to dictionaries, it should recursive... |
def count_overlapping_occurrences(text, pattern):
if not pattern or len(pattern) > len(text):
return 0
count = 0
pattern_length = len(pattern)
text_length = len(text)
for i in range(text_length - pattern_length + 1):
if text[i:i + pattern_length] == pattern:
count += 1
... | simplelr_Apps | [
{
"content": "Question:\n# Task\n\nSamantha is working on a text-parsing project and she needs to analyze a specific pattern within a given text string. She requests your help in writing a program to identify and count overlapping substrings within the text.\n\nA substring is defined as overlapping if it occurs... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5846,
"level": 1,
"question": "# Task\n\nSamantha is working on a text-parsing project and she needs to analyze a specific pattern within a given text string. She requests your help in writing a program to identify and count overlapping substrings within the text.\n\nA substring is ... |
def topThreeRatedRestaurants(reviews):
restaurant_ratings = {}
for review in reviews:
name = review['restaurant']
rating = review['rating']
if name in restaurant_ratings:
restaurant_ratings[name][0] += rating
restaurant_ratings[name][1] += 1
else:
... | simplelr_Apps | [
{
"content": "Question:\nYou have been appointed as a software engineer for a popular food delivery application. The application allows customers to rate restaurants they order from. Each restaurant can receive multiple reviews from different customers. The application developers want to introduce a new feature... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5847,
"level": 1,
"question": "You have been appointed as a software engineer for a popular food delivery application. The application allows customers to rate restaurants they order from. Each restaurant can receive multiple reviews from different customers. The application develop... |
def filter_dict_list(dict_list, key, value):
"""
Filters a list of dictionaries based on a specific key and value.
Args:
dict_list (list): A list of dictionaries.
key (str): The key to filter by.
value: The value to match.
Returns:
list: A list of dictionaries w... | simplelr_Filter | [
{
"content": "Question:\nDesign a Python program to filter a list of dictionaries based on a specific key and value. For example, if you have a list of dictionaries where each dictionary represents a person with keys like 'name', 'age', and 'city', the program should be able to filter this list to return only t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5848,
"level": 1,
"question": "Design a Python program to filter a list of dictionaries based on a specific key and value. For example, if you have a list of dictionaries where each dictionary represents a person with keys like 'name', 'age', and 'city', the program should be able t... |
def minConferenceRooms(intervals):
events = []
for start, end in intervals:
events.append((start, 1)) # 1 represents the start of a meeting
events.append((end, 0)) # 0 represents the end of a meeting
events.sort() # Sorts by time, and for same times, ends come before starts
current_... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `n` intervals where each interval represents booking requests. Each interval consists of a start and end time in the form of `[start_i, end_i]`. You need to determine the minimum number of conference rooms required to hold all the given booking requests. \n\nA bo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5849,
"level": 1,
"question": "You are given a list of `n` intervals where each interval represents booking requests. Each interval consists of a start and end time in the form of `[start_i, end_i]`. You need to determine the minimum number of conference rooms required to hold all t... |
def max_identical_starting_substring_length(s1, s2):
max_len = 0
min_len = min(len(s1), len(s2))
for i in range(min_len):
if s1[i] == s2[i]:
max_len += 1
else:
break
return max_len | simplelr_Filter | [
{
"content": "Question:\nGiven two string variables, write a function to find the maximum length of the identical substring starting from the first character that appears in both strings.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5850,
"level": 1,
"question": "Given two string variables, write a function to find the maximum length of the identical substring starting from the first character that appears in both strings.",
"split": "train"
} |
from typing import List
from collections import Counter
def dominant_difficulty(problems: List[int]) -> int:
counts = Counter(problems)
max_count = max(counts.values())
max_difficulties = [d for d, cnt in counts.items() if cnt == max_count]
return min(max_difficulties) | simplelr_Codeforces | [
{
"content": "Question:\nA group of friends decided to conduct a programming challenge. They each created a number of problems and had fun solving them. However, they want to standardize the scores assigned to their problems based on difficulty.\n\nEach problem is assigned a difficulty level which is represente... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5851,
"level": 1,
"question": "A group of friends decided to conduct a programming challenge. They each created a number of problems and had fun solving them. However, they want to standardize the scores assigned to their problems based on difficulty.\n\nEach problem is assigned a d... |
def process_orders(orders, inventory):
# Create a dictionary from the inventory for quick look-up
inventory_dict = {p['product_id']: p['quantity_in_stock'] for p in inventory}
# Process each order
for order in orders:
if order['status'] == 'pending':
product_id = order['product_... | simplelr_Package | [
{
"content": "Question:\n### Database Record Processing\n\nIn an e-commerce application, orders are stored in a database and processed periodically. Each order has an associated status that indicates its state in the order processing workflow. You're tasked with creating a function that updates the order status... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5852,
"level": 1,
"question": "### Database Record Processing\n\nIn an e-commerce application, orders are stored in a database and processed periodically. Each order has an associated status that indicates its state in the order processing workflow. You're tasked with creating a fun... |
def count_primes(n):
if n <= 2:
return 0
sieve = [True] * n
sieve[0] = sieve[1] = False
for i in range(2, int(n ** 0.5) + 1):
if sieve[i]:
for j in range(i * i, n, i):
sieve[j] = False
return sum(sieve[2:]) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the number of prime numbers less than a non-negative integer n using the Sieve of Eratosthenes algorithm. The function should be efficient and handle large inputs.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5853,
"level": 1,
"question": "Write a function to calculate the number of prime numbers less than a non-negative integer n using the Sieve of Eratosthenes algorithm. The function should be efficient and handle large inputs.",
"split": "train"
} |
from collections import Counter
def word_count(words):
# Count each word case-insensitively
counts = Counter(word.lower() for word in words)
# Sort the keys in reverse alphabetical order
sorted_words = sorted(counts.keys(), reverse=True)
# Create the result dictionary with sorted keys
result = ... | simplelr_Evol | [
{
"content": "Question:\nCreate a function that takes in a list of words and returns a dictionary. Each unique word in the list should be a key in the dictionary, and the value should be the number of times that word appears in the list in reverse alphabetical order. Implement the function such that it efficien... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5854,
"level": 1,
"question": "Create a function that takes in a list of words and returns a dictionary. Each unique word in the list should be a key in the dictionary, and the value should be the number of times that word appears in the list in reverse alphabetical order. Implement... |
from typing import List, Tuple
def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if not intervals:
return []
# Sort intervals based on the start time
sorted_intervals = sorted(intervals, key=lambda x: x[0])
# Initialize the merged list with the first inte... | simplelr_Leetcode | [
{
"content": "Question:\n: A company needs to ensure that its team of engineers logs their working hours correctly. Each engineer logs their working hours as a list of intervals where each interval is represented as a tuple `(start, end)`. The company needs a function that, given these intervals, merges any ove... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5855,
"level": 1,
"question": ": A company needs to ensure that its team of engineers logs their working hours correctly. Each engineer logs their working hours as a list of intervals where each interval is represented as a tuple `(start, end)`. The company needs a function that, gi... |
def find_substring(main_string, sub_string, start=0):
"""
Finds the starting index of a substring within a main string.
Args:
main_string (str): The main string to search in.
sub_string (str): The substring to search for.
start (int, optional): The starting index to begin the se... | simplelr_Filter | [
{
"content": "Question:\nHello, I'm trying to find the index of a substring in a given string using Python. Can you assist me with a function that would accomplish this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5856,
"level": 1,
"question": "Hello, I'm trying to find the index of a substring in a given string using Python. Can you assist me with a function that would accomplish this?",
"split": "train"
} |
import math
def distance(point1, point2):
x1, y1 = point1
x2, y2 = point2
dx = x2 - x1
dy = y2 - y1
sum_of_squares = dx ** 2 + dy ** 2
return math.sqrt(sum_of_squares) | simplelr_Filter | [
{
"content": "Question:\n### Create a function `distance` that takes two arguments: `point1` and `point2`. Both `point1` and `point2` are tuples of two integers each, representing the x and y coordinates of a point. The function should return the Euclidean distance between the two points.\nAnswer:\nLet's think ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5857,
"level": 1,
"question": "### Create a function `distance` that takes two arguments: `point1` and `point2`. Both `point1` and `point2` are tuples of two integers each, representing the x and y coordinates of a point. The function should return the Euclidean distance between the... |
def create_chess_board():
board = {}
for i in range(8):
for j in range(8):
square = (i, j)
if i == 0:
if j in [0, 7]:
piece = 'rook'
elif j in [1, 6]:
piece = 'knight'
elif j in [2, 5]:
... | simplelr_Filter | [
{
"content": "Question:\nHere is the problem: \nWe will create a function called create_chess_board that takes no input arguments and returns a dictionary representing a chess board. \nThe keys in the chess board dictionary should be tuples representing the coordinates of the squares on the board. \nThe value... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5858,
"level": 1,
"question": "Here is the problem: \nWe will create a function called create_chess_board that takes no input arguments and returns a dictionary representing a chess board. \nThe keys in the chess board dictionary should be tuples representing the coordinates of the... |
import torch
import torch.distributions as dist
def gaussian_bernoulli_model(data: torch.Tensor, mu: float, sigma: float, p: float) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Models the data distribution using a mixture of Gaussian and Bernoulli distributions,
performs sampling, and computes l... | simplelr_Docs | [
{
"content": "Question:\n**Question:**\n\nYou are provided with a data distribution consisting of two components: a Gaussian (Normal) distribution and a Bernoulli distribution. Your task is to implement a function that models this data using PyTorch's `torch.distributions` package and performs specific statisti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5859,
"level": 1,
"question": "**Question:**\n\nYou are provided with a data distribution consisting of two components: a Gaussian (Normal) distribution and a Bernoulli distribution. Your task is to implement a function that models this data using PyTorch's `torch.distributions` pac... |
def fewest_coins(coins: list, amount: int) -> int:
dp = [float('inf')] * (amount + 1)
dp[0] = 0 # Base case: 0 coins needed to make 0 amount
for coin in coins:
for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] != float('... | simplelr_Algorithm | [
{
"content": "Question:\n### Task\n\nYou are required to write a function `fewest_coins(coins: list, amount: int) -> int` that determines the minimum number of coins needed to make up a given amount using coins of specified denominations.\n\n### Input\n- A list of positive integers `coins` representing the avai... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5860,
"level": 1,
"question": "### Task\n\nYou are required to write a function `fewest_coins(coins: list, amount: int) -> int` that determines the minimum number of coins needed to make up a given amount using coins of specified denominations.\n\n### Input\n- A list of positive int... |
def is_strict_palindrome(s):
s_clean = ""
for char in s:
if char.isalnum():
s_clean += char.lower()
return s_clean == s_clean[::-1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that checks if a given string is a valid strict palindrome. A strict palindrome is one where the string reads the same forwards and backwards, disregarding any non-alphanumeric characters and ignoring cases.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5861,
"level": 1,
"question": "Create a function that checks if a given string is a valid strict palindrome. A strict palindrome is one where the string reads the same forwards and backwards, disregarding any non-alphanumeric characters and ignoring cases.",
"split": "train"
} |
import math
def bulbSwitch(n: int) -> int:
return math.isqrt(n) | simplelr_Apps | [
{
"content": "Question:\nYou are given a series of `n` bulbs, numbered from 1 to `n`, initially all turned off. Each bulb `i` has a switch that toggles its state (from off to on, or from on to off). There are `n` people standing in line, and each person `i` toggles every `i-th` bulb in the series (i.e., person ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5862,
"level": 1,
"question": "You are given a series of `n` bulbs, numbered from 1 to `n`, initially all turned off. Each bulb `i` has a switch that toggles its state (from off to on, or from on to off). There are `n` people standing in line, and each person `i` toggles every `i-th... |
def snake_to_camel(s):
words = s.split('_')
if not words:
return ''
camel = words[0].lower()
for word in words[1:]:
if word:
camel += word.capitalize()
return camel | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to convert a given string from snake_case to camelCase. For example, \"this_is_a_test\" should be converted to \"thisIsATest\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5863,
"level": 1,
"question": "Write a Python function to convert a given string from snake_case to camelCase. For example, \"this_is_a_test\" should be converted to \"thisIsATest\".",
"split": "train"
} |
import random
def coin_flip():
return random.choice(["Heads", "Tails"])
# Example usage:
print(coin_flip()) | simplelr_Filter | [
{
"content": "Question:\nCreate a function to simulate a coin flip and return either \"Heads\" or \"Tails\" as a result.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5864,
"level": 1,
"question": "Create a function to simulate a coin flip and return either \"Heads\" or \"Tails\" as a result.",
"split": "train"
} |
def count_unique_substrings(string):
substrings = set()
for i in range(len(string)):
for j in range(i + 1, len(string) + 1):
substrings.add(string[i:j])
return len(substrings) | simplelr_Filter | [
{
"content": "Question:\nHere is the problem statement:\n\nWrite a function that analyzes the structure of a given string and returns the total number of unique substrings it contains.\n\nFor example, given the string \"abc\", the function should return 6 because the unique substrings are: \"a\", \"b\", \"c\", ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5865,
"level": 1,
"question": "Here is the problem statement:\n\nWrite a function that analyzes the structure of a given string and returns the total number of unique substrings it contains.\n\nFor example, given the string \"abc\", the function should return 6 because the unique su... |
def are_all_elements_integers(lst):
return all(type(x) is int for x in lst) | simplelr_Filter | [
{
"content": "Question:\nI have a list of items in Python, and I need to ensure all items are of a specific type, say `int`. How can I do this? I want to write a function that checks if all elements in a given list are integers and returns `True` if they are, or `False` otherwise. Could you provide me with a co... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5866,
"level": 1,
"question": "I have a list of items in Python, and I need to ensure all items are of a specific type, say `int`. How can I do this? I want to write a function that checks if all elements in a given list are integers and returns `True` if they are, or `False` otherw... |
def has_pair_with_sum_zero(nums):
seen = set()
for num in nums:
if -num in seen:
return True
seen.add(num)
return False | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list of integers and returns true if there is a pair of numbers that sum to zero. For example, given the list [1, 3, 5, 0], the function should return true because the sum of 0 and 3 is 0. If there's no such pair, the function should return false. For i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5867,
"level": 1,
"question": "Create a function that takes in a list of integers and returns true if there is a pair of numbers that sum to zero. For example, given the list [1, 3, 5, 0], the function should return true because the sum of 0 and 3 is 0. If there's no such pair, the ... |
def create_matrix(rows, cols):
"""Create a matrix with the specified number of rows and columns,
filled with zeros."""
matrix = [[0 for _ in range(cols)] for _ in range(rows)]
return matrix | simplelr_Filter | [
{
"content": "Question:\ndef create_matrix(rows, cols):\n \"\"\"Create a matrix with the specified number of rows and columns, \n filled with zeros.\"\"\"\n matrix = [[0 for _ in range(cols)] for _ in range(rows)]\n return matrix\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5868,
"level": 1,
"question": "def create_matrix(rows, cols):\n \"\"\"Create a matrix with the specified number of rows and columns, \n filled with zeros.\"\"\"\n matrix = [[0 for _ in range(cols)] for _ in range(rows)]\n return matrix",
"split": "train"
} |
import re
def word_count(text):
return len(re.findall(r'[A-Za-z]+', text)) | simplelr_Package | [
{
"content": "Question:\nYou are required to create a function named `word_count` that takes a string of text as input and returns the number of words in the text. A word is defined as any contiguous sequence of alphabetic characters and can contain both uppercase and lowercase letters. All other characters (su... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5869,
"level": 1,
"question": "You are required to create a function named `word_count` that takes a string of text as input and returns the number of words in the text. A word is defined as any contiguous sequence of alphabetic characters and can contain both uppercase and lowercas... |
import datetime
def is_valid_date(date_string):
try:
datetime.datetime.strptime(date_string, '%Y-%m-%d')
return True
except ValueError:
return False | simplelr_Filter | [
{
"content": "Question:\nYou have been tasked with creating a function that determines whether a given string contains a valid date in the format 'YYYY-MM-DD'. Here is a Python solution that uses the `datetime` module:\n```python\nimport datetime\n\ndef is_valid_date(date_string):\n try:\n datetime.da... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5870,
"level": 1,
"question": "You have been tasked with creating a function that determines whether a given string contains a valid date in the format 'YYYY-MM-DD'. Here is a Python solution that uses the `datetime` module:\n```python\nimport datetime\n\ndef is_valid_date(date_stri... |
def delete_reoccurring_characters_modified(s: str) -> str:
seen = set()
result = []
for char in s:
if char not in seen:
result.append(char)
seen.add(char)
return ''.join(result) | simplelr_Data_Structure | [
{
"content": "Question:\n**Scenario**:\nIn a message preprocessing system, you need to filter out repeated characters from the messages to ensure that each character appears only once in the output while preserving their first occurrence order.\n\n**Task**:\nWrite a function `delete_reoccurring_characters_modif... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5871,
"level": 1,
"question": "**Scenario**:\nIn a message preprocessing system, you need to filter out repeated characters from the messages to ensure that each character appears only once in the output while preserving their first occurrence order.\n\n**Task**:\nWrite a function `... |
def is_decreasing(nums):
return all(nums[i] > nums[i+1] for i in range(len(nums)-1)) | simplelr_Filter | [
{
"content": "Question:\n```python\ndef is_decreasing(nums):\n\n for i in range(len(nums) - 1):\n if nums[i] <= nums[i + 1]:\n return False\n return True\n\n```\n\nThis Python function, `is_decreasing`, aims to determine if a given list of numbers (`nums`) is in strictly decreasing order... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5872,
"level": 1,
"question": "```python\ndef is_decreasing(nums):\n\n for i in range(len(nums) - 1):\n if nums[i] <= nums[i + 1]:\n return False\n return True\n\n```\n\nThis Python function, `is_decreasing`, aims to determine if a given list of numbers (`num... |
def count_characters(s):
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
return counts | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to count the numbers of each character in a string and store the result in a dictionary.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5873,
"level": 1,
"question": "Write a python function to count the numbers of each character in a string and store the result in a dictionary.",
"split": "train"
} |
from collections import Counter
def can_form_palindrome_by_rearranging_and_removing(s: str, k: int) -> bool:
freq = Counter(s)
sum_pairs = sum(v // 2 for v in freq.values())
has_odd = any(v % 2 != 0 for v in freq.values())
max_len = 2 * sum_pairs + (1 if has_odd else 0)
deletions_needed = len(s) - ... | simplelr_Filter | [
{
"content": "Question:\nGiven a string s1 and integer k, you need to write a program to check if the input string can be made a palindrome by rearranging all of its characters and removing at most k of its characters. Return true if it's possible, otherwise return false.\nAnswer:\nLet's think step by step.\n",... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5874,
"level": 1,
"question": "Given a string s1 and integer k, you need to write a program to check if the input string can be made a palindrome by rearranging all of its characters and removing at most k of its characters. Return true if it's possible, otherwise return false.",
... |
def compress_string(s):
compressed = []
i = 0
while i < len(s):
count = 1
while i + 1 < len(s) and s[i] == s[i+1]:
i += 1
count += 1
compressed.append(s[i])
compressed.append(str(count))
i += 1
return compressed
print(compress_string("aaaa... | simplelr_Filter | [
{
"content": "Question:\nHere is the problem.\n\nThe question is asking you to find the resulting compressed string if you run a string compression algorithm on the input string “aaaabcccccaaa”.\n\nHere is the solution.\n\ndef compress_string(s):\n compressed = []\n i = 0\n\n while i < len(s):\n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5875,
"level": 1,
"question": "Here is the problem.\n\nThe question is asking you to find the resulting compressed string if you run a string compression algorithm on the input string “aaaabcccccaaa”.\n\nHere is the solution.\n\ndef compress_string(s):\n compressed = []\n i = ... |
def sort_people(people):
return sorted(people, key=lambda x: x[1], reverse=True) | simplelr_Filter | [
{
"content": "Question:\nIn a function, a person can be represented in the form of a 2-element array `['name', protein_count]`, where 'name' is a string (name of the person) and `protein_count` is a positive integer. Implement a function `sort_people` that sorts the people in descending order based on their pro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5876,
"level": 1,
"question": "In a function, a person can be represented in the form of a 2-element array `['name', protein_count]`, where 'name' is a string (name of the person) and `protein_count` is a positive integer. Implement a function `sort_people` that sorts the people in ... |
def factorial(n):
if n < 0:
return -1
elif n == 0:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the factorial of a given number. The function should be able to handle numbers from 0 to 20. If the input number is negative, the function should return -1. If the input number is 0, the function should return 1. For other numbers, the function should retur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5877,
"level": 1,
"question": "Write a function to calculate the factorial of a given number. The function should be able to handle numbers from 0 to 20. If the input number is negative, the function should return -1. If the input number is 0, the function should return 1. For other... |
def smallest_substring_with_k_distinct(s, k):
unique_chars = len(set(s))
if unique_chars < k:
return -1
from collections import defaultdict
freq = defaultdict(int)
left = 0
min_length = float('inf')
distinct_count = 0
for right in range(len(s)):
char = s[right]
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **non-empty** string `s` consisting of lowercase English letters. A **substring** is a contiguous sequence of characters within a string. Return _the **length** of the **smallest** substring of `s` that contains **at least k** distinct characters_. If there is no such su... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5878,
"level": 1,
"question": "You are given a **non-empty** string `s` consisting of lowercase English letters. A **substring** is a contiguous sequence of characters within a string. Return _the **length** of the **smallest** substring of `s` that contains **at least k** distinct ... |
def reverse_characters(s):
return ' '.join(word[::-1] for word in s.split()) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to reverse the characters of a string in a given sentence. The function should take a single string as input and return a new string where the characters of each word are reversed, but the words remain in their original order. For example, given the string \"hello world... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5879,
"level": 1,
"question": "Write a function to reverse the characters of a string in a given sentence. The function should take a single string as input and return a new string where the characters of each word are reversed, but the words remain in their original order. For exam... |
import logging.config
def configure_logging(config):
try:
logging.config.dictConfig(config)
except (ValueError, TypeError, AttributeError, ImportError) as e:
print(f"Failed to configure logging: {e}")
| simplelr_Docs | [
{
"content": "Question:\n**Question: Advanced Logging Configuration in Python**\n\nPython provides powerful logging capabilities through the \"logging\" library. This library can be configured using dictionaries with the `logging.config.dictConfig` function or using files with the `logging.config.fileConfig` fu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5880,
"level": 1,
"question": "**Question: Advanced Logging Configuration in Python**\n\nPython provides powerful logging capabilities through the \"logging\" library. This library can be configured using dictionaries with the `logging.config.dictConfig` function or using files with... |
def find_max(lst):
if not lst:
return None
for item in lst:
if type(item) not in (int, float):
raise TypeError("Non-numeric value found in the list")
return max(lst) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum number in a given list. However, if the list is empty, the function should return `None`. If the list contains non-numeric values, the function should raise a `TypeError`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5881,
"level": 1,
"question": "Write a python function to find the maximum number in a given list. However, if the list is empty, the function should return `None`. If the list contains non-numeric values, the function should raise a `TypeError`.",
"split": "train"
} |
def nCr(n, r):
if r > n:
return 0
if r == 0 or r == n:
return 1
r = min(r, n - r)
result = 1
for i in range(1, r + 1):
result = result * (n - r + i) // i
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate nCr which is the number of ways to choose r items from n items without regard to the order of selection. The solution should use the efficient form of calculating nCr to avoid large intermediate values that can lead to overflow.\nAnswer:\nLet's think step b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5882,
"level": 1,
"question": "Write a function to calculate nCr which is the number of ways to choose r items from n items without regard to the order of selection. The solution should use the efficient form of calculating nCr to avoid large intermediate values that can lead to ove... |
def add_commas(s):
reversed_s = s[::-1]
chunks = [reversed_s[i:i+3] for i in range(0, len(reversed_s), 3)]
reversed_chunks = [chunk[::-1] for chunk in chunks]
reversed_chunks.reverse()
return ','.join(reversed_chunks)
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a string representation of a non-negative integer and returns the string with commas added as thousands separators.\n\nFor example, if the input is `\"1234567\"`, the output should be `\"1,234,567\"`.\n\nThe input string is guaranteed to represent a valid non... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5883,
"level": 1,
"question": "Write a function that takes a string representation of a non-negative integer and returns the string with commas added as thousands separators.\n\nFor example, if the input is `\"1234567\"`, the output should be `\"1,234,567\"`.\n\nThe input string is ... |
def length_of_longest_substring(s):
char_index = {}
start = 0
max_length = 0
for i in range(len(s)):
char = s[i]
if char in char_index and char_index[char] >= start:
start = char_index[char] + 1
char_index[char] = i
current_length = i - start + 1
if cu... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `str`, find the length of the longest substring without repeating characters. Implement a function that takes a string as input and returns the length of such a substring. The solution should prioritize efficiency, aiming for a time complexity of O(n). \n\nFor example, gi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5884,
"level": 1,
"question": "Given a string `str`, find the length of the longest substring without repeating characters. Implement a function that takes a string as input and returns the length of such a substring. The solution should prioritize efficiency, aiming for a time comp... |
from typing import List
def zigzag_traversal(matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
result = []
for i in range(len(matrix)):
if i % 2 == 0:
result.extend(matrix[i])
else:
result.extend(reversed(matrix[i]))
return result | simplelr_Data_Structure | [
{
"content": "Question:\nZigzag Order Traversal of a Matrix\n\nGiven a matrix of m x n elements (m rows, n columns), return all elements of the matrix in zigzag order. In zigzag order, elements are visited in a 'zigzag' pattern: the first row is traversed from left to right, the second row from right to left, t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5885,
"level": 1,
"question": "Zigzag Order Traversal of a Matrix\n\nGiven a matrix of m x n elements (m rows, n columns), return all elements of the matrix in zigzag order. In zigzag order, elements are visited in a 'zigzag' pattern: the first row is traversed from left to right, t... |
def transform_array(n):
result = []
current_sum = 0
for i in range(n, 0, -1):
current_sum += i
result.append(current_sum)
return result | simplelr_Apps | [
{
"content": "Question:\nYou are given an integer `n` representing the number of elements in an array. You need to perform the following operations sequentially and determine the resulting array:\n\n1. Generate an array of size `n` with elements `[1, 2, 3, ..., n]`.\n2. Reverse the array.\n3. Replace each eleme... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5886,
"level": 1,
"question": "You are given an integer `n` representing the number of elements in an array. You need to perform the following operations sequentially and determine the resulting array:\n\n1. Generate an array of size `n` with elements `[1, 2, 3, ..., n]`.\n2. Revers... |
def compressed_length(s: str) -> int:
if not s:
return 0
current_char = s[0]
current_count = 1
total = 0
for i in range(1, len(s)):
if s[i] == current_char:
current_count += 1
else:
if current_count == 1:
total += 1
... | simplelr_Evol | [
{
"content": "Question:\nWrite a function `compressed_length` that takes a string `s` as input and returns the length of the string after applying basic string compression using the counts of repeated characters. For example, the string \"aabcccccaaa\" would become \"a2b1c5a3\". If the compressed string would n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5887,
"level": 1,
"question": "Write a function `compressed_length` that takes a string `s` as input and returns the length of the string after applying basic string compression using the counts of repeated characters. For example, the string \"aabcccccaaa\" would become \"a2b1c5a3\... |
from typing import List
def increment_digits(digits: List[int]) -> List[int]:
new_digits = list(digits)
carry = 1
i = len(new_digits) - 1
while i >= 0 and carry:
temp = new_digits[i] + carry
new_digits[i] = temp % 10
carry = temp // 10
i -= 1
if carry:
new_di... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Incremental Digit Array\n\nYou are given a non-negative number represented as an array of digits, where each digit is a single digit from 0 to 9. The most significant digit is at the head of the list. Write a function that adds one to the number and returns the resulting a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5888,
"level": 1,
"question": "### Question: Incremental Digit Array\n\nYou are given a non-negative number represented as an array of digits, where each digit is a single digit from 0 to 9. The most significant digit is at the head of the list. Write a function that adds one to the... |
def multiply(a, b):
return a * b | simplelr_Filter | [
{
"content": "Question:\nPlease write a Python function that takes two integers as input and returns their product. The function should handle both positive and negative integers, including zero.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5889,
"level": 1,
"question": "Please write a Python function that takes two integers as input and returns their product. The function should handle both positive and negative integers, including zero.",
"split": "train"
} |
def rotate_string(s, n):
if len(s) == 0:
return s
effective_n = n % len(s)
if effective_n == 0:
return s
return s[-effective_n:] + s[:-effective_n] | simplelr_Apps | [
{
"content": "Question:\nWrite a function called `rotate_string` that takes a string `s` and an integer `n`, and returns a new string with the characters rotated to the right by `n` positions. The rotation should be circular, meaning characters shifted off the end reappear at the beginning.\n\n```python\nrotate... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5890,
"level": 1,
"question": "Write a function called `rotate_string` that takes a string `s` and an integer `n`, and returns a new string with the characters rotated to the right by `n` positions. The rotation should be circular, meaning characters shifted off the end reappear at ... |
def extract_substring(s, start, end):
return s[start:end] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that can extract substrings from a given string using a start and end index. The function should return the extracted substring.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5891,
"level": 1,
"question": "Create a function that can extract substrings from a given string using a start and end index. The function should return the extracted substring.",
"split": "train"
} |
def find_max_length(nums):
sum_indices = {0: -1}
current_sum = 0
max_length = 0
for i, num in enumerate(nums):
current_sum += 1 if num == 1 else -1
if current_sum in sum_indices:
length = i - sum_indices[current_sum]
if length > max_length:
max_len... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes an integer array as input and returns the length of the longest contiguous subarray that consists of an equal number of 0s and 1s. The input array will contain only the integers 0 and 1. Use an efficient algorithm to optimize the solution.\n\nExample:\nInput:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5892,
"level": 1,
"question": "Write a function that takes an integer array as input and returns the length of the longest contiguous subarray that consists of an equal number of 0s and 1s. The input array will contain only the integers 0 and 1. Use an efficient algorithm to optimiz... |
import re
from datetime import datetime
def parse_log_entry(log_entry):
# Extract main components using regex
pattern = r'^(\S+) - \S+ \[(.*?)\] "([^"]+)" (\d+) (-|\d+)$'
match = re.match(pattern, log_entry)
if not match:
return None
ip = match.group(1)
datetime_str = match.group(2... | simplelr_Package | [
{
"content": "Question:\nYou are required to create a function that parses Apache access log files and extracts useful information. The Apache log follows the Common Log Format, which looks like this:\n\n```\n127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326\n```\n\nYour ta... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5893,
"level": 1,
"question": "You are required to create a function that parses Apache access log files and extracts useful information. The Apache log follows the Common Log Format, which looks like this:\n\n```\n127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif ... |
def calculate_stock_value(products):
return [{'name': product['name'], 'total_value': product['price'] * product['quantity']} for product in products] | simplelr_Package | [
{
"content": "Question:\nGiven a list of dictionaries where each dictionary contains details of a product (`name`, `price`, `quantity`), write a function to compute the total stock value of each product and return the result as a list of dictionaries. Each dictionary should include the `name` and `total_value`,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5894,
"level": 1,
"question": "Given a list of dictionaries where each dictionary contains details of a product (`name`, `price`, `quantity`), write a function to compute the total stock value of each product and return the result as a list of dictionaries. Each dictionary should in... |
from typing import List, Tuple
def priority_roads(n: int, pop: List[int], roads: List[Tuple[int, int]]) -> List[int]:
result = []
for a, b in roads:
result.append(pop[a] + pop[b])
return result
| simplelr_Taco | [
{
"content": "Question:\nIn a given town, there is a very peculiar road network resembling a tree structure, where each road connects two towns in such a way that there is exactly one path between any two towns. Each town has a certain population. \n\nThe Mayor of the town wants to allocate a budget for the con... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5895,
"level": 1,
"question": "In a given town, there is a very peculiar road network resembling a tree structure, where each road connects two towns in such a way that there is exactly one path between any two towns. Each town has a certain population. \n\nThe Mayor of the town wan... |
def xor_binary_strings(a, b):
int_a = int(a, 2)
int_b = int(b, 2)
xor = int_a ^ int_b
return bin(xor) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in two binary strings, `a` and `b`, and returns the bit-wise XOR of the two. The result should be a binary string, prefixed with \"0b\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5896,
"level": 1,
"question": "Create a function that takes in two binary strings, `a` and `b`, and returns the bit-wise XOR of the two. The result should be a binary string, prefixed with \"0b\".",
"split": "train"
} |
def trap(height):
if not height:
return 0
n = len(height)
if n < 3:
return 0
left_max = [0] * n
right_max = [0] * n
# Compute left_max array
for i in range(1, n):
left_max[i] = max(left_max[i-1], height[i-1])
# Compute right_max array
for i... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of `n` non-negative integers representing the height of each wall section. Assume it is going to rain and water will be trapped between these walls, forming two-dimensional puddles. Write a function that calculates the total amount of water trapped.\n\nYou should re... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5897,
"level": 1,
"question": "You are given a list of `n` non-negative integers representing the height of each wall section. Assume it is going to rain and water will be trapped between these walls, forming two-dimensional puddles. Write a function that calculates the total amount... |
from typing import List
def max_product(lst: List[int]) -> int:
if len(lst) < 2:
return 0
sorted_lst = sorted(lst)
product1 = sorted_lst[-1] * sorted_lst[-2]
product2 = sorted_lst[0] * sorted_lst[1]
return max(product1, product2)
| simplelr_Taco | [
{
"content": "Question:\nGiven a list of integers, write a function to determine the maximum product of two distinct numbers from the list. If the list has fewer than two elements, return 0.\n\n### Function Signature\n```python\ndef max_product(lst: List[int]) -> int:\n pass\n```\n\n### Input\n- A single lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5898,
"level": 1,
"question": "Given a list of integers, write a function to determine the maximum product of two distinct numbers from the list. If the list has fewer than two elements, return 0.\n\n### Function Signature\n```python\ndef max_product(lst: List[int]) -> int:\n pas... |
def find_peak_element(nums):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
# Check if mid is a peak
is_peak = True
if mid > 0 and nums[mid] <= nums[mid - 1]:
is_peak = False
if mid < len(nums) - 1 and nums[mid] <= nu... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of `n` integers, a \"peak\" element is an element that is strictly greater than its neighbors. Write a program to find a peak element in the list. If the list contains multiple peaks, return the index of any one of the peak elements. The input list will always contain at le... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5899,
"level": 1,
"question": "Given a list of `n` integers, a \"peak\" element is an element that is strictly greater than its neighbors. Write a program to find a peak element in the list. If the list contains multiple peaks, return the index of any one of the peak elements. The i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.