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_distinct_elements(lst):
if not lst:
return 0
lst.sort()
count = 1
for i in range(1, len(lst)):
if lst[i] != lst[i-1]:
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\nGiven a list of numbers, propose code that returns the number of distinct elements in the list. Additionally, ensure that the solution has a time complexity of O(nlogn), where n is the length of the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 0,
"level": 1,
"question": "Given a list of numbers, propose code that returns the number of distinct elements in the list. Additionally, ensure that the solution has a time complexity of O(nlogn), where n is the length of the list.",
"split": "train"
} |
def array_to_string(arr):
return ','.join(map(str, arr)) | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes an array of integers and returns a string containing the values separated by commas.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1,
"level": 1,
"question": "Write a function in Python that takes an array of integers and returns a string containing the values separated by commas.",
"split": "train"
} |
def buildings_with_sunset_view(heights):
max_height = 0
result = []
for i in range(len(heights) - 1, -1, -1):
if heights[i] > max_height:
result.append(i)
max_height = heights[i]
return result[::-1] | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `heights` representing the heights of buildings within a city. The city has a rule that a building can see the sunset if there are no taller buildings to its right. Return _the list of indices of the buildings that can see the sunset_, in **as... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2,
"level": 1,
"question": "You are given a **0-indexed** integer array `heights` representing the heights of buildings within a city. The city has a rule that a building can see the sunset if there are no taller buildings to its right. Return _the list of indices of the buildings t... |
def longest_common_prefix(words):
if not words:
return 0
first = words[0]
for i in range(len(first)):
current_char = first[i]
for word in words[1:]:
if word[i] != current_char:
return i
return len(first) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of strings `words` of length `n`. Each string in `words` is uppercase and has the same length. You need to find the length of the **longest common prefix** shared among all the strings in the list `words`. A common prefix is a substring that appears at the beginning... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 3,
"level": 1,
"question": "You are given a list of strings `words` of length `n`. Each string in `words` is uppercase and has the same length. You need to find the length of the **longest common prefix** shared among all the strings in the list `words`. A common prefix is a substri... |
def echo(s, *args):
if '-n' in args:
print(s, end='')
else:
print(s) | simplelr_Filter | [
{
"content": "Question:\nThis problem requires you to implement a function that reproduces the behavior of the Unix `echo` command. The function, called `echo`, takes a string as input and prints it. The function also takes an optional flag `-n` to suppress the trailing newline character. Here is how you can te... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 4,
"level": 1,
"question": "This problem requires you to implement a function that reproduces the behavior of the Unix `echo` command. The function, called `echo`, takes a string as input and prints it. The function also takes an optional flag `-n` to suppress the trailing newline c... |
def min_distance_pair(arr1, arr2):
n = len(arr1)
min_dist = float('inf')
result = []
for i in range(n):
for j in range(i + 1, n):
dist = abs(arr1[i] - arr1[j]) + abs(arr2[i] - arr2[j])
if dist < min_dist:
min_dist = dist
result = [i, j]
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two integer arrays `arr1` and `arr2` of length `n`, representing the coordinates of points in a 2D plane. The `i`-th point in this plane has coordinates `(arr1[i], arr2[i])`. Your task is to find a pair of distinct points such that the distance between them is minimized, a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 5,
"level": 1,
"question": "You are given two integer arrays `arr1` and `arr2` of length `n`, representing the coordinates of points in a 2D plane. The `i`-th point in this plane has coordinates `(arr1[i], arr2[i])`. Your task is to find a pair of distinct points such that the dista... |
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
high = mid - 1
else:
low = mid + 1
return -1 | simplelr_Filter | [
{
"content": "Question:\nCraft a software routine that effectively finds and delivers the position within an array, particularly a sequence that is sorted, of a given number utilizing the methods of binary search.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 6,
"level": 1,
"question": "Craft a software routine that effectively finds and delivers the position within an array, particularly a sequence that is sorted, of a given number utilizing the methods of binary search.",
"split": "train"
} |
def flatten_list(nested_list: list) -> list:
if not isinstance(nested_list, list):
raise TypeError("Input must be a list")
result = []
for element in nested_list:
if isinstance(element, list):
sub_flattened = flatten_list(element)
result.extend(sub_flattened)
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nYou are working on a data processing engine that includes a feature to \"flatten\" nested lists (lists within lists) into a single list of values. This functionality is crucial for standardizing input data structures before further proces... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 7,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario\nYou are working on a data processing engine that includes a feature to \"flatten\" nested lists (lists within lists) into a single list of values. This functionality is crucial for standardizing input data ... |
from collections import Counter
def can_form_word(tiles: str, word: str) -> bool:
if len(word) > len(tiles):
return False
tile_counts = Counter(tiles)
word_counts = Counter(word)
for char, count in word_counts.items():
if tile_counts.get(char, 0) < count:
return False
re... | simplelr_Algorithm | [
{
"content": "Question:\n## Question\n\nYour task is to implement a function to determine if a given word can be constructed using a set of given tiles. Each tile has a letter, and each letter can be used only once to form the word.\n\n### Function Signature\n```python\ndef can_form_word(tiles: str, word: str) ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 8,
"level": 1,
"question": "## Question\n\nYour task is to implement a function to determine if a given word can be constructed using a set of given tiles. Each tile has a letter, and each letter can be used only once to form the word.\n\n### Function Signature\n```python\ndef can_f... |
from collections import Counter
def least_interval(tasks, n):
if not tasks:
return 0
count = Counter(tasks)
max_count = max(count.values())
count_of_max = sum(1 for v in count.values() if v == max_count)
required = (max_count - 1) * (n + 1) + count_of_max
total_tasks = len(tasks)
re... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a list of tasks represented as integer values, where each task needs to run at a specific interval. Each task takes one unit of time to complete, but there must be at least `n` units of time interval between two instances of the same task. You need to determine the **minim... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9,
"level": 1,
"question": "You are given a list of tasks represented as integer values, where each task needs to run at a specific interval. Each task takes one unit of time to complete, but there must be at least `n` units of time interval between two instances of the same task. Y... |
def is_palindrome(s):
cleaned = ''.join([c.lower() for c in s if c.isalnum()])
return cleaned == cleaned[::-1]
| simplelr_Taco | [
{
"content": "Question:\nJack is an enthusiastic competitive programmer. He often encounters problems that involve determining whether a sequence is the same forwards and backwards. He needs a program to help him quickly identify palindromes. Your task is to write a function ```isPalindrome```(C# ```IsPalindrom... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 10,
"level": 1,
"question": "Jack is an enthusiastic competitive programmer. He often encounters problems that involve determining whether a sequence is the same forwards and backwards. He needs a program to help him quickly identify palindromes. Your task is to write a function ```... |
def is_match(s: str, p: str) -> bool:
m = len(s)
n = len(p)
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for i in range(m + 1):
for j in range(n + 1):
if i == 0 and j == 0:
continue # already initialized to True
if i == 0:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Regular Expression Matching with Dynamic Programming\n\nYou are given a string `s` and a pattern `p` where:\n- `'.'` matches any single character.\n- `'*'` matches zero or more of the preceding element.\n\nWrite a function `is_match(s: str, p: str) -> bool` that returns whether `s` ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 11,
"level": 1,
"question": "### Regular Expression Matching with Dynamic Programming\n\nYou are given a string `s` and a pattern `p` where:\n- `'.'` matches any single character.\n- `'*'` matches zero or more of the preceding element.\n\nWrite a function `is_match(s: str, p: str) -... |
def find_first_position(arr, n):
low = 0
high = len(arr) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if arr[mid] == n:
result = mid
high = mid - 1 # Continue searching left for a possible earlier occurrence
elif arr[mid] < n:
lo... | simplelr_Filter | [
{
"content": "Question:\nwrite a python code to find the first position of a number n in a sorted array. If the number is not present, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 12,
"level": 1,
"question": "write a python code to find the first position of a number n in a sorted array. If the number is not present, return -1.",
"split": "train"
} |
def find_person_by_name(people, name):
for person in people:
if person['name'] == name:
return person
return "Person not found" | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find a person by name in a list of dictionaries. Each dictionary represents a person with keys for 'name' and 'age'. The function should return the first dictionary where the 'name' key matches the input name. If no dictionary is found with that name, the function sh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 13,
"level": 1,
"question": "Write a function to find a person by name in a list of dictionaries. Each dictionary represents a person with keys for 'name' and 'age'. The function should return the first dictionary where the 'name' key matches the input name. If no dictionary is foun... |
from typing import List
def rotate_clockwise(matrix: List[List[int]]) -> List[List[int]]:
if not matrix or not matrix[0]:
return []
rows = len(matrix)
cols = len(matrix[0]) if rows > 0 else 0
# Transpose the matrix
transposed = []
for j in range(cols):
new_row = [matri... | simplelr_Data_Structure | [
{
"content": "Question:\n### Matrix Transformation Challenge\n\n**Context**: As a junior software developer at a tech company, you are working on an image processing module. The module requires you to implement a series of matrix transformations that enhance the images by manipulating pixel arrangements. Your t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 14,
"level": 1,
"question": "### Matrix Transformation Challenge\n\n**Context**: As a junior software developer at a tech company, you are working on an image processing module. The module requires you to implement a series of matrix transformations that enhance the images by manipu... |
from collections import defaultdict
def longestSubstringWithSameLetters(s, k):
n = len(s)
if n == 0:
return 0
freq = defaultdict(int)
left = 0
max_len = 0
max_freq = 0
for right in range(n):
char = s[right]
freq[char] += 1
if freq[char] > m... | simplelr_Taco | [
{
"content": "Question:\nYou are given a string str and an integer k. You need to perform k operations on the string. In each operation, select any one character of the string and change it to any other lowercase English letter. Your task is to determine the length of the longest substring that contains all sam... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 15,
"level": 1,
"question": "You are given a string str and an integer k. You need to perform k operations on the string. In each operation, select any one character of the string and change it to any other lowercase English letter. Your task is to determine the length of the longes... |
def check_password_strength(password: str) -> str:
special_chars = '!@#$%^&*()-_'
condition_length = 8 <= len(password) <= 20
condition_upper = any(c.isupper() for c in password)
condition_lower = any(c.islower() for c in password)
condition_digit = any(c.isdigit() for c in password)
condit... | simplelr_Code_Contests | [
{
"content": "Question:\nGaurav wants to create a simple password strength checker. The password strength is determined based on the following criteria:\n- Contains at least one uppercase letter.\n- Contains at least one lowercase letter.\n- Contains at least one digit.\n- Contains at least one special characte... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 16,
"level": 1,
"question": "Gaurav wants to create a simple password strength checker. The password strength is determined based on the following criteria:\n- Contains at least one uppercase letter.\n- Contains at least one lowercase letter.\n- Contains at least one digit.\n- Conta... |
def balancedParenthesesAndSum(expression):
stack = []
sum_digits = 0
for c in expression:
if c == '(':
stack.append(c)
elif c == ')':
if not stack:
return -1
stack.pop()
else:
sum_digits += int(c)
return sum_digits i... | simplelr_Apps | [
{
"content": "Question:\n## Task\nImplement a function `balancedParenthesesAndSum` that checks if a given expression containing parentheses is balanced and if it is, then calculates the sum of the digits present in the expression.\n \nAn expression is considered balanced if:\n1. Every opening parenthesis '(' ha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 17,
"level": 1,
"question": "## Task\nImplement a function `balancedParenthesesAndSum` that checks if a given expression containing parentheses is balanced and if it is, then calculates the sum of the digits present in the expression.\n \nAn expression is considered balanced if:\n1.... |
def generate_pyramid(n):
max_width = 2 * n - 1
rows = []
for r in range(1, n + 1):
stars = '*' * (2 * r - 1)
centered_row = stars.center(max_width)
rows.append(centered_row)
return '\n'.join(rows) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to generate a string of asterisks forming a pyramid shape with a given number of rows. The pyramid should be centered, and the number of asterisks in each row should increase by 2 for each subsequent row, starting from 1 at the top.\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 18,
"level": 1,
"question": "Write a Python function to generate a string of asterisks forming a pyramid shape with a given number of rows. The pyramid should be centered, and the number of asterisks in each row should increase by 2 for each subsequent row, starting from 1 at the to... |
def shortest_unique_substring(s):
required = len(set(s))
if required == 0:
return ""
char_count = {}
left = 0
min_length = float('inf')
result = ""
current_unique = 0
for right in range(len(s)):
char = s[right]
if char in char_count:
char_count[char] ... | simplelr_Filter | [
{
"content": "Question:\nYou've been tasked with writing a function that takes a string and returns the shortest possible substring that contains all the unique characters in the string. If there are multiple substrings of the same length, return the first one you encounter. What would you be if you were a func... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 19,
"level": 1,
"question": "You've been tasked with writing a function that takes a string and returns the shortest possible substring that contains all the unique characters in the string. If there are multiple substrings of the same length, return the first one you encounter. Wha... |
def are_anagrams(str1, str2):
if len(str1) != len(str2):
return False
return sorted(str1) == sorted(str2) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings, `str1` and `str2`. Your task is to determine if `str1` can be rearranged to form `str2`. In other words, check if the two strings are anagrams of each other. An anagram of a string is the rearrangement of its characters to form another string using all the ori... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 20,
"level": 1,
"question": "You are given two strings, `str1` and `str2`. Your task is to determine if `str1` can be rearranged to form `str2`. In other words, check if the two strings are anagrams of each other. An anagram of a string is the rearrangement of its characters to form... |
from typing import List
def dailyTemperatures(temperatures: List[int]) -> List[int]:
n = len(temperatures)
result = [0] * n
stack = []
for i in range(n):
while stack and temperatures[stack[-1]] < temperatures[i]:
idx = stack.pop()
result[idx] = i - idx
stack.appe... | simplelr_Apps | [
{
"content": "Question:\nVera has an array of integers representing the daily temperatures over a period of time. She wants to know, for each day in the array, how many days she would have to wait until a warmer temperature occurs. If no future day has a warmer temperature, she should put `0` for that day.\n\nW... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 21,
"level": 1,
"question": "Vera has an array of integers representing the daily temperatures over a period of time. She wants to know, for each day in the array, how many days she would have to wait until a warmer temperature occurs. If no future day has a warmer temperature, she ... |
def min_completion_time(tasks: list[int]) -> int:
total = sum(tasks)
target = total // 2
dp = 1 # Using a bitmask to represent achievable sums
for t in tasks:
dp |= dp << t
dp &= (1 << (target + 1)) - 1 # Mask to keep only up to target
# Find the highest set bit
max_sum = 0
... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given an array of n integers, where each integer represents the amount of time it takes to complete a particular task. You need to distribute these tasks between two workers such that the time taken to complete all the tasks is minimized. Each worker can work on multiple tasks s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 22,
"level": 1,
"question": "You are given an array of n integers, where each integer represents the amount of time it takes to complete a particular task. You need to distribute these tasks between two workers such that the time taken to complete all the tasks is minimized. Each wo... |
from collections import Counter
def most_frequent_element(arr):
if not arr:
return None
counts = Counter(arr)
most_common_element, _ = counts.most_common(1)[0]
return most_common_element | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the most frequent element in an array. The function should take an array as input and return the most frequent element.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 23,
"level": 1,
"question": "Write a python function to find the most frequent element in an array. The function should take an array as input and return the most frequent element.",
"split": "train"
} |
from collections import Counter
def is_anagram_of_palindrome(s: str) -> bool:
# Normalize the string by converting to lowercase and removing non-alphabetic characters
normalized = ''.join([c.lower() for c in s if c.isalpha()])
# An empty string is trivially a palindrome
if not normalized:
... | simplelr_Evol | [
{
"content": "Question:\nImplement a function to determine if a given string is an anagram of a palindrome. An anagram of a palindrome means that the characters of the string can be rearranged to form a palindrome. If the string fulfills this condition, your function should return True; otherwise, it should ret... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 24,
"level": 1,
"question": "Implement a function to determine if a given string is an anagram of a palindrome. An anagram of a palindrome means that the characters of the string can be rearranged to form a palindrome. If the string fulfills this condition, your function should retu... |
def increment_elements(lst):
return [x + 1 for x in lst] | simplelr_Filter | [
{
"content": "Question:\nI want to create a function that takes a list of integers and returns a new list with each element incremented by 1. For example, if I pass the list `[1, 2, 3]` to the function, it should return `[2, 3, 4]`. How can I achieve this in Python?\nAnswer:\nLet's think step by step.\n",
"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 25,
"level": 1,
"question": "I want to create a function that takes a list of integers and returns a new list with each element incremented by 1. For example, if I pass the list `[1, 2, 3]` to the function, it should return `[2, 3, 4]`. How can I achieve this in Python?",
"split":... |
import pandas as pd
import numpy as np
from typing import Tuple
def summarizeCSVColumn(filePath: str, columnName: str) -> Tuple[float, float, float]:
"""
Calculates and returns the mean, median, and standard deviation of a specified column in a CSV file.
Parameters:
- filePath (str): The path to the C... | simplelr_Package | [
{
"content": "Question:\nYou are tasked with creating a function in Python that reads, processes, and summarizes data from a CSV file. Your function should compute summary statistics (mean, median, and standard deviation) for a specified column in the CSV file. \n\nTo fulfill this task, implement the following ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 26,
"level": 1,
"question": "You are tasked with creating a function in Python that reads, processes, and summarizes data from a CSV file. Your function should compute summary statistics (mean, median, and standard deviation) for a specified column in the CSV file. \n\nTo fulfill th... |
def string_to_int(s):
i = 0
while i < len(s) and s[i].isdigit():
i += 1
num_str = s[:i]
return int(num_str) if num_str else 0 | simplelr_Filter | [
{
"content": "Question:\nI am working on a project and I need a simple function to convert a string of numbers to an integer. However, if the string contains a non-numeric character, I would like to truncate the string at the first non-numeric character and then attempt to convert it.\n\nHere is an example: \n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 27,
"level": 1,
"question": "I am working on a project and I need a simple function to convert a string of numbers to an integer. However, if the string contains a non-numeric character, I would like to truncate the string at the first non-numeric character and then attempt to conve... |
def count_long_words(sentence, num):
words = sentence.split()
count = 0
for word in words:
if len(word) > num:
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python that takes a sentence and a number as inputs, and returns the number of words in that sentence that are longer than the given number.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 28,
"level": 1,
"question": "Write a function in Python that takes a sentence and a number as inputs, and returns the number of words in that sentence that are longer than the given number.",
"split": "train"
} |
from typing import List
def reorder_packets(packets: List[int], indices: List[int]) -> List[int]:
zipped = list(zip(indices, packets))
sorted_pairs = sorted(zipped, key=lambda x: x[0])
reordered = [packet for index, packet in sorted_pairs]
return reordered
| simplelr_Taco | [
{
"content": "Question:\nIn a system where data packets are sent from a source to a destination, consider a scenario where you have a sequence of packets identified by their indices. Each packet can arrive out of order. You need to reorder the packets based on their original sequence before further processing.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 29,
"level": 1,
"question": "In a system where data packets are sent from a source to a destination, consider a scenario where you have a sequence of packets identified by their indices. Each packet can arrive out of order. You need to reorder the packets based on their original seq... |
def updateInventory(products, orders):
# Create a copy of the products dictionary to avoid modifying the original
updated_products = products.copy()
for order in orders:
product_name = order['product']
quantity = order['quantity']
if product_name in updated_products:
upda... | simplelr_Package | [
{
"content": "Question:\nIn this problem, we will work with a basic inventory management system for an e-commerce platform. Your task is to implement a function that updates the inventory levels based on a list of orders processed within a day.\n\n**Function to Implement**:\n`updateInventory(products, orders)`\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 30,
"level": 1,
"question": "In this problem, we will work with a basic inventory management system for an e-commerce platform. Your task is to implement a function that updates the inventory levels based on a list of orders processed within a day.\n\n**Function to Implement**:\n`up... |
def authenticate_user(auth_data):
import getpass
# Step 1: Fetch the logged-in user's name
username = getpass.getuser()
# Step 2: Check if the user exists in auth_data
if username not in auth_data:
return False
# Step 3: Prompt the user for their password securely
pass... | simplelr_Docs | [
{
"content": "Question:\n### Password Authentication System\n\nYou are tasked with creating a simple password authentication system. For this, you will use the `getpass` module, which securely handles password input and user login information.\n\n### Your Task:\n\nImplement the following function:\n\n```python\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 31,
"level": 1,
"question": "### Password Authentication System\n\nYou are tasked with creating a simple password authentication system. For this, you will use the `getpass` module, which securely handles password input and user login information.\n\n### Your Task:\n\nImplement the ... |
def min_meeting_rooms(meetings):
events = []
for start, end in meetings:
events.append((start, 1))
events.append((end, -1))
events.sort()
current_rooms = 0
max_rooms = 0
for time, delta in events:
current_rooms += delta
if current_rooms > max_rooms:
ma... | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a list of tuples, where each tuple contains two integers representing the start and end times of a meeting. The function should return the minimum number of meeting rooms required to accommodate all the meetings without any overlap.\n\nExample:\n\n```python\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 32,
"level": 1,
"question": "Write a function that takes a list of tuples, where each tuple contains two integers representing the start and end times of a meeting. The function should return the minimum number of meeting rooms required to accommodate all the meetings without any ov... |
def calculate_average_scores(words):
student_scores = {}
for word in words:
student_id, score_str = word.split(':')
score = int(score_str)
if student_id in student_scores:
student_scores[student_id][0] += score
student_scores[student_id][1] += 1
else:
... | simplelr_Leetcode | [
{
"content": "Question:\nGiven a list of `n` strings `words`, each string represents a student's score report in the format \"student_id:score\". Write a function to calculate the average score for each student and return a list of results in the format \"student_id:average_score\". The results should be sorted... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 33,
"level": 1,
"question": "Given a list of `n` strings `words`, each string represents a student's score report in the format \"student_id:score\". Write a function to calculate the average score for each student and return a list of results in the format \"student_id:average_scor... |
import heapq
from typing import List, Tuple
def dijkstra_optimized(graph: List[List[Tuple[int, int]]], src: int) -> List[int]:
n = len(graph)
if n == 0:
return []
dist = [float('inf')] * n
dist[src] = 0
heap = []
heapq.heappush(heap, (0, src))
while heap:
curr... | simplelr_Data_Structure | [
{
"content": "Question:\nImplement Dijkstra's Algorithm with Priority Queue Optimization\n\n#### Scenario\nYou are tasked with implementing an optimized version of Dijkstra's algorithm using a priority queue to find the shortest paths from a given source vertex to all other vertices in a weighted graph. This wi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 34,
"level": 1,
"question": "Implement Dijkstra's Algorithm with Priority Queue Optimization\n\n#### Scenario\nYou are tasked with implementing an optimized version of Dijkstra's algorithm using a priority queue to find the shortest paths from a given source vertex to all other vert... |
def longestUniqueSkillsSubarray(N, skills):
last_pos = {} # To track the last occurrence of each skill
max_unique = 0
left = 0
unique_len = {} # Maps unique count to its maximum length
for right in range(N):
# Update the left pointer to exclude duplicates
if skills[right] in l... | simplelr_Taco | [
{
"content": "Question:\nA company has N employees, each with a set of skills. The company's management wants to form the most skilled team for a special project. Each skill is represented by an integer, and an employee can have multiple skills. Management decides to select a sub-array of contiguous employees s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 35,
"level": 1,
"question": "A company has N employees, each with a set of skills. The company's management wants to form the most skilled team for a special project. Each skill is represented by an integer, and an employee can have multiple skills. Management decides to select a su... |
def floyd_warshall(adjacency_matrix):
n = len(adjacency_matrix)
dist = [row.copy() for row in adjacency_matrix]
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][j] > dist[i][k] + dist[k][j]:
dist[i][j] = dist[i][k] + dist[k][j]
... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a weighted, directed graph described by an **n x n** adjacency matrix `adjacency_matrix` where `adjacency_matrix[i][j]` represents the weight of the edge from node `i` to node `j`. If there is no edge between the nodes, the corresponding cell will contain a very large numb... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 36,
"level": 1,
"question": "You are given a weighted, directed graph described by an **n x n** adjacency matrix `adjacency_matrix` where `adjacency_matrix[i][j]` represents the weight of the edge from node `i` to node `j`. If there is no edge between the nodes, the corresponding ce... |
def count_substring_case_insensitive(main_string, sub_string):
return main_string.lower().count(sub_string.lower()) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to count the number of times a given substring appears in a string, case-insensitively. The function should be named `count_substring_case_insensitive` and should have two parameters: `main_string` and `sub_string`.\nAnswer:\nLet's think step by step.\n",
"ro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 37,
"level": 1,
"question": "Write a python function to count the number of times a given substring appears in a string, case-insensitively. The function should be named `count_substring_case_insensitive` and should have two parameters: `main_string` and `sub_string`.",
"split": "... |
def count_sorted_vowel_strings(n):
return ( (n + 4) * (n + 3) * (n + 2) * (n + 1) ) // 24 | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer `n`, return the number of strings of length `n` that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string `s` is lexicographically sorted if for all valid `i`, `s[i] <= s[i+1]`.\n\n**Note:**\n* The length of the string `n` is guaranteed to b... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 38,
"level": 1,
"question": "Given an integer `n`, return the number of strings of length `n` that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string `s` is lexicographically sorted if for all valid `i`, `s[i] <= s[i+1]`.\n\n**Note:**\n* The length of ... |
def smallest_missing_positive(arr):
n = len(arr)
for i in range(n):
while 1 <= arr[i] <= n and arr[i] != i + 1:
j = arr[i] - 1
if arr[j] == arr[i]:
break
arr[i], arr[j] = arr[j], arr[i]
for i in range(n):
if arr[i] != i + 1:
ret... | simplelr_Apps | [
{
"content": "Question:\nWrite a function `smallest_missing_positive` that takes an array of integers and returns the smallest positive integer (greater than 0) that does not appear in the array. The function should have a time complexity of O(n) and a space complexity of O(1).\n\nFor example:\n```\nsmallest_mi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 39,
"level": 1,
"question": "Write a function `smallest_missing_positive` that takes an array of integers and returns the smallest positive integer (greater than 0) that does not appear in the array. The function should have a time complexity of O(n) and a space complexity of O(1).\... |
def two_sum(nums, target):
nums_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in nums_map:
return [nums_map[complement], i]
nums_map[num] = i
return [] | simplelr_Filter | [
{
"content": "Question:\n# Problem\nGiven an array of integers, return indices of the two numbers such that they add up to a specific target value.\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 indices in any order.\n\nExampl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 40,
"level": 1,
"question": "# Problem\nGiven an array of integers, return indices of the two numbers such that they add up to a specific target value.\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 th... |
def max_product_of_two(arr):
if len(arr) < 2:
return 0
arr_sorted = sorted(arr, reverse=True)
return arr_sorted[0] * arr_sorted[1] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that returns the maximum product of two distinct elements in an array of non-negative integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 41,
"level": 1,
"question": "Create a function that returns the maximum product of two distinct elements in an array of non-negative integers.",
"split": "train"
} |
def letter_frequency_analysis(ciphertext: str) -> dict:
# Initialize the frequency dictionary with all lowercase letters set to 0
frequency = {chr(ord('a') + i): 0 for i in range(26)}
# Iterate through each character in the ciphertext
for char in ciphertext:
lower_char = char.lower()
if ... | simplelr_Apps | [
{
"content": "Question:\nA common way to create a frequency analysis for solving monoalphabetic substitution ciphers is to analyze the frequency distribution of letters in a given ciphertext. By comparing the frequency distribution of each letter in the ciphertext to known frequency distributions in the English... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 42,
"level": 1,
"question": "A common way to create a frequency analysis for solving monoalphabetic substitution ciphers is to analyze the frequency distribution of letters in a given ciphertext. By comparing the frequency distribution of each letter in the ciphertext to known frequ... |
def count_unique_substrings(s: str) -> int:
substrings = set()
n = len(s)
for i in range(n):
for j in range(i, n):
substr = s[i:j+1]
substrings.add(substr)
return len(substrings) | simplelr_Algorithm | [
{
"content": "Question:\nCounting Unique Substrings\n\n#### Context\nYou need to develop an algorithm to count the number of unique substrings in a given string. This problem tests your ability to understand and manipulate strings efficiently.\n\n#### Function Definition\nImplement the `count_unique_substrings(... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 43,
"level": 1,
"question": "Counting Unique Substrings\n\n#### Context\nYou need to develop an algorithm to count the number of unique substrings in a given string. This problem tests your ability to understand and manipulate strings efficiently.\n\n#### Function Definition\nImplem... |
import pandas as pd
def process_csv(filename, condition_column, target_column, new_value):
"""
This function processes a CSV file by modifying values in a specific column
based on a condition in another column.
Args:
filename (str): Path to the CSV file.
condition_column (str): Name of... | simplelr_Filter | [
{
"content": "Question:\nLet's say I have a Python code like this example:\n\nThe goal is to process a CSV file with Pandas and modify it based on some conditions.\n\n```python\nimport pandas as pd\n\ndef process_csv(filename, condition_column, target_column, new_value):\n \"\"\"\n This function processes a C... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 44,
"level": 1,
"question": "Let's say I have a Python code like this example:\n\nThe goal is to process a CSV file with Pandas and modify it based on some conditions.\n\n```python\nimport pandas as pd\n\ndef process_csv(filename, condition_column, target_column, new_value):\n \"\"... |
def save_and_load_results(results_dict, file_path):
"""
Save the results dictionary to a binary file and load it back.
:param results_dict: dict - Dictionary with computational results.
:param file_path: str - Path to the binary file.
:return: dict - The dictionary loaded from the binary file.
... | simplelr_Docs | [
{
"content": "Question:\n**Python Coding Assessment Question:**\n\n### Serialization and Deserialization with Marshal\n\nThe `marshal` module in Python allows for the serialization (marshaling) and deserialization (unmarshaling) of Python objects into a specific binary format. This is particularly useful for sa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 45,
"level": 1,
"question": "**Python Coding Assessment Question:**\n\n### Serialization and Deserialization with Marshal\n\nThe `marshal` module in Python allows for the serialization (marshaling) and deserialization (unmarshaling) of Python objects into a specific binary format. T... |
import random
def generate_random_integer(a, b):
return random.randint(a, b) | simplelr_Filter | [
{
"content": "Question:\nI'm a developer working on a project that involves generating random numbers within a specific range. I need a simple, straightforward function that can produce a random integer between two given numbers, inclusive.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 46,
"level": 1,
"question": "I'm a developer working on a project that involves generating random numbers within a specific range. I need a simple, straightforward function that can produce a random integer between two given numbers, inclusive.",
"split": "train"
} |
def reverse_squares_of_odds(numbers: list[int]) -> list[int]:
squared_odds = list(map(lambda x: x ** 2, filter(lambda x: x % 2 != 0, numbers)))
return squared_odds[::-1]
| simplelr_Docs | [
{
"content": "Question:\n**Objective:**\nImplement a function that takes a list of integers and returns a new list containing the squares of all odd numbers in reverse order. If there are no odd numbers, return an empty list.\n\n**Detailed Instructions:**\n\n1. Your function should be named `reverse_squares_of_... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 47,
"level": 1,
"question": "**Objective:**\nImplement a function that takes a list of integers and returns a new list containing the squares of all odd numbers in reverse order. If there are no odd numbers, return an empty list.\n\n**Detailed Instructions:**\n\n1. Your function sho... |
from typing import List, Tuple
def analyze_data_transfers(transfers: List[Tuple[str, str, int]]) -> List[Tuple[str, int]]:
totals = {}
for src, _, data in transfers:
totals[src] = totals.get(src, 0) + data
return sorted(totals.items(), key=lambda x: (-x[1], x[0])) | simplelr_Apps | [
{
"content": "Question:\nAs a security analyst, you are tasked with monitoring the network for potential anomalies in data transfer activities. You need to analyze a list of data transfer records where each record is represented as a tuple containing the following information: (source IP, destination IP, transf... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 48,
"level": 1,
"question": "As a security analyst, you are tasked with monitoring the network for potential anomalies in data transfer activities. You need to analyze a list of data transfer records where each record is represented as a tuple containing the following information: (... |
import bisect
def closest_value(arr, x):
if not arr:
return None # assuming the function is called with a non-empty array as per problem statement
i = bisect.bisect_left(arr, x)
if i == 0:
return arr[0]
if i == len(arr):
return arr[-1]
before = arr[i-1]
after = arr[i]
... | simplelr_Filter | [
{
"content": "Question:\nWrite a python function to find the closest value to a given number in a given sorted array. The array can contain duplicate values.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 49,
"level": 1,
"question": "Write a python function to find the closest value to a given number in a given sorted array. The array can contain duplicate values.",
"split": "train"
} |
def reverse_k_chars(s, k):
n = min(k, len(s))
return s[:n][::-1] + s[n:]
| simplelr_Taco | [
{
"content": "Question:\nGiven a string s and an integer k, your task is to reverse the first k characters of the string. If the string has fewer than k characters, reverse the entire string. Implement the function reverse_k_chars(s, k) that takes a string and an integer as arguments and returns the modified st... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 50,
"level": 1,
"question": "Given a string s and an integer k, your task is to reverse the first k characters of the string. If the string has fewer than k characters, reverse the entire string. Implement the function reverse_k_chars(s, k) that takes a string and an integer as argu... |
def decode_string(s: str) -> str:
stack = []
current_string = ''
current_number = 0
for char in s:
if char.isdigit():
current_number = current_number * 10 + int(char)
elif char == '[':
stack.append((current_string, current_number))
current_string = ''... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given an encoded string that follows a specific encoding rule: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly `k` times. Implement a function `decode_string(s)` that decodes this string and returns the decoded string.\n\n### Inpu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 51,
"level": 1,
"question": "You are given an encoded string that follows a specific encoding rule: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly `k` times. Implement a function `decode_string(s)` that decodes this string and return... |
def estimate_range(mpg: float, fuel_percentage: float, tank_capacity: float) -> float:
remaining_gallons = (fuel_percentage / 100.0) * tank_capacity
distance = remaining_gallons * mpg
return distance
| simplelr_Taco | [
{
"content": "Question:\nThe miles-per-gallon (MPG) of a car is a measure of how many miles a car can travel on one gallon of gasoline. Given a car's MPG, the car's fuel gauge reading (as a percentage), and the capacity of the car's fuel tank in gallons, determine how far the car can travel before running out o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 52,
"level": 1,
"question": "The miles-per-gallon (MPG) of a car is a measure of how many miles a car can travel on one gallon of gasoline. Given a car's MPG, the car's fuel gauge reading (as a percentage), and the capacity of the car's fuel tank in gallons, determine how far the ca... |
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import os
def visualize_data_with_palettes(df, qualitative_col, value_col1, value_col2, value_col3, output_dir):
# Ensure the output directory exists
os.makedirs(output_dir, exist_ok=True)
# Scatter plot with a qualitative palet... | simplelr_Docs | [
{
"content": "Question:\nDesigning and Applying Color Palettes in Seaborn\n\n#### Objective\nDesign and apply different color palettes to a plot using seaborn to demonstrate your understanding of qualitative, sequential, and diverging palettes.\n\n#### Task\n1. **Create a Data Visualization Function**: Implemen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 53,
"level": 1,
"question": "Designing and Applying Color Palettes in Seaborn\n\n#### Objective\nDesign and apply different color palettes to a plot using seaborn to demonstrate your understanding of qualitative, sequential, and diverging palettes.\n\n#### Task\n1. **Create a Data V... |
def find_unique_element(arr: list) -> int:
result = 0
for num in arr:
result ^= num
return result | simplelr_Apps | [
{
"content": "Question:\n# Task\n\nConsider an array of integers where every element appears twice except for one. Find the element that appears only once. Your algorithm should have a linear runtime complexity.\n\nYou must implement a function that solves the following problem:\n\n**Function Signature:**\n```p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 54,
"level": 1,
"question": "# Task\n\nConsider an array of integers where every element appears twice except for one. Find the element that appears only once. Your algorithm should have a linear runtime complexity.\n\nYou must implement a function that solves the following problem:... |
from typing import List, Optional
def replace_missing_values(data: List[List[Optional[float]]]) -> List[List[float]]:
# Transpose the data to process columns easily
columns = zip(*data)
means = []
for col in columns:
non_none_values = [x for x in col if x is not None]
if not non_none_va... | simplelr_Package | [
{
"content": "Question:\nYou are required to implement a function `replace_missing_values` that replaces missing values in a dataset with the mean of the respective column. For the purpose of this question, a missing value is denoted by `None` (Python's `NoneType`). Your function should handle input in the form... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 55,
"level": 1,
"question": "You are required to implement a function `replace_missing_values` that replaces missing values in a dataset with the mean of the respective column. For the purpose of this question, a missing value is denoted by `None` (Python's `NoneType`). Your functio... |
def is_balanced_parentheses(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False
stack.pop()
return len(stack) == 0 | simplelr_Filter | [
{
"content": "Question:\nCan you write a Python program that verifies if a string of parentheses is balanced? A balanced string of parentheses is one where each opening parenthesis has a corresponding closing parenthesis in the correct order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 56,
"level": 1,
"question": "Can you write a Python program that verifies if a string of parentheses is balanced? A balanced string of parentheses is one where each opening parenthesis has a corresponding closing parenthesis in the correct order.",
"split": "train"
} |
def filter_numbers(lst):
result = []
for item in lst:
if type(item) in (int, float):
result.append(item)
return result | simplelr_Evol | [
{
"content": "Question:\nDesign a function that takes a list of mixed data types and returns a new list where only the numeric values (integers and floats) are retained. The function should maintain the original order of appearance of the numeric values from the input list. If there are no numeric values, it sh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 57,
"level": 1,
"question": "Design a function that takes a list of mixed data types and returns a new list where only the numeric values (integers and floats) are retained. The function should maintain the original order of appearance of the numeric values from the input list. If t... |
def add_bitwise_operator(x: int, y: int) -> int:
while y != 0:
sum_without_carry = x ^ y
carry = (x & y) << 1
x, y = sum_without_carry, carry
return x | simplelr_Data_Structure | [
{
"content": "Question:\n### **Bitwise Addition Simulator**\n\n**Objective:**\nImplement a function that adds two positive integers using bitwise operations, similar to how the underlying hardware might perform addition without using the '+' operator.\n\n**Input Format:**\n- Two positive integers, a and b.\n\n*... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 58,
"level": 1,
"question": "### **Bitwise Addition Simulator**\n\n**Objective:**\nImplement a function that adds two positive integers using bitwise operations, similar to how the underlying hardware might perform addition without using the '+' operator.\n\n**Input Format:**\n- Two... |
def find_first_occurrence(nums, target):
low = 0
high = len(nums) - 1
res = -1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
res = mid
high = mid - 1
elif nums[mid] < target:
low = mid + 1
else:
high = m... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums` sorted in non-decreasing order, and an integer `target`. Return _the **index** of the first occurrence of_ `target` _in_ `nums`. _If_ `target` _is not present, return_ `-1`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 59,
"level": 1,
"question": "You are given an array of integers `nums` sorted in non-decreasing order, and an integer `target`. Return _the **index** of the first occurrence of_ `target` _in_ `nums`. _If_ `target` _is not present, return_ `-1`.",
"split": "train"
} |
from typing import List
def maximumWealth(accounts: List[List[int]]) -> int:
max_wealth = 0
for customer in accounts:
current_sum = sum(customer)
if current_sum > max_wealth:
max_wealth = current_sum
return max_wealth | simplelr_Codeforces | [
{
"content": "Question:\nYou are given an array of integers representing the amount of money in different accounts in a bank. The goal is to calculate the maximum wealth an individual can have. Wealth is defined as the sum of all the money a person has across all their accounts.\n\nEach customer may have one or... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 60,
"level": 1,
"question": "You are given an array of integers representing the amount of money in different accounts in a bank. The goal is to calculate the maximum wealth an individual can have. Wealth is defined as the sum of all the money a person has across all their accounts.... |
def fibonacci_up_to_n(n):
if n < 0:
return []
fib = []
a, b = 0, 1
while a <= n:
fib.append(a)
a, b = b, a + b
return fib | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python function that generates a Fibonacci sequence up to a given number `n`? The function should return a list of all Fibonacci numbers up to `n`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 61,
"level": 1,
"question": "Can you provide a Python function that generates a Fibonacci sequence up to a given number `n`? The function should return a list of all Fibonacci numbers up to `n`.",
"split": "train"
} |
def hamming_distance(s1, s2):
if len(s1) != len(s2):
raise ValueError("Strings must be of the same length")
return sum(c1 != c2 for c1, c2 in zip(s1, s2)) | simplelr_Filter | [
{
"content": "Question:\nHow can I calculate the Hamming distance between two strings in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 62,
"level": 1,
"question": "How can I calculate the Hamming distance between two strings in Python?",
"split": "train"
} |
from typing import List
squares_cache = {}
def sum_of_squares(nums: List[int]) -> int:
nums_tuple = tuple(nums)
if nums_tuple in squares_cache:
return squares_cache[nums_tuple]
else:
total = sum(x ** 2 for x in nums)
squares_cache[nums_tuple] = total
return total | simplelr_Package | [
{
"content": "Question:\nYou are required to create a function named `sum_of_squares` that takes a list of integers and computes the sum of squares of those integers. The sum of squares is the sum of each number in the list raised to the power of 2. To optimize the performance, if the list of integers has alrea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 63,
"level": 1,
"question": "You are required to create a function named `sum_of_squares` that takes a list of integers and computes the sum of squares of those integers. The sum of squares is the sum of each number in the list raised to the power of 2. To optimize the performance, ... |
def max_points(grid):
rows = len(grid)
cols = len(grid[0]) if rows > 0 else 0
# Create a 2D list to store maximum points up to each cell
dp = [[0] * cols for _ in range(rows)]
# Initialize the starting point
dp[-1][0] = grid[-1][0]
# Fill the first column
for i in range(ro... | simplelr_Taco | [
{
"content": "Question:\nYou are designing a new game where the player needs to collect points that are scattered on a grid. The grid is represented as a 2D list where each cell contains an integer representing the number of points in that cell. The player can only start at the bottom-left corner of the grid an... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 64,
"level": 1,
"question": "You are designing a new game where the player needs to collect points that are scattered on a grid. The grid is represented as a 2D list where each cell contains an integer representing the number of points in that cell. The player can only start at the ... |
def prime_factors(n):
factors = []
if n < 2:
return factors
n = abs(n)
while n % 2 == 0:
factors.append(2)
n = n // 2
i = 3
while i * i <= n:
while n % i == 0:
factors.append(i)
n = n // i
i += 2
if n > 1:
factors.append... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find all the prime factors of a given number.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 65,
"level": 1,
"question": "Write a function to find all the prime factors of a given number.",
"split": "train"
} |
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 key in anagrams:
groups.append(sorted(anagrams[key]))
groups.sort(key=lambda x: x[0... | simplelr_Apps | [
{
"content": "Question:\nGiven a list of words, group the anagrams together. Each group of anagrams should be output in alphabetical order, and the groups themselves should also be printed in alphabetical order based on their first word.\n\nExample 1:\n\nInput: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"ba... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 66,
"level": 1,
"question": "Given a list of words, group the anagrams together. Each group of anagrams should be output in alphabetical order, and the groups themselves should also be printed in alphabetical order based on their first word.\n\nExample 1:\n\nInput: [\"eat\", \"tea\"... |
def robot_returns(moves: str) -> bool:
x = 0
y = 0
for move in moves:
if move == 'U':
y += 1
elif move == 'D':
y -= 1
elif move == 'L':
x -= 1
else: # 'R'
x += 1
return x == 0 and y == 0 | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Robotic Return Path\n\nYou are tasked with determining whether a robot, starting at the origin (0,0), returns to the original point after performing a given sequence of moves. The robot can follow these specific moves:\n- 'U' (Up): Move one unit up the y-axis.\n- 'D' (Down... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 67,
"level": 1,
"question": "### Question: Robotic Return Path\n\nYou are tasked with determining whether a robot, starting at the origin (0,0), returns to the original point after performing a given sequence of moves. The robot can follow these specific moves:\n- 'U' (Up): Move one... |
from datetime import date
def manage_dates(dates):
# Parse each date string into a date object
parsed_dates = [date.fromisoformat(d) for d in dates]
# Sort the parsed dates chronologically
sorted_dates = sorted(parsed_dates)
# Filter dates that fall on weekends (Saturday or Sunday)
we... | simplelr_Package | [
{
"content": "Question:\nYou are required to create a function named `manage_dates` that will accept a list of dates (in string format `YYYY-MM-DD`). This function should utilize Python's `datetime` library to perform the following operations:\n\n1. **Sort Dates**:\n - Sort the list of dates chronologically.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 68,
"level": 1,
"question": "You are required to create a function named `manage_dates` that will accept a list of dates (in string format `YYYY-MM-DD`). This function should utilize Python's `datetime` library to perform the following operations:\n\n1. **Sort Dates**:\n - Sort t... |
def min_length_after_removals(s):
count_a = s.count('a')
count_b = s.count('b')
return abs(count_a - count_b) | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` containing only the characters `a` and `b`. You are allowed to perform two operations on the string any number of times: 1) remove one occurrence of `ab` from the string, or 2) remove one occurrence of `ba` from the string. Return _the **minimum length** of th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 69,
"level": 1,
"question": "You are given a string `s` containing only the characters `a` and `b`. You are allowed to perform two operations on the string any number of times: 1) remove one occurrence of `ab` from the string, or 2) remove one occurrence of `ba` from the string. Ret... |
from typing import List
def symmetric_difference(list1: List[int], list2: List[int]) -> List[int]:
# Create a dictionary to track presence of elements in list2
set2 = {}
for x in list2:
set2[x] = True
result = []
# Check each element in list1 against set2
for x in list1:
if x no... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes two lists of integers, `list1` and `list2`, as input and returns a list of integers containing elements that are present in either `list1` or `list2`, but not in both. Your solution should not use any library functions like `set()`. \n\nFor example, \n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 70,
"level": 1,
"question": "Write a Python function that takes two lists of integers, `list1` and `list2`, as input and returns a list of integers containing elements that are present in either `list1` or `list2`, but not in both. Your solution should not use any library functions ... |
def unique_sorted_words(inputfile: str, outputfile: str) -> bool:
unique_words = set()
try:
with open(inputfile, 'r') as infile:
for line in infile:
words = line.split()
for word in words:
lower_word = word.lower()
uniqu... | simplelr_Package | [
{
"content": "Question:\nWrite a Python function named `unique_sorted_words` that reads data from a text file where each line contains a sentence. The function should extract all unique words from the sentences, sort them alphabetically, and write them into a new text file with one word per line in sorted order... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 71,
"level": 1,
"question": "Write a Python function named `unique_sorted_words` that reads data from a text file where each line contains a sentence. The function should extract all unique words from the sentences, sort them alphabetically, and write them into a new text file with ... |
def calculate(symbol, a, b):
allowed_ops = {'+', '-', '*', '/'}
if symbol not in allowed_ops:
raise ValueError(f"Invalid operator. Expected one of {allowed_ops}, got {symbol}.")
if type(a) not in (int, float) or type(b) not in (int, float):
raise ValueError("Both inputs must be numbers (int ... | simplelr_Filter | [
{
"content": "Question:\nDefine an operator function that performs a calculation based on a given operator symbol (+, -, *, /) and two numerical inputs. Implement error handling for invalid operator input and non-numeric inputs. Additionally, improve the piece of provided erroneous code as a starting point to w... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 72,
"level": 1,
"question": "Define an operator function that performs a calculation based on a given operator symbol (+, -, *, /) and two numerical inputs. Implement error handling for invalid operator input and non-numeric inputs. Additionally, improve the piece of provided errone... |
from typing import List
def max_ones_index(arr: List[int]) -> int:
# Check if there are any zeros
if 0 not in arr:
return -1
n = len(arr)
left_ones = [0] * n
right_ones = [0] * n
# Compute left_ones
for i in range(1, n):
if arr[i-1] == 1:
left_ones[i] =... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Find the Index to Maximize Continuous 1s in a Binary Array\n\n#### Objective\nYou are given a binary array, where each element is either 0 or 1. You need to determine the index of a `0` that, if replaced by `1`, would maximize the length of the longest contiguous subarray ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 73,
"level": 1,
"question": "### Question: Find the Index to Maximize Continuous 1s in a Binary Array\n\n#### Objective\nYou are given a binary array, where each element is either 0 or 1. You need to determine the index of a `0` that, if replaced by `1`, would maximize the length of... |
import numpy as np
from numpy.lib.stride_tricks import as_strided
def median_filter(image):
m, n = image.shape
output = np.zeros((m, n), dtype=np.uint8)
if m < 3 or n < 3:
return image.astype(np.uint8, copy=False)
# Create a view for the 3x3 blocks
view_shape = (m-2, n-2, 3, 3)
... | simplelr_Algorithm | [
{
"content": "Question:\n### Image Denoising using Median Filter\n\nGiven the code snippet and analysis of a Median Filter for noise reduction, implement a function to denoise a given grayscale image using a 3x3 median filter.\n\n### Input Format\n* A 2D numpy array representing a grayscale image, with pixel va... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 74,
"level": 1,
"question": "### Image Denoising using Median Filter\n\nGiven the code snippet and analysis of a Median Filter for noise reduction, implement a function to denoise a given grayscale image using a 3x3 median filter.\n\n### Input Format\n* A 2D numpy array representing... |
def basic_operations(op1, op2, operation):
if operation == 'add':
return op1 + op2
elif operation == 'subtract':
return op1 - op2
elif operation == 'multiply':
return op1 * op2
elif operation == 'divide':
if op2 == 0:
raise ValueError("Cannot divide by zero.")... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to implement the four basic operations (add, subtract, multiply, divide) in Python. The function should take three parameters: two operand values and the operation to be performed. It should return the result of the operation.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 75,
"level": 1,
"question": "Write a function to implement the four basic operations (add, subtract, multiply, divide) in Python. The function should take three parameters: two operand values and the operation to be performed. It should return the result of the operation.",
"split... |
def count_zero_bits(n):
if n == 0:
return 1
binary = bin(abs(n))[2:]
return binary.count('0') | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer as input and returns the number of zero bits in the binary representation of the integer. For example, the binary representation of 5 is '101', so the function should return 1, as there is one zero bit. If the input is 0, the function should retur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 76,
"level": 1,
"question": "Create a function that takes an integer as input and returns the number of zero bits in the binary representation of the integer. For example, the binary representation of 5 is '101', so the function should return 1, as there is one zero bit. If the inpu... |
def highest_scorers(students_scores):
if not students_scores:
return []
max_score = max(score for name, score in students_scores)
top_students = [name for name, score in students_scores if score == max_score]
top_students.sort()
return top_students | simplelr_Evol | [
{
"content": "Question:\nWrite a program that processes a list of students' names and their corresponding scores, to determine the highest scoring student(s). If there are multiple students with the highest score, return all their names in alphabetical order. Your task is to create a function that accepts a lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 77,
"level": 1,
"question": "Write a program that processes a list of students' names and their corresponding scores, to determine the highest scoring student(s). If there are multiple students with the highest score, return all their names in alphabetical order. Your task is to cre... |
def maxSubArray(nums):
if not nums:
return None
max_current = max_global = nums[0]
for num in nums[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global | simplelr_Filter | [
{
"content": "Question:\nI am trying to solve the \"Maximum Subarray\" problem on LeetCode. \n\nThe problem is to find the maximum contiguous subarray (containing at least one number) of a given one-dimensional array of numbers. \n\nFor example, given the array `[-2,1,-3,4,-1,2,1,-5,4]`, the function should ret... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 78,
"level": 1,
"question": "I am trying to solve the \"Maximum Subarray\" problem on LeetCode. \n\nThe problem is to find the maximum contiguous subarray (containing at least one number) of a given one-dimensional array of numbers. \n\nFor example, given the array `[-2,1,-3,4,-1,2,... |
def count_visible_buildings(heights):
n = len(heights)
if n == 0:
return []
res = [0] * n
for i in range(n-2, -1, -1):
if heights[i+1] < heights[i]:
res[i] = 1 + res[i+1]
else:
res[i] = 0
return res | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `heights` representing the heights of buildings, where `heights[i]` is the height of the `i`-th building. An individual standing on top of a building can see the next building if and only if it is strictly shorter than the current one. Starting from th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 79,
"level": 1,
"question": "You are given an array of integers `heights` representing the heights of buildings, where `heights[i]` is the height of the `i`-th building. An individual standing on top of a building can see the next building if and only if it is strictly shorter than ... |
def min_difference(arr):
arr.sort()
min_diff = float('inf')
for i in range(len(arr) - 1):
diff = arr[i+1] - arr[i]
if diff < min_diff:
min_diff = diff
return min_diff | simplelr_Filter | [
{
"content": "Question:\nYou are given an array of integers.\n\nWrite a function that efficiently determines the minimum difference between any two elements in the array.\n\nExample:\n\n```python\narr = [1, 5, 8, 3, 10]\n\n# Output: 2 (Difference between 3 and 5)\n```\n\nConstraints:\n\n The array length is at ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 80,
"level": 1,
"question": "You are given an array of integers.\n\nWrite a function that efficiently determines the minimum difference between any two elements in the array.\n\nExample:\n\n```python\narr = [1, 5, 8, 3, 10]\n\n# Output: 2 (Difference between 3 and 5)\n```\n\nConstra... |
def minimal_weight_difference(n, weights):
total = sum(weights)
target = total // 2
current_sums = {0}
for weight in weights:
new_sums = set()
for s in current_sums:
temp = s + weight
if temp <= target and temp not in current_sums:
new_sums.add(tem... | simplelr_Code_Contests | [
{
"content": "Question:\nYou have a box that can hold `n` items, where each item has a certain weight. You are given a list of `n` integers representing the weights of these items. Your task is to distribute these items into two separate boxes such that the difference in the total weight of the items in the two... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 81,
"level": 1,
"question": "You have a box that can hold `n` items, where each item has a certain weight. You are given a list of `n` integers representing the weights of these items. Your task is to distribute these items into two separate boxes such that the difference in the tot... |
import math
def detect_prime(n: int) -> bool:
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = math.sqrt(n)
for i in range(3, int(sqrt_n) + 1, 2):
if n % i == 0:
return False
return True | simplelr_Data_Structure | [
{
"content": "Question:\n### Prime Number Identification\n\nGiven a number `n`, create a function `detect_prime(n: int) -> bool` that checks whether `n` is a prime number. \n\n### Function Signature\n```python\ndef detect_prime(n: int) -> bool:\n pass\n```\n\n### Description\n\nA prime number is defined as a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 82,
"level": 1,
"question": "### Prime Number Identification\n\nGiven a number `n`, create a function `detect_prime(n: int) -> bool` that checks whether `n` is a prime number. \n\n### Function Signature\n```python\ndef detect_prime(n: int) -> bool:\n pass\n```\n\n### Description\... |
def max_value(items, weight_limit):
if weight_limit == 0:
return 0
dp = [0] * (weight_limit + 1)
for weight, value in items:
for w in range(weight_limit, weight - 1, -1):
if dp[w - weight] + value > dp[w]:
dp[w] = dp[w - weight] + value
return dp[weight_limit]... | simplelr_Taco | [
{
"content": "Question:\nSuzuki needs help preparing for his trip!\n\nSuzuki is planning a trip and wants to pack his bag efficiently. He wants to maximize the number of items he can carry without exceeding a given weight limit. You will be given a list of items, each with a weight and a value. Suzuki wants to ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 83,
"level": 1,
"question": "Suzuki needs help preparing for his trip!\n\nSuzuki is planning a trip and wants to pack his bag efficiently. He wants to maximize the number of items he can carry without exceeding a given weight limit. You will be given a list of items, each with a wei... |
def count_flips_to_convert(a, b):
xor = a ^ b
return bin(xor).count('1') | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nIn certain communication systems, it is crucial to assess the difference between given states represented as integers, often requiring the counting of bit differences. This helps in error detection and correction mechanisms.\n\n### Task\nWrite a function to determine the m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 84,
"level": 1,
"question": "### Scenario\nIn certain communication systems, it is crucial to assess the difference between given states represented as integers, often requiring the counting of bit differences. This helps in error detection and correction mechanisms.\n\n### Task\nWr... |
def sum_of_even_numbers(arr):
return sum(num for num in arr if num % 2 == 0) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum of all even numbers in an array of integers. Write this function in Python. Also, consider the case where the array might be empty or contain no even numbers. In such cases, your function should return 0.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 85,
"level": 1,
"question": "Write a function to calculate the sum of all even numbers in an array of integers. Write this function in Python. Also, consider the case where the array might be empty or contain no even numbers. In such cases, your function should return 0.",
"split"... |
import poplib
from email.parser import BytesParser
def retrieve_email_subjects(host: str, username: str, password: str, use_ssl: bool = False) -> list:
try:
# Connect to the POP3 server
if use_ssl:
server = poplib.POP3_SSL(host)
else:
server = poplib.POP3(host)
... | simplelr_Docs | [
{
"content": "Question:\n#### Objective:\nYou are tasked with implementing a Python function that connects to a POP3 server, retrieves email messages, and prints the subject line of each email. You should use the `poplib` module to accomplish this task.\n\n#### Problem Statement:\nImplement the function `retrie... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 86,
"level": 1,
"question": "#### Objective:\nYou are tasked with implementing a Python function that connects to a POP3 server, retrieves email messages, and prints the subject line of each email. You should use the `poplib` module to accomplish this task.\n\n#### Problem Statement... |
def isBalanced(s: str) -> bool:
stack = []
bracket_map = {')': '(', '}': '{', ']': '['}
for char in s:
if char in ['(', '{', '[']:
stack.append(char)
elif char in bracket_map:
if not stack:
return False
top = stack.pop()
if top ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string representing a code snippet that may contain nested brackets of three types: `()`, `{}`, and `[]`. Write a function that determines if the brackets are balanced. Brackets are considered balanced if:\n\n- Each opening bracket has a corresponding closing bracket of ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 87,
"level": 1,
"question": "You are given a string representing a code snippet that may contain nested brackets of three types: `()`, `{}`, and `[]`. Write a function that determines if the brackets are balanced. Brackets are considered balanced if:\n\n- Each opening bracket has a ... |
def longest_common_subsequence(text1, text2):
m = len(text1)
n = len(text2)
# Create a DP table with (m+1) rows and (n+1) columns.
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):
if text1[i-1] == text2[j-... | simplelr_Algorithm | [
{
"content": "Question:\n### Question\nWrite a function `string longest_common_subsequence(string text1, string text2)` that finds the longest common subsequence (LCS) of two strings and returns the LCS as a string.\n\n**Background**: The longest common subsequence problem is to find the longest subsequence pre... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 88,
"level": 1,
"question": "### Question\nWrite a function `string longest_common_subsequence(string text1, string text2)` that finds the longest common subsequence (LCS) of two strings and returns the LCS as a string.\n\n**Background**: The longest common subsequence problem is to... |
def max_items(nums, budget):
nums_sorted = sorted(nums)
total = 0
count = 0
for num in nums_sorted:
if total + num <= budget:
total += num
count += 1
else:
break
return count | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `nums` representing the cost of various items in a store. You have a certain amount of money `budget`. Your goal is to maximize the total number of items you can buy without exceeding your `budget`. Return _the maximum number of items you can ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 89,
"level": 1,
"question": "You are given a **0-indexed** integer array `nums` representing the cost of various items in a store. You have a certain amount of money `budget`. Your goal is to maximize the total number of items you can buy without exceeding your `budget`. Return _the... |
def count_unique_numbers(lst):
unique_numbers = set(lst)
return len(unique_numbers)
# Example usage:
numbers = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7]
print(count_unique_numbers(numbers)) # Output: 7 | simplelr_Filter | [
{
"content": "Question:\nHow can we determine the number of unique numbers in a given list using Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 90,
"level": 1,
"question": "How can we determine the number of unique numbers in a given list using Python?",
"split": "train"
} |
def longest_subarray_with_k_distinct(nums, k):
if not nums or k == 0:
return 0
unique_count = len(set(nums))
if k > unique_count:
return 0
max_length = 0
freq = {}
left = 0
for right in range(len(nums)):
current = nums[right]
if current in freq:
fr... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes an array of integers and an integer `k`, and returns the length of the longest subarray that contains exactly `k` different integers. If there is no such subarray, return 0. The function should handle edge cases where the array is empty or where `k` is zero o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 91,
"level": 1,
"question": "Write a function that takes an array of integers and an integer `k`, and returns the length of the longest subarray that contains exactly `k` different integers. If there is no such subarray, return 0. The function should handle edge cases where the arra... |
def common_elements(list1, list2):
set1 = set(list1)
set2 = set(list2)
common = set1.intersection(set2)
common_list = list(common)
common_list.sort()
return common_list | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that finds the common elements between two given lists. The function should return a list containing the common elements, ensuring that the elements are unique and sorted in ascending order.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 92,
"level": 1,
"question": "Write a Python function that finds the common elements between two given lists. The function should return a list containing the common elements, ensuring that the elements are unique and sorted in ascending order.",
"split": "train"
} |
def trap(height):
if not height or len(height) < 3:
return 0
n = len(height)
left_max = [0] * n
right_max = [0] * n
# Compute left_max array
current_max = 0
for i in range(1, n):
current_max = max(current_max, height[i-1])
left_max[i] = current_max
# Com... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given an array of integer heights representing the elevation map where the width of each bar is 1. Compute how much water it is able to trap after raining.\n\nThe elevation map is described by an array of non-negative integers, where each element represents the height of a verti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 93,
"level": 1,
"question": "You are given an array of integer heights representing the elevation map where the width of each bar is 1. Compute how much water it is able to trap after raining.\n\nThe elevation map is described by an array of non-negative integers, where each element... |
from collections import Counter
def can_form_palindrome(s: str) -> bool:
# Filter the string to include only alphanumeric characters, converted to lowercase
filtered = [c.lower() for c in s if c.isalnum()]
# Count the frequency of each character
counts = Counter(filtered)
# Count how many character... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that determines whether a given string can be rearranged to form a palindrome. A string is a palindrome if it reads the same forward and backward. \n\nFor the purposes of this problem, only consider alphanumeric characters and ignore case differences.\n\nTo solve this p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 94,
"level": 1,
"question": "Write a function that determines whether a given string can be rearranged to form a palindrome. A string is a palindrome if it reads the same forward and backward. \n\nFor the purposes of this problem, only consider alphanumeric characters and ignore cas... |
def findPair(arr, target):
left = 0
right = len(arr) - 1
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == target:
return [arr[left], arr[right]]
elif current_sum < target:
left += 1
else:
right -= 1
return []
| simplelr_Taco | [
{
"content": "Question:\nGiven a sorted array of integers, write a function that finds the two numbers that sum up to a given target. If no such pair exists, return an empty list. The array contains unique numbers.\n\nExample 1:\nInput:\narr = [1, 2, 3, 4, 6], target = 5\nOutput:\n[1, 4]\nExplanation:\n1 + 4 = ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 95,
"level": 1,
"question": "Given a sorted array of integers, write a function that finds the two numbers that sum up to a given target. If no such pair exists, return an empty list. The array contains unique numbers.\n\nExample 1:\nInput:\narr = [1, 2, 3, 4, 6], target = 5\nOutput... |
def min_subarray_length_with_product(arr, x):
min_len = float('inf')
n = len(arr)
# Check if any single element meets the condition
if any(num >= x for num in arr):
return 1
for i in range(n):
current_product = 1
for j in range(i, n):
current_product *= ... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `arr` and an integer `x`, your task is to determine the minimum length of a contiguous subarray of which the product is greater than or equal to `x`. If no such subarray exists, return `0`. A **contiguous subarray** is a consecutive sequence of elements within the... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 96,
"level": 1,
"question": "Given an integer array `arr` and an integer `x`, your task is to determine the minimum length of a contiguous subarray of which the product is greater than or equal to `x`. If no such subarray exists, return `0`. A **contiguous subarray** is a consecutiv... |
def double_and_filter(nums):
result = []
for num in nums:
doubled = num * 2
if doubled >= 10:
result.append(doubled)
return result | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of integers as input and returns a new list where each integer is doubled and each integer is greater than or equal to 10. The function should also handle the case where the input list is empty.\nAnswer:\nLet's think step by step.\n",
"role": "use... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 97,
"level": 1,
"question": "Create a function that takes a list of integers as input and returns a new list where each integer is doubled and each integer is greater than or equal to 10. The function should also handle the case where the input list is empty.",
"split": "train"
} |
def merge_sorted_arrays(arr1, arr2):
i = j = 0
merged = []
# Merge smaller elements first
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
merged.append(arr1[i])
i += 1
else:
merged.append(arr2[j])
j += 1
# Add the remainin... | simplelr_Filter | [
{
"content": "Question:\nWhat is the Python code to merge two sorted arrays and return a new sorted array?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 98,
"level": 1,
"question": "What is the Python code to merge two sorted arrays and return a new sorted array?",
"split": "train"
} |
def sum_of_natural_numbers(n):
total_sum = 0
for i in range(1, n + 1):
total_sum += i
return total_sum | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to calculate the sum of the first n natural numbers using a loop.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 99,
"level": 1,
"question": "Write a function to calculate the sum of the first n natural numbers using a loop.",
"split": "train"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.