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 min_operations_to_make_equal(s1, s2):
m = len(s1)
n = len(s2)
# Create a DP table with (m+1) rows and (n+1) columns
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i -... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two strings, `s1` and `s2`, and you need to make the two strings equal by performing the minimum number of operations. In each operation, you can remove one character from either string. \n\nReturn the minimum number of operations required to make `s1` and `s2` equal.\n\nF... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9800,
"level": 1,
"question": "You are given two strings, `s1` and `s2`, and you need to make the two strings equal by performing the minimum number of operations. In each operation, you can remove one character from either string. \n\nReturn the minimum number of operations require... |
def to_lower_case(s):
result = ''
for c in s:
if 'A' <= c <= 'Z':
result += chr(ord(c) + 32)
else:
result += c
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a function that takes a string and converts it to all lower case, but without using any built-in string manipulation functions or methods such as `lower()`, `lowercase()`, or any similar ones available in the programming language you choose. Additionally, your function should hand... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9801,
"level": 1,
"question": "Write a function that takes a string and converts it to all lower case, but without using any built-in string manipulation functions or methods such as `lower()`, `lowercase()`, or any similar ones available in the programming language you choose. Addi... |
def next_bigger(num: int) -> int:
digits = list(map(int, str(num)))
n = len(digits)
pivot = -1
# Find the pivot
for i in range(n - 2, -1, -1):
if digits[i] < digits[i + 1]:
pivot = i
break
if pivot == -1:
return -1 # No such number possible
... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a number, and your task is to generate the next higher number consisting of the exact same set of digits as the original number. If no such number exists, return -1.\n\n**Function Signature**\n\n```python\ndef next_bigger(num: int) -> int:\n```\n\n**Input:**\n1. An integer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9802,
"level": 1,
"question": "You are given a number, and your task is to generate the next higher number consisting of the exact same set of digits as the original number. If no such number exists, return -1.\n\n**Function Signature**\n\n```python\ndef next_bigger(num: int) -> int... |
def max_balanced_substring(s: str) -> int:
balance = 0
max_length = 0
balance_indices = {0: -1} # To store the first occurrence of each balance value
for index, char in enumerate(s):
if char == 'L':
balance += 1
else:
balance -= 1
if balance... | simplelr_Package | [
{
"content": "Question:\n**\n\nCreate a function `max_balanced_substring(s)` that finds the length of the longest balanced substring within a given string `s`. A balanced substring is defined as one that has an equal number of 'L' and 'R' characters.\n\nThe function should have the following signature:\n```pyth... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9803,
"level": 1,
"question": "**\n\nCreate a function `max_balanced_substring(s)` that finds the length of the longest balanced substring within a given string `s`. A balanced substring is defined as one that has an equal number of 'L' and 'R' characters.\n\nThe function should hav... |
def find_x_smallest_elements(arr, x):
sorted_arr = sorted(arr)
return sorted_arr[:x] | simplelr_Leetcode | [
{
"content": "Question:\n**Question 4:** You are provided with an unsorted integer array `arr` and an integer `x`. Your task is to find the `x` smallest elements in the array and return them in sorted order.\n\nFor example:\n- If `arr = [7, 10, 4, 3, 20, 15]` and `x = 3`, then the output should be `[3, 4, 7]`.\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9804,
"level": 1,
"question": "**Question 4:** You are provided with an unsorted integer array `arr` and an integer `x`. Your task is to find the `x` smallest elements in the array and return them in sorted order.\n\nFor example:\n- If `arr = [7, 10, 4, 3, 20, 15]` and `x = 3`, then... |
from typing import List, Tuple
def elevator_system(requests: List[Tuple[int, int]]) -> List[int]:
current_floor = 0
result = []
for start, destination in requests:
result.append(start)
result.append(destination)
return result | simplelr_Package | [
{
"content": "Question:\nYou are asked to write a Python function to simulate an \"elevator system\" in a building. The function should take a list of requests, where each request is a tuple representing the starting floor and the destination floor. The function should return a list of floors visited by the ele... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9805,
"level": 1,
"question": "You are asked to write a Python function to simulate an \"elevator system\" in a building. The function should take a list of requests, where each request is a tuple representing the starting floor and the destination floor. The function should return ... |
def count_ways(steps):
if steps == 1:
return 1
elif steps == 2:
return 2
a, b, c = 1, 1, 2 # Represents ways(0), ways(1), ways(2)
for i in range(3, steps + 1):
next_val = a + b + c
a, b, c = b, c, next_val
return c | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with designing an extended version of the staircase problem, where each time you can either climb 1, 2, or 3 steps instead of just 1 or 2. Given a positive integer `steps`, you are to find the number of distinct ways to reach the top.\n\n### Function Specification\n\nImpl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9806,
"level": 1,
"question": "You are tasked with designing an extended version of the staircase problem, where each time you can either climb 1, 2, or 3 steps instead of just 1 or 2. Given a positive integer `steps`, you are to find the number of distinct ways to reach the top.\n\... |
def correct_profile_id(profiles):
return [''.join([c.lower() for c in s if c.isalpha()]) for s in profiles] | simplelr_Codeforces | [
{
"content": "Question:\nA company uses a simplified system to log in to employee profiles, where each employee has a unique profile ID composed of lowercase English letters. Unfortunately, a bug was introduced which changed some profiles to uppercase. To maintain consistency, we need to convert them back to th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9807,
"level": 1,
"question": "A company uses a simplified system to log in to employee profiles, where each employee has a unique profile ID composed of lowercase English letters. Unfortunately, a bug was introduced which changed some profiles to uppercase. To maintain consistency,... |
def find_two_largest(numbers):
if len(numbers) < 2:
return None
first = second = float('-inf')
for num in numbers:
if num > first:
second = first
first = num
elif num > second:
second = num
return (first, second) | simplelr_Filter | [
{
"content": "Question:\nHello, could you help me with a question about a Python function? I have a list of numbers and I want to find the two largest numbers in that list. Can you provide a function to do that?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9808,
"level": 1,
"question": "Hello, could you help me with a question about a Python function? I have a list of numbers and I want to find the two largest numbers in that list. Can you provide a function to do that?",
"split": "train"
} |
def find_key_with_highest_value(dictionary):
if not dictionary:
return None
return max(dictionary, key=lambda k: dictionary[k]) | simplelr_Filter | [
{
"content": "Question:\nGiven a dictionary with keys as strings and integer values, write a Python program to find the key with the highest value. If the input dictionary is empty, return None.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9809,
"level": 1,
"question": "Given a dictionary with keys as strings and integer values, write a Python program to find the key with the highest value. If the input dictionary is empty, return None.",
"split": "train"
} |
def reorganize_books(books: list[tuple[str, int]]) -> list[tuple[str, int]]:
if not books:
return []
return [bk for _, bk in sorted(enumerate(books), key=lambda x: (-x[1][1], x[0]))] | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario\n\nImagine you are developing a utility for a library management system. The library needs a feature to reorganize books on the shelf based on their borrowing frequency. Each book is represented by its borrowing frequency, and the objectiv... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9810,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario\n\nImagine you are developing a utility for a library management system. The library needs a feature to reorganize books on the shelf based on their borrowing frequency. Each book is represented by its bo... |
from collections import Counter
from typing import List
def sort_by_occurrences_and_value(arr: List[int]) -> List[int]:
counts = Counter(arr)
return sorted(arr, key=lambda x: (-counts[x], x)) | simplelr_Package | [
{
"content": "Question:\nCreate a function `sort_by_occurrences_and_value(arr)` which takes a list of integers `arr` and returns a new list sorted by the frequency of occurrences of each number in descending order. If two numbers have the same frequency, they should be sorted by their numerical value in ascendi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9811,
"level": 1,
"question": "Create a function `sort_by_occurrences_and_value(arr)` which takes a list of integers `arr` and returns a new list sorted by the frequency of occurrences of each number in descending order. If two numbers have the same frequency, they should be sorted ... |
def is_palindrome(s):
processed = [char.lower() for char in s if char.isalnum()]
processed_str = ''.join(processed)
return processed_str == processed_str[::-1] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that checks if a given string is a palindrome, considering only alphanumeric characters and ignoring cases. A palindrome is a word, phrase, number, or other sequences of characters which reads the same backward as forward, such as \"madam\" or \"racecar\". For th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9812,
"level": 1,
"question": "Write a Python function that checks if a given string is a palindrome, considering only alphanumeric characters and ignoring cases. A palindrome is a word, phrase, number, or other sequences of characters which reads the same backward as forward, such ... |
def max_manhattan_distance(moves):
current_x = 0
current_y = 0
max_distance = 0
for move in moves:
if move == 'L':
current_x -= 1
elif move == 'R':
current_x += 1
elif move == 'U':
current_y += 1
elif move == 'D':
current_y ... | simplelr_Filter | [
{
"content": "Question:\nDesign a Python function to calculate the Manhattan distance from the origin to the farthest point visited on a 2D plane, given a string of moves. The string consists of characters 'L', 'R', 'U', and 'D', representing left, right, up, and down movements, respectively. The function shoul... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9813,
"level": 1,
"question": "Design a Python function to calculate the Manhattan distance from the origin to the farthest point visited on a 2D plane, given a string of moves. The string consists of characters 'L', 'R', 'U', and 'D', representing left, right, up, and down movement... |
def is_match(w: str, p: str) -> bool:
m = len(p)
n = len(w)
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for i in range(1, m + 1):
for j in range(0, n + 1):
if j == 0:
if p[i-1] == '*' and dp[i-1][j]:
dp[i][j] = True
... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a string \\( w \\) consisting of lowercase English letters, and a pattern \\( p \\) where each character is either a lowercase English letter or a wildcard character '*'. The wildcard character '*' in the pattern matches zero or more of any characters in the string \\( w \... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9814,
"level": 1,
"question": "You are given a string \\( w \\) consisting of lowercase English letters, and a pattern \\( p \\) where each character is either a lowercase English letter or a wildcard character '*'. The wildcard character '*' in the pattern matches zero or more of a... |
def sum_of_gcds(n):
if n < 2:
return 0
# Compute Euler's totient function for all numbers up to n
phi = list(range(n + 1))
for i in range(2, n + 1):
if phi[i] == i: # i is prime
for j in range(i, n + 1, i):
phi[j] = phi[j] // i * (i - 1)
# Compu... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the sum of the greatest common divisors (GCD) of all pairs (i, j) where 1 ≤ i < j ≤ n, and n is a positive integer.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9815,
"level": 1,
"question": "Write a python function to calculate the sum of the greatest common divisors (GCD) of all pairs (i, j) where 1 ≤ i < j ≤ n, and n is a positive integer.",
"split": "train"
} |
def apply_operations(arr: list[int], operations: list[tuple[str, int, int]]) -> list[int]:
new_arr = arr.copy()
for op in operations:
op_type, idx, val = op
if op_type == 'add':
new_arr[idx] += val
elif op_type == 'subtract':
new_arr[idx] -= val
elif op_ty... | simplelr_Algorithm | [
{
"content": "Question:\nArray Manipulation Question\n\n**Scenario**: As a developer building data analysis tools, you are often required to preprocess large datasets. One common task is to transform an array of numbers by carrying out specified operations efficiently.\n\n**Task**: Implement a function `apply_o... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9816,
"level": 1,
"question": "Array Manipulation Question\n\n**Scenario**: As a developer building data analysis tools, you are often required to preprocess large datasets. One common task is to transform an array of numbers by carrying out specified operations efficiently.\n\n**Ta... |
def first_duplicate(nums):
seen = set()
for num in nums:
if num in seen:
return num
seen.add(num)
return None | simplelr_Filter | [
{
"content": "Question:\nGiven a list of integers, find the first duplicate.\n\nExample:\nInput: `[1, 2, 3, 4, 5, 6, 7, 8, 6, 9]`\nOutput: `6`\n\nExample:\nInput: `[1, 2, 3, 4, 5, 6, 7, 8, 9]`\nOutput: `None`\n\nHere is a simple solution in Python:\n```python\ndef firstDuplicate(nums):\n seen = set()\n fo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9817,
"level": 1,
"question": "Given a list of integers, find the first duplicate.\n\nExample:\nInput: `[1, 2, 3, 4, 5, 6, 7, 8, 6, 9]`\nOutput: `6`\n\nExample:\nInput: `[1, 2, 3, 4, 5, 6, 7, 8, 9]`\nOutput: `None`\n\nHere is a simple solution in Python:\n```python\ndef firstDuplica... |
def is_prime(n: int) -> bool:
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True | simplelr_Data_Structure | [
{
"content": "Question:\nYou are tasked with enhancing a number validation system that identifies prime numbers. Your goal is to implement an optimized version of a function to check prime numbers. You must ensure that the implemented function is efficient and handles large inputs reasonably well, given the con... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9818,
"level": 1,
"question": "You are tasked with enhancing a number validation system that identifies prime numbers. Your goal is to implement an optimized version of a function to check prime numbers. You must ensure that the implemented function is efficient and handles large in... |
from typing import List
def cocktail_shaker_sort(arr: List[int]) -> List[int]:
n = len(arr)
if n <= 1:
return arr
left = 0
right = n - 1
while left < right:
swapped = False
# Left to right pass
for i in range(left, right):
if arr[i] > a... | simplelr_Data_Structure | [
{
"content": "Question:\n### Cocktail Shaker Sort Assessment\n\n#### Problem Statement\nYou have been provided with an unsorted list of integers. Your task is to implement the Cocktail Shaker Sort algorithm to sort this list in ascending order. The Cocktail Shaker Sort is a variation of Bubble Sort that sorts t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9819,
"level": 1,
"question": "### Cocktail Shaker Sort Assessment\n\n#### Problem Statement\nYou have been provided with an unsorted list of integers. Your task is to implement the Cocktail Shaker Sort algorithm to sort this list in ascending order. The Cocktail Shaker Sort is a va... |
def is_bijective_pattern(pattern: str, string: str) -> bool:
words = string.split()
if len(pattern) != len(words):
return False
p_map = {}
w_map = {}
for p_char, word in zip(pattern, words):
if p_char in p_map:
if p_map[p_char] != word:
return Fa... | simplelr_Data_Structure | [
{
"content": "Question:\n### Prompt:\nGiven a specific pattern characterized by lowercase letters and a string `str` composed of lowercase words separated by a single space, your task is to write a function `is_bijective_pattern(pattern: str, string: str) -> bool` that returns `True` if the string follows the p... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9820,
"level": 1,
"question": "### Prompt:\nGiven a specific pattern characterized by lowercase letters and a string `str` composed of lowercase words separated by a single space, your task is to write a function `is_bijective_pattern(pattern: str, string: str) -> bool` that returns... |
def third_largest(nums):
if len(nums) < 3:
return None
sorted_numbers = sorted(nums, reverse=True)
return sorted_numbers[2] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the third largest number in a list. How can I approach this problem?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9821,
"level": 1,
"question": "Write a python function to find the third largest number in a list. How can I approach this problem?",
"split": "train"
} |
def is_valid_phone_number(phone_number):
if len(phone_number) != 10:
return False
if phone_number[0] in ('0', '1'):
return False
return True | simplelr_Filter | [
{
"content": "Question:\n[Problem:] Given a string of digits, determine if it's a valid phone number.\n\n[Input format:] A string containing only digits.\n\n[Output format:] A boolean value: `True` if the string represents a valid phone number, `False` otherwise.\n\n[Valid phone number definition:] A valid phon... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9822,
"level": 1,
"question": "[Problem:] Given a string of digits, determine if it's a valid phone number.\n\n[Input format:] A string containing only digits.\n\n[Output format:] A boolean value: `True` if the string represents a valid phone number, `False` otherwise.\n\n[Valid pho... |
def extended_fizzbuzz(n: int) -> list:
if type(n) is not int:
raise TypeError("n must be an integer")
if n < 1:
raise ValueError("n must be at least 1")
result = []
for i in range(1, n + 1):
s = ""
if i % 3 == 0:
s += 'Fizz'
if i % 5 == 0:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: FizzBuzz Extended\n\nYou are to implement a function to generate a sequence from 1 to N, following specific rules for replacements. Extend the traditional FizzBuzz problem with an additional condition.\n\n#### Function Signature\n```python\ndef extended_fizzbuzz(n: int) ->... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9823,
"level": 1,
"question": "### Question: FizzBuzz Extended\n\nYou are to implement a function to generate a sequence from 1 to N, following specific rules for replacements. Extend the traditional FizzBuzz problem with an additional condition.\n\n#### Function Signature\n```pytho... |
import sys
import termios
import os
def secure_password_input(prompt: str = "Password: ") -> str:
if os.name != 'posix':
raise OSError("This function is only supported on Unix-based systems.")
fd = sys.stdin.fileno()
old_attr = termios.tcgetattr(fd)
try:
new_attr = list(old_at... | simplelr_Docs | [
{
"content": "Question:\n**Question: Implement a Secure Password Input Function Using `termios`**\n\nYou are required to implement a Python function that secures password input by temporarily disabling the display of characters as they are typed (no echoing). Your function should work on Unix-based systems by u... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9824,
"level": 1,
"question": "**Question: Implement a Secure Password Input Function Using `termios`**\n\nYou are required to implement a Python function that secures password input by temporarily disabling the display of characters as they are typed (no echoing). Your function sho... |
def replace_character(original, to_replace, new_char):
return original.replace(to_replace, new_char) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to format a given string by replacing all occurrences of a specified character with another character. The function should take three parameters: the original string, the character to be replaced, and the new character. It should return the modified string.\nAnswer:\nLe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9825,
"level": 1,
"question": "Write a function to format a given string by replacing all occurrences of a specified character with another character. The function should take three parameters: the original string, the character to be replaced, and the new character. It should retur... |
from typing import List
def optimised_comb_sort(arr: List[int]) -> List[int]:
a = list(arr)
n = len(a)
if n <= 1:
return a
gap = n
swapped = True
while gap != 1 or swapped:
gap = int(gap / 1.3)
if gap < 1:
gap = 1
swapped = False
for i in rang... | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou have been hired by a company to optimize their existing data processing system. After reviewing their code, you noticed that their data is regularly sorted. The current sorting implementation is causing performance issues. You decide to implement a more optimized sorti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9826,
"level": 1,
"question": "### Scenario\nYou have been hired by a company to optimize their existing data processing system. After reviewing their code, you noticed that their data is regularly sorted. The current sorting implementation is causing performance issues. You decide ... |
def find_maximum(nums):
if not nums:
return None
max_num = nums[0]
for num in nums[1:]:
if num > max_num:
max_num = num
return max_num | simplelr_Filter | [
{
"content": "Question:\nDesign a simple algorithm to find the maximum number in a list of integers. The algorithm should be efficient and easy to understand. Explain each step of the algorithm and provide a brief code snippet in Python to demonstrate its implementation.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9827,
"level": 1,
"question": "Design a simple algorithm to find the maximum number in a list of integers. The algorithm should be efficient and easy to understand. Explain each step of the algorithm and provide a brief code snippet in Python to demonstrate its implementation.",
"... |
def sortArrayByParity(arr):
evens = []
odds = []
for num in arr:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens + odds | simplelr_Apps | [
{
"content": "Question:\nGiven an array of integers, sort the array such that all the even numbers appear before the odd numbers, while maintaining the relative order of the even and odd numbers.\n\nFor example:\n\n* `sortArrayByParity([3, 1, 2, 4])` should return `[2, 4, 3, 1]`\n* `sortArrayByParity([0, 5, 7, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9828,
"level": 1,
"question": "Given an array of integers, sort the array such that all the even numbers appear before the odd numbers, while maintaining the relative order of the even and odd numbers.\n\nFor example:\n\n* `sortArrayByParity([3, 1, 2, 4])` should return `[2, 4, 3, 1... |
def list_to_semi_comma_string(lst):
return f';{",".join(map(str, lst))};' | simplelr_Filter | [
{
"content": "Question:\nHow can I create a Python function that converts a list of integers to a comma-separated string, but also adds a semicolon at the beginning and the end of the string? For example, the list `[1, 2, 3]` should be converted to `\";1,2,3;\"`.\nAnswer:\nLet's think step by step.\n",
"rol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9829,
"level": 1,
"question": "How can I create a Python function that converts a list of integers to a comma-separated string, but also adds a semicolon at the beginning and the end of the string? For example, the list `[1, 2, 3]` should be converted to `\";1,2,3;\"`.",
"split": ... |
def remove_duplicates(dict_list, key):
seen = set()
unique_list = []
for d in dict_list:
current_key = d[key]
if current_key not in seen:
seen.add(current_key)
unique_list.append(d)
return unique_list
# Example usage:
people = [
{'name': 'Alice', 'age': 25},
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove duplicates from a list of dictionaries in Python based on a specific key. For example, given a list of dictionaries where each dictionary represents a person, with a 'name' and 'age' key, how can I remove duplicate entries based on the 'name' key?\nAnsw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9830,
"level": 1,
"question": "Write a python function to remove duplicates from a list of dictionaries in Python based on a specific key. For example, given a list of dictionaries where each dictionary represents a person, with a 'name' and 'age' key, how can I remove duplicate ent... |
def is_interleave(s1, s2, s3):
if len(s3) != len(s1) + len(s2):
return False
m, n = len(s1), len(s2)
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
if ... | simplelr_Filter | [
{
"content": "Question:\nDefine a Python function that takes three string inputs: `s1`, `s2`, and `s3`. The function should return `True` if `s3` can be formed by interleaving the characters of `s1` and `s2` in any order, maintaining the relative order of characters within each string. The function should retur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9831,
"level": 1,
"question": "Define a Python function that takes three string inputs: `s1`, `s2`, and `s3`. The function should return `True` if `s3` can be formed by interleaving the characters of `s1` and `s2` in any order, maintaining the relative order of characters within eac... |
def count_adjacent_pairs(ball_colors):
count = 0
for i in range(len(ball_colors) - 1):
if ball_colors[i] == ball_colors[i + 1]:
count += 1
return count
| simplelr_Taco | [
{
"content": "Question:\nYou are given a list of colored balls. Your task is to create a function `count_adjacent_pairs` that will take a list of strings as input, where each string represents the color of a ball. The function should return the number of adjacent pairs of balls that have the same color.\n\nExam... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9832,
"level": 1,
"question": "You are given a list of colored balls. Your task is to create a function `count_adjacent_pairs` that will take a list of strings as input, where each string represents the color of a ball. The function should return the number of adjacent pairs of ball... |
from typing import List
def min_energy_cost(grid: List[List[int]]) -> int:
if not grid:
raise ValueError("Grid is empty")
for row in grid:
for num in row:
if num < 0:
raise ValueError("Energy cost cannot be negative")
m = len(grid)
n = len(grid[0])
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nImagine you are working on a robot automation system. One of the tasks involves guiding the robot through a path, represented as a grid of cells. Each cell in the grid has a specific energy cost associated with moving through it. The robo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9833,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario\nImagine you are working on a robot automation system. One of the tasks involves guiding the robot through a path, represented as a grid of cells. Each cell in the grid has a specific energy cost associat... |
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return (seen[complement], i)
seen[num] = i
return None | simplelr_Evol | [
{
"content": "Question:\nWrite a function `two_sum(nums, target)` that takes in a list of integers `nums` and an integer `target`. The function should return a tuple of indices of two numbers such that they add up to the target. You may assume that each input would have exactly one solution, and you may not use... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9834,
"level": 1,
"question": "Write a function `two_sum(nums, target)` that takes in a list of integers `nums` and an integer `target`. The function should return a tuple of indices of two numbers such that they add up to the target. You may assume that each input would have exactl... |
def max_overlapping_flights(flights):
events = []
for s, e in flights:
events.append((s, 1))
events.append((e, -1))
events.sort()
current = 0
max_flights = 0
for time, val in events:
current += val
if current > max_flights:
max_flights = current
re... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n**Context**:\nYou are given a list of airline flight times. Each airline provides a start time and an end time for their available flights as tuples of integers representing hours in a 24-hour format (e.g., (13, 15) means the flight is available from 1 ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9835,
"level": 1,
"question": "### Coding Assessment Question\n\n**Context**:\nYou are given a list of airline flight times. Each airline provides a start time and an end time for their available flights as tuples of integers representing hours in a 24-hour format (e.g., (13, 15) me... |
def process_numbers(integer_list):
"""
Process a list of integers by filtering, sorting, and computing the sum.
:param integer_list: List of integers
:return: Dictionary with 'sorted_list' and 'sum' of the integers
"""
# Filter integers retaining only the even ones
filtered_integers = [... | simplelr_Package | [
{
"content": "Question:\nYou are given a function that filters and processes a list of integers based on specific conditions. The function accepts a list of integers and performs the following operations:\n\n1. **Filter the Integers**: Retain only the integers that are even.\n2. **Sort the Integers**: Sort the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9836,
"level": 1,
"question": "You are given a function that filters and processes a list of integers based on specific conditions. The function accepts a list of integers and performs the following operations:\n\n1. **Filter the Integers**: Retain only the integers that are even.\n... |
def print_all_strings_with_all_digits(strings, num):
for string in strings:
if all(char in string for char in '0123456789'):
print(f"{string} {num}") | simplelr_Filter | [
{
"content": "Question:\nI'll describe a snippet of code, and I'd like you to write the code based on my description. \n\nI need a function that takes 2 parameters: a list of strings and an integer. The function should iterate through the list of strings, and for each string, it should check if a certain condit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9837,
"level": 1,
"question": "I'll describe a snippet of code, and I'd like you to write the code based on my description. \n\nI need a function that takes 2 parameters: a list of strings and an integer. The function should iterate through the list of strings, and for each string, ... |
from collections import Counter
def is_permutation(s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
return Counter(s1) == Counter(s2) | simplelr_Algorithm | [
{
"content": "Question:\n### Question:\n\n#### String Permutation Checker\n\nA permutation of a string is another string that contains the same characters, only the order of characters can be different. For example, \"abc\" has the following permutations: \"abc\", \"acb\", \"bac\", \"bca\", \"cab\", and \"cba\"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9838,
"level": 1,
"question": "### Question:\n\n#### String Permutation Checker\n\nA permutation of a string is another string that contains the same characters, only the order of characters can be different. For example, \"abc\" has the following permutations: \"abc\", \"acb\", \"b... |
def max_subarray_sum(arr):
if not arr:
return 0 # or raise ValueError("Array is empty")
max_current = max_global = arr[0]
for num in arr[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the largest sum of any contiguous subarray of a given list of integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9839,
"level": 1,
"question": "Write a function to find the largest sum of any contiguous subarray of a given list of integers.",
"split": "train"
} |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def plot_sinwaves():
themes = ['darkgrid', 'whitegrid', 'ticks', 'dark']
contexts = ['paper', 'notebook', 'talk', 'poster']
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
for i in range(4):
ax = axes[i // 2, i %... | simplelr_Docs | [
{
"content": "Question:\n#### Objective\nYour task is to create a `plot_sinwaves` function that demonstrates three core capabilities of the seaborn package:\n1. Applying different themes.\n2. Modifying plot styles temporarily.\n3. Scaling plot elements for various contexts.\n\n#### Problem Statement\n\nImplemen... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9840,
"level": 1,
"question": "#### Objective\nYour task is to create a `plot_sinwaves` function that demonstrates three core capabilities of the seaborn package:\n1. Applying different themes.\n2. Modifying plot styles temporarily.\n3. Scaling plot elements for various contexts.\n\... |
def filter_comments(comments, negative_words):
filtered = []
for comment in comments:
lower_comment = comment.lower()
contains_negative = False
for nw in negative_words:
if nw.lower() in lower_comment:
contains_negative = True
break
if ... | simplelr_Taco | [
{
"content": "Question:\n### Task:\n\nYou have been hired to help a social media company to filter out negative comments from their posts. The application should accept a list of comments and a list of negative words. Your task is to return a list of comments that do not contain any of the negative words.\n\n##... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9841,
"level": 1,
"question": "### Task:\n\nYou have been hired to help a social media company to filter out negative comments from their posts. The application should accept a list of comments and a list of negative words. Your task is to return a list of comments that do not conta... |
def remove_min(stack):
if not stack:
return stack
min_val = stack[0]
min_index = 0
for i in range(1, len(stack)):
if stack[i] < min_val:
min_val = stack[i]
min_index = i
del stack[min_index]
return stack | simplelr_Data_Structure | [
{
"content": "Question:\n#### Context\nYou are implementing a data preprocessing function for an application that requires cleaning up stack-based data structures. One specific requirement is to remove the smallest value from a given stack while retaining other elements in their original order. \n\n#### Task\nW... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9842,
"level": 1,
"question": "#### Context\nYou are implementing a data preprocessing function for an application that requires cleaning up stack-based data structures. One specific requirement is to remove the smallest value from a given stack while retaining other elements in the... |
def remove_duplicates(arr):
seen = set()
result = []
for num in arr:
if num not in seen:
seen.add(num)
result.append(num)
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove duplicates from an array while keeping the order of elements. How would you test this function with a list of integers?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9843,
"level": 1,
"question": "Write a python function to remove duplicates from an array while keeping the order of elements. How would you test this function with a list of integers?",
"split": "train"
} |
def find_min(lst):
if not lst:
raise ValueError("List is empty")
min_val = lst[0]
for num in lst[1:]:
if num < min_val:
min_val = num
return min_val | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the minimum element in a list without using built-in functions like min() and sort().\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9844,
"level": 1,
"question": "Write a python function to find the minimum element in a list without using built-in functions like min() and sort().",
"split": "train"
} |
def count_capitals(sentence):
count = 0
for char in sentence:
if char.isupper():
count += 1
return count | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that calculates the number of capitals in a sentence\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9845,
"level": 1,
"question": "Create a function that calculates the number of capitals in a sentence",
"split": "train"
} |
import math
from itertools import combinations
def are_coprime(lst):
if len(lst) < 2:
raise ValueError("The list must contain at least two integers.")
for a, b in combinations(lst, 2):
if a == 0 and b == 0:
return False
current_gcd = math.gcd(abs(a), abs(b))
if curre... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list of integers and returns a boolean value. The function should return `True` if there are no two integers in the list that are divisible by the same integer greater than 1 (i.e., they are coprime), and `False` otherwise. Make sure to handle exception... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9846,
"level": 1,
"question": "Create a function that takes in a list of integers and returns a boolean value. The function should return `True` if there are no two integers in the list that are divisible by the same integer greater than 1 (i.e., they are coprime), and `False` other... |
from typing import List
def spiral_traversal(mat: List[List[int]]) -> List[int]:
if not mat:
return []
n = len(mat)
m = len(mat[0]) if n > 0 else 0
top = 0
bottom = n - 1
left = 0
right = m - 1
result = []
while top <= bottom and left <= right:
# ... | simplelr_Taco | [
{
"content": "Question:\nGiven a matrix `mat` of size `n x m`, write a function `spiral_traversal(mat)` that returns the spiral order traversal of the matrix.\n\nThe spiral order traversal of a matrix involves starting at the top-left corner and moving right, then down, then left, then up, and repeating these s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9847,
"level": 1,
"question": "Given a matrix `mat` of size `n x m`, write a function `spiral_traversal(mat)` that returns the spiral order traversal of the matrix.\n\nThe spiral order traversal of a matrix involves starting at the top-left corner and moving right, then down, then l... |
def find_pair_with_sum(nums, target):
seen = set()
for num in nums:
complement = target - num
if complement in seen:
return (complement, num)
seen.add(num)
return None | simplelr_Evol | [
{
"content": "Question:\nCreate a function in Python that takes a list of integers and a target integer. The function should determine if there are two distinct numbers in the list that add up to the target integer. If such a pair exists, return a tuple of the two numbers; if no such pair exists, return None. E... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9848,
"level": 1,
"question": "Create a function in Python that takes a list of integers and a target integer. The function should determine if there are two distinct numbers in the list that add up to the target integer. If such a pair exists, return a tuple of the two numbers; if ... |
def binary_search(sorted_list, target):
low = 0
high = len(sorted_list) - 1
while low <= high:
mid = (low + high) // 2
if sorted_list[mid] == target:
return mid
elif target < sorted_list[mid]:
high = mid - 1
else:
low = mid + 1
return -... | simplelr_Filter | [
{
"content": "Question:\nGiven a list of sorted integers, implement a binary search algorithm to find the index of a given value. If the value is not present in the list, return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9849,
"level": 1,
"question": "Given a list of sorted integers, implement a binary search algorithm to find the index of a given value. If the value is not present in the list, return -1.",
"split": "train"
} |
def find_max(nums):
"""
This function finds the maximum number in a given list of integers.
Args:
nums (list): A list of integers.
Returns:
int: The maximum integer in the list.
Raises:
TypeError: If the input is not a list or if any element in the list is not an integer.
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum number in an array of integers. You should also include the functionality to handle any exceptions that might arise during the execution of the function.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9850,
"level": 1,
"question": "Write a python function to find the maximum number in an array of integers. You should also include the functionality to handle any exceptions that might arise during the execution of the function.",
"split": "train"
} |
def shuffle_string(s, indices):
result = [''] * len(s)
for i in range(len(s)):
result[indices[i]] = s[i]
return ''.join(result) | simplelr_Leetcode | [
{
"content": "Question:\nGiven a string `s` that consists of lowercase letters and a list of indices `indices` where `indices` is a permutation of the string length, [0, 1, 2, ..., len(s)-1], shuffle the string such that the character at the `i`-th position moves to `indices[i]` in the shuffled string. Return t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9851,
"level": 1,
"question": "Given a string `s` that consists of lowercase letters and a list of indices `indices` where `indices` is a permutation of the string length, [0, 1, 2, ..., len(s)-1], shuffle the string such that the character at the `i`-th position moves to `indices[i... |
def twoSum(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 a list of integers, write a function that returns the indices of the two numbers that add up to a given target. You can assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.\n\nExample:\n\nInput:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9852,
"level": 1,
"question": "Given a list of integers, write a function that returns the indices of the two numbers that add up to a given target. You can assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer ... |
import re
def extract_first_number(s):
match = re.search(r'-?\d+', s)
return int(match.group(0)) if match else -1 | simplelr_Filter | [
{
"content": "Question:\nI need help with a Python function that can extract the first occurrence of a number in a given string and return it as an integer. If no number is found, the function should return -1. Can you provide a solution?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9853,
"level": 1,
"question": "I need help with a Python function that can extract the first occurrence of a number in a given string and return it as an integer. If no number is found, the function should return -1. Can you provide a solution?",
"split": "train"
} |
from typing import List
def maxProfit(prices: List[int]) -> int:
if len(prices) < 2:
return 0
max_profit = 0
min_price = prices[0]
for price in prices[1:]:
current_profit = price - min_price
if current_profit > max_profit:
max_profit = current_profit
if price... | simplelr_Taco | [
{
"content": "Question:\nYou are given an integer array representing the daily stock prices of a certain company over a period of n days, where the price of the stock on day i is given by prices[i]. You are allowed to perform at most one transaction (i.e., buy one and sell one share of the stock). Your goal is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9854,
"level": 1,
"question": "You are given an integer array representing the daily stock prices of a certain company over a period of n days, where the price of the stock on day i is given by prices[i]. You are allowed to perform at most one transaction (i.e., buy one and sell one... |
def find_anagram_substring(s1, s2):
if len(s2) > len(s1):
return -1
len_s2 = len(s2)
# Initialize count arrays with size 256 for all extended ASCII characters
count_s2 = [0] * 256
count_window = [0] * 256
for i in range(len_s2):
count_s2[ord(s2[i])] += 1
for i in range(len_... | simplelr_Filter | [
{
"content": "Question:\nGiven two strings s1 and s2, how can you check if s2 is an anagram of any substring of s1 and get the index of the beginning of the substring in s1 if it exists?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9855,
"level": 1,
"question": "Given two strings s1 and s2, how can you check if s2 is an anagram of any substring of s1 and get the index of the beginning of the substring in s1 if it exists?",
"split": "train"
} |
def complement_dna(s):
trans_table = str.maketrans('ATCG', 'TAGC')
return s.translate(trans_table) | simplelr_Filter | [
{
"content": "Question:\nCreate a function that returns the compliment of a DNA string (A-T and G-C) by mapping each letter of the DNA string to its compliment.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9856,
"level": 1,
"question": "Create a function that returns the compliment of a DNA string (A-T and G-C) by mapping each letter of the DNA string to its compliment.",
"split": "train"
} |
from collections import Counter
def canFormPalindrome(s):
counts = Counter(s)
odd_counts = sum(1 for cnt in counts.values() if cnt % 2 != 0)
return odd_counts <= 1
| simplelr_Taco | [
{
"content": "Question:\nWrite a function `canFormPalindrome(s)` that takes a string `s` as input and returns `true` if any permutation of `s` could form a palindrome, otherwise returns `false`. A string can form a palindrome if at most one character appears an odd number of times. For example, the string \"rac... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9857,
"level": 1,
"question": "Write a function `canFormPalindrome(s)` that takes a string `s` as input and returns `true` if any permutation of `s` could form a palindrome, otherwise returns `false`. A string can form a palindrome if at most one character appears an odd number of t... |
import heapq
def k_smallest_pairs(nums1, nums2, k):
if not nums1 or not nums2:
return []
heap = []
visited = set()
i, j = 0, 0
heapq.heappush(heap, (nums1[i] + nums2[j], i, j))
visited.add((i, j))
result = []
for _ in range(k):
if not heap:
break
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given two integer arrays `nums1` and `nums2` sorted in non-decreasing order and an integer `k`. Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. Find the k pairs `(u1, v1), (u2, v2), ..., (uk, vk)` with the smallest... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9858,
"level": 1,
"question": "You are given two integer arrays `nums1` and `nums2` sorted in non-decreasing order and an integer `k`. Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. Find the k pairs `(u1, v1), (u2, v2... |
def can_reach_end(arr, k):
for i in range(len(arr) - 1):
if arr[i+1] - arr[i] != k:
return False
return True | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **sorted** array `arr` of integers where each element is **distinct** and an integer `k`. Imagine you start at `arr[0]` and want to jump to `arr[arr.length - 1]` (the end of the array). You can only jump to the next index if the difference between the current element and... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9859,
"level": 1,
"question": "You are given a **sorted** array `arr` of integers where each element is **distinct** and an integer `k`. Imagine you start at `arr[0]` and want to jump to `arr[arr.length - 1]` (the end of the array). You can only jump to the next index if the differe... |
def triangle(n):
m = (n - 1) // 2
max_length = 2 * m + 1
result = []
for i in range(n):
distance = abs(i - m)
num_hashes = 2 * (m - distance) + 1
spaces = (max_length - num_hashes) // 2
line = ' ' * spaces + '#' * num_hashes + ' ' * spaces
result.append(line)
... | simplelr_Taco | [
{
"content": "Question:\nTriangle Pattern\n\nYou will get an odd integer n (>= 3) and your task is to draw an isosceles triangle. Each line is separated with '\\n'.\n\nUse the following characters: # and ' ' (space)\n\ne.g.:\n\n #\n # ###\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9860,
"level": 1,
"question": "Triangle Pattern\n\nYou will get an odd integer n (>= 3) and your task is to draw an isosceles triangle. Each line is separated with '\\n'.\n\nUse the following characters: # and ' ' (space)\n\ne.g.:\n\n #\n ... |
import itertools
def list_combinations(lists):
return [list(comb) for comb in itertools.product(*lists)] | simplelr_Filter | [
{
"content": "Question:\nI've been trying to solve a Python exercise that asks to create a function that returns a list of all the possible combinations of a given list of lists. \n\nHere is an example:\ninput = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]\noutput = [[1, 4, 6], [1, 4, 7], [1, 4, 8], [1, 4, 9], \n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9861,
"level": 1,
"question": "I've been trying to solve a Python exercise that asks to create a function that returns a list of all the possible combinations of a given list of lists. \n\nHere is an example:\ninput = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]\noutput = [[1, 4, 6], [1, 4, 7]... |
from typing import List
def has_subsequence_with_sum(arr: List[int], target: int) -> bool:
current_sum = 0
prefix_sums = {0}
for num in arr:
current_sum += num
if (current_sum - target) in prefix_sums:
return True
prefix_sums.add(current_sum)
return False | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question:\n\n#### Scenario:\nYou are a software developer at a data analysis firm. Your team is creating a tool that needs to efficiently identify anomalies in data streams. Specifically, you need to verify if a sequence of numbers contains a subsequence where the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9862,
"level": 1,
"question": "### Coding Assessment Question:\n\n#### Scenario:\nYou are a software developer at a data analysis firm. Your team is creating a tool that needs to efficiently identify anomalies in data streams. Specifically, you need to verify if a sequence of number... |
def prime_factors(n):
factors = []
if n < 0:
factors.append(-1)
n = abs(n)
if n == 1:
return factors
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
... | simplelr_Filter | [
{
"content": "Question:\nIncrease the difficulty of the given programming test question by requiring the implementation to handle both positive and negative input numbers, and optimize the process of identifying prime factors.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9863,
"level": 1,
"question": "Increase the difficulty of the given programming test question by requiring the implementation to handle both positive and negative input numbers, and optimize the process of identifying prime factors.",
"split": "train"
} |
def max_coins(grid):
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
dp = [[0 for _ in range(n)] for _ in range(m)]
dp[0][0] = grid[0][0]
for j in range(1, n):
dp[0][j] = dp[0][j-1] + grid[0][j]
for i in range(1, m):
dp[i][0] = dp[i-1][0]... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a matrix of `m x n` size representing a field of coins, where each cell contains a non-negative integer representing the number of coins in that cell. You need to start from the top-left cell and move to the bottom-right cell, only being able to move to the right or down a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9864,
"level": 1,
"question": "You are given a matrix of `m x n` size representing a field of coins, where each cell contains a non-negative integer representing the number of coins in that cell. You need to start from the top-left cell and move to the bottom-right cell, only being ... |
def string_to_integer(s):
cleaned = []
if not s:
return 0
# Check for negative sign at the beginning
if s[0] == '-':
cleaned.append('-')
s = s[1:]
else:
# Check for positive sign at the beginning
if s[0] == '+':
s = s[1:]
# Process each charact... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to convert a string to an integer. If the string contains non-numeric characters, those should be removed before conversion. Additionally, handle negative numbers correctly.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9865,
"level": 1,
"question": "Write a python function to convert a string to an integer. If the string contains non-numeric characters, those should be removed before conversion. Additionally, handle negative numbers correctly.",
"split": "train"
} |
def update_inventory(inventory, sales):
total_revenue = 0
errors = []
# Create a copy of the inventory to avoid modifying the original
inventory_copy = [list(item) for item in inventory]
for item_name, quantity_sold in sales:
found = False
for i in range(len(inventory_copy)):
... | simplelr_Evol | [
{
"content": "Question:\nCreate a Python function to simulate a simplified inventory management system. The function should receive a list of tuples, where each tuple represents an item with its name (str), quantity (int), and price per unit (float). The function needs to update the quantity of items based on s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9866,
"level": 1,
"question": "Create a Python function to simulate a simplified inventory management system. The function should receive a list of tuples, where each tuple represents an item with its name (str), quantity (int), and price per unit (float). The function needs to upda... |
def xor_binary_strings(a, b):
max_len = max(len(a), len(b))
a_padded = a.zfill(max_len)
b_padded = b.zfill(max_len)
result = []
for a_bit, b_bit in zip(a_padded, b_padded):
xor = int(a_bit) ^ int(b_bit)
result.append(str(xor))
return ''.join(result) | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to implement the XOR operation between two binary strings, returning the XOR result as a binary string. Ensure that the function handles binary strings of different lengths.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9867,
"level": 1,
"question": "Write a function to implement the XOR operation between two binary strings, returning the XOR result as a binary string. Ensure that the function handles binary strings of different lengths.",
"split": "train"
} |
from collections import Counter
def evenCharSubseq(s):
freq = Counter(s)
total = 0
for count in freq.values():
if count % 2 == 0:
total += count
else:
total += count - 1
return total
| simplelr_Taco | [
{
"content": "Question:\nYou are given a string s consisting of lowercase and uppercase alphabets. We need to find the length of the longest subsequence of s where each character appears an even number of times.\n\nFor example, for the string \"abbac\", the longest subsequence where each character appears an ev... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9868,
"level": 1,
"question": "You are given a string s consisting of lowercase and uppercase alphabets. We need to find the length of the longest subsequence of s where each character appears an even number of times.\n\nFor example, for the string \"abbac\", the longest subsequence... |
def product_except_self(nums):
n = len(nums)
if n == 0:
return []
prefix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]
suffix = [1] * n
for i in range(n-2, -1, -1):
suffix[i] = suffix[i+1] * nums[i+1]
return [prefix[i] * suffix[i] for i in range(... | simplelr_Filter | [
{
"content": "Question:\nI need to write a Python function that takes a list of integers and returns a new list where each element is the product of all the other elements in the original list except itself. How can I do this without using division?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9869,
"level": 1,
"question": "I need to write a Python function that takes a list of integers and returns a new list where each element is the product of all the other elements in the original list except itself. How can I do this without using division?",
"split": "train"
} |
def min_path_sum(grid: list) -> int:
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
if m == 1 and n == 1:
return grid[0][0]
# Process the first row
for j in range(1, n):
grid[0][j] += grid[0][j-1]
# Process the first column
for i in ... | simplelr_Algorithm | [
{
"content": "Question:\n### Efficient Matrix Path Sum Coding Challenge\n\n**Context**:\nAs a software engineer, you have been provided a 2D grid (matrix) filled with non-negative integers. Your task is to find the minimum path sum from the top-left corner to the bottom-right corner of the matrix, where you can... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9870,
"level": 1,
"question": "### Efficient Matrix Path Sum Coding Challenge\n\n**Context**:\nAs a software engineer, you have been provided a 2D grid (matrix) filled with non-negative integers. Your task is to find the minimum path sum from the top-left corner to the bottom-right ... |
def find_frequent_words(words, k):
if not words or k <= 0:
return []
from collections import defaultdict
word_counts = defaultdict(int)
for word in words:
word_counts[word] += 1
unique_words = list(word_counts.keys())
unique_words.sort(key=lambda x: (-word_counts[x], x)... | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function named `find_frequent_words` that takes a list of strings called `words` and an integer `k` and returns the `k` most frequent words from the list. If there is a tie, return the words with the smallest alphabetical order first. \n\nTo solve this problem, you should... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9871,
"level": 1,
"question": "Write a Python function named `find_frequent_words` that takes a list of strings called `words` and an integer `k` and returns the `k` most frequent words from the list. If there is a tie, return the words with the smallest alphabetical order first. \n... |
from typing import List, Tuple, Dict
from datetime import datetime
from collections import defaultdict
def summarize_transactions(transactions: List[Tuple[int, float]]) -> Dict[str, float]:
result = defaultdict(float)
for timestamp, amount in transactions:
dt = datetime.utcfromtimestamp(timestamp)
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement:\n\nImagine you are working on data processing software for an e-commerce platform. One of the tasks involves summarizing transaction details. Given the timestamps of transactions in the form of UNIX time, write a function to categorize these transactions by month ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9872,
"level": 1,
"question": "### Problem Statement:\n\nImagine you are working on data processing software for an e-commerce platform. One of the tasks involves summarizing transaction details. Given the timestamps of transactions in the form of UNIX time, write a function to cate... |
def most_frequent_vehicle(sequence: str) -> str:
vehicle_data = {}
for index, c in enumerate(sequence):
if c not in vehicle_data:
vehicle_data[c] = {'count': 1, 'first_index': index}
else:
vehicle_data[c]['count'] += 1
max_count = max(vehicle_data[c]['count'] for... | simplelr_Code_Contests | [
{
"content": "Question:\nGiven a string representing a sequence of car types arriving at a parking lot ('S' for sedan, 'T' for truck, 'M' for motorcycle, 'V' for van), you are to determine which type of vehicle is the most frequent in the sequence. If there's a tie, return the type that appears first in the pro... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9873,
"level": 1,
"question": "Given a string representing a sequence of car types arriving at a parking lot ('S' for sedan, 'T' for truck, 'M' for motorcycle, 'V' for van), you are to determine which type of vehicle is the most frequent in the sequence. If there's a tie, return the... |
from functools import cmp_to_key
from typing import List, Callable
def custom_sort(lst: List[int], cmp: Callable[[int, int], int]) -> List[int]:
return sorted(lst, key=cmp_to_key(cmp)) | simplelr_Algorithm | [
{
"content": "Question:\n### Sorting Integers with Custom Comparator\n\nYou are given a list of integers and a custom comparator function that defines a specific sorting order based on some criteria. Your task is to write a function that sorts the integers according to the provided comparator.\n\n#### Objective... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9874,
"level": 1,
"question": "### Sorting Integers with Custom Comparator\n\nYou are given a list of integers and a custom comparator function that defines a specific sorting order based on some criteria. Your task is to write a function that sorts the integers according to the pro... |
from typing import List, Tuple
def top_books(ratings: List[Tuple[str, int, float]], min_ratings: int) -> List[str]:
book_data = {}
for title, user_id, rating in ratings:
if title not in book_data:
book_data[title] = [rating, 1]
else:
book_data[title][0] += rating
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou have been hired to develop a recommendation engine for an online book store. Your first task is to build a function that identifies books with the highest average user rating. Each book can have multiple ratings from different users, and you'll have to ensur... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9875,
"level": 1,
"question": "### Problem Statement\n\nYou have been hired to develop a recommendation engine for an online book store. Your first task is to build a function that identifies books with the highest average user rating. Each book can have multiple ratings from differ... |
def count_rectangles(w: int, h: int) -> int:
return (w * (w + 1) // 2) * (h * (h + 1) // 2) | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nA rectangle is defined by its width `w` and height `h`. Your task is to compute the total number of rectangles of all possible sizes that can be formed within a given rectangle. A rectangle includes both horizontal and vertical alignments. For instance, within a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9876,
"level": 1,
"question": "### Problem Statement\n\nA rectangle is defined by its width `w` and height `h`. Your task is to compute the total number of rectangles of all possible sizes that can be formed within a given rectangle. A rectangle includes both horizontal and vertical... |
def length_of_lis(nums):
if not nums:
return 0
dp = [1] * len(nums)
max_length = 1
for i in range(1, len(nums)):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
if dp[i] > max_length:
max_length = dp[i]
return max... | simplelr_Filter | [
{
"content": "Question:\nI have a list of numbers. I want to find the length of the longest increasing subsequence (LIS) in the list. I've heard that dynamic programming can be used for this. \n\nHow can I implement a function to find the length of the LIS using dynamic programming in Python?\nAnswer:\nLet's th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9877,
"level": 1,
"question": "I have a list of numbers. I want to find the length of the longest increasing subsequence (LIS) in the list. I've heard that dynamic programming can be used for this. \n\nHow can I implement a function to find the length of the LIS using dynamic progra... |
from typing import List
def remove_duplicates(nums: List[int]) -> int:
if not nums:
return 0
write_pointer = 0
for read_pointer in range(1, len(nums)):
if nums[read_pointer] != nums[write_pointer]:
write_pointer += 1
nums[write_pointer] = nums[read_pointer]
retur... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given an integer array `nums` sorted in non-decreasing order. Your task is to determine the number of unique elements in the array after removing all duplicates in-place. After removing the duplicates, the unique elements should still be in non-decreasing order and must occupy t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9878,
"level": 1,
"question": "You are given an integer array `nums` sorted in non-decreasing order. Your task is to determine the number of unique elements in the array after removing all duplicates in-place. After removing the duplicates, the unique elements should still be in non... |
def first_n_characters(s, n):
n = max(n, 0)
return s[:n] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two arguments, a string and an integer n. The function should return the first n characters of the string. If the string is shorter than n, return the entire string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9879,
"level": 1,
"question": "Create a function that takes two arguments, a string and an integer n. The function should return the first n characters of the string. If the string is shorter than n, return the entire string.",
"split": "train"
} |
def modifyArray(nums):
# Step 1: Create a frequency map
freq = {}
for num in nums:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
# Step 2: Create the filtered list based on frequency
filtered = []
for num in nums:
if freq[num] <= 2:
... | simplelr_Taco | [
{
"content": "Question:\nGiven an integer array nums, modify it according to the following rules:\n- Remove all instances of an element if it appears more than twice in the array.\n- Reverse the order of the elements in the resulting array.\n\nExample:\nInput:\nnums = [1, 2, 3, 2, 3, 3, 4]\n\nOutput:\n[4, 2, 3,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9880,
"level": 1,
"question": "Given an integer array nums, modify it according to the following rules:\n- Remove all instances of an element if it appears more than twice in the array.\n- Reverse the order of the elements in the resulting array.\n\nExample:\nInput:\nnums = [1, 2, 3... |
def count_primes(limit):
if limit < 2:
return 0
sieve = [True] * (limit + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(limit ** 0.5) + 1):
if sieve[i]:
for j in range(i * i, limit + 1, i):
sieve[j] = False
return sum(sieve) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the number of prime numbers up to a given limit.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9881,
"level": 1,
"question": "Write a python function to find the number of prime numbers up to a given limit.",
"split": "train"
} |
from typing import List, Dict
import pandas as pd
def identify_fraudulent_activity(transactions: List[Dict], threshold: int, time_period: str) -> List[str]:
"""
Args:
transactions (List[dict]): List of transaction records.
threshold (int): Maximum number of transactions allowed within the given... | simplelr_Package | [
{
"content": "Question:\nYou are given a list of transaction records for various customers. Each record contains a customer ID, transaction amount, and timestamp. Your task is to analyze the transactions and identify fraudulent activities. A fraudulent activity is defined as any customer having more than a spec... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9882,
"level": 1,
"question": "You are given a list of transaction records for various customers. Each record contains a customer ID, transaction amount, and timestamp. Your task is to analyze the transactions and identify fraudulent activities. A fraudulent activity is defined as a... |
def find_median(lst):
sorted_lst = sorted(lst)
n = len(sorted_lst)
median_index = n // 2
return sorted_lst[median_index] | simplelr_Apps | [
{
"content": "Question:\nWrite a function that finds the median of a list of integers. The list will always contain an odd number of elements. The median is the middle value when the numbers are arranged in sorted order.\n\nExamples:\n```code\n[1, 3, 4, 2, 5] => 3\n[7, 1, 5, 3, 9] => 5\n[99, -2, 56, 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9883,
"level": 1,
"question": "Write a function that finds the median of a list of integers. The list will always contain an odd number of elements. The median is the middle value when the numbers are arranged in sorted order.\n\nExamples:\n```code\n[1, 3, 4, 2, 5] => 3\n[7, 1,... |
def watered_cells(n: int, r: int) -> int:
c = (n - 1) // 2
max_distance = 2 * c
if r >= max_distance:
return n * n
else:
total = 0
for x in range(0, c + 1):
if x > r:
continue
remaining = r - x
if remaining < 0:
... | simplelr_Leetcode | [
{
"content": "Question:\nA gardener is planning to design a square garden with a water sprinkler system installed at the center of the garden. The garden will be represented by an `n x n` grid and the sprinkler at the center can water its surrounding cells. Given an integer `n` representing the size of the gard... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9884,
"level": 1,
"question": "A gardener is planning to design a square garden with a water sprinkler system installed at the center of the garden. The garden will be represented by an `n x n` grid and the sprinkler at the center can water its surrounding cells. Given an integer `n... |
def sequential_search(arr, target):
"""
Perform a sequential search on the array to find the target element.
Arguments:
arr -- list of elements to search through
target -- element to be searched for in the array
Returns:
index -- the index of the target element in the array, or -1 if the t... | simplelr_Package | [
{
"content": "Question:\nYou are to design a function `sequential_search(arr, target)` using Python that performs a sequential search on an array to find the index of a target element. The function should return the first index of the target element if it is found, and `-1` if the element is not present in the ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9885,
"level": 1,
"question": "You are to design a function `sequential_search(arr, target)` using Python that performs a sequential search on an array to find the index of a target element. The function should return the first index of the target element if it is found, and `-1` if... |
def square_list(numbers):
return [x ** 2 for x in numbers] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python code snippet that takes a list of integers and returns a list containing the squared values of those integers.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9886,
"level": 1,
"question": "Write a Python code snippet that takes a list of integers and returns a list containing the squared values of those integers.",
"split": "train"
} |
def binary_search(lst: list[int], target: int) -> int:
"""
Performs a binary search on a sorted list of integers to find the index of the target.
Args:
lst: A sorted list of integers.
target: The integer to search for.
Returns:
The index of the target if found; -1 if no... | simplelr_Filter | [
{
"content": "Question:\nWrite a program in Python that performs a binary search on a sorted list of integers. The program should take a list of integers and a target integer as input, and return the index of the target if found, or -1 if the target is not in the list. Ensure your code is well-commented and fol... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9887,
"level": 1,
"question": "Write a program in Python that performs a binary search on a sorted list of integers. The program should take a list of integers and a target integer as input, and return the index of the target if found, or -1 if the target is not in the list. Ensure ... |
def most_common_string(words):
counts = {}
unique_words = []
for word in words:
if word not in counts:
counts[word] = 1
unique_words.append(word)
else:
counts[word] += 1
max_count = -1
result = None
for word in unique_words:
if counts[w... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of strings and returns the string that is the most common, most frequently occurring, in the array. If there is a tie, the first one that appears in the array should be returned. You may assume that there will always be at least one word in the arra... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9888,
"level": 1,
"question": "Create a function that takes an array of strings and returns the string that is the most common, most frequently occurring, in the array. If there is a tie, the first one that appears in the array should be returned. You may assume that there will alwa... |
from typing import List
def summarize_ranges(array: List[int]) -> List[str]:
if not array:
return []
result = []
start = end = array[0]
for num in array[1:]:
if num == end + 1:
end = num
else:
if start == end:
result.append(f"{st... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a sorted list of integers without duplicates. You need to implement a function that summarizes its ranges. A range is a sequence of two or more consecutive integers.\n\n**Function Signature**:\n```python\ndef summarize_ranges(array: List[int]) -> List[str]:\n```\n\n**Input... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9889,
"level": 1,
"question": "You are given a sorted list of integers without duplicates. You need to implement a function that summarizes its ranges. A range is a sequence of two or more consecutive integers.\n\n**Function Signature**:\n```python\ndef summarize_ranges(array: List[... |
def fibonacci_list(n):
if n <= 0:
return []
elif n == 1:
return [0]
else:
fibs = [0, 1]
while len(fibs) < n:
next_num = fibs[-1] + fibs[-2]
fibs.append(next_num)
return fibs | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that generates a list containing the first n Fibonacci numbers. The function should be named `fibonacci_list` and should take one parameter, `n`, which is the number of Fibonacci numbers to generate. The Fibonacci sequence starts with 0 and 1, and each subsequent numbe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9890,
"level": 1,
"question": "Create a function that generates a list containing the first n Fibonacci numbers. The function should be named `fibonacci_list` and should take one parameter, `n`, which is the number of Fibonacci numbers to generate. The Fibonacci sequence starts with... |
from typing import List
def custom_sort(arr: List[int]) -> List[int]:
arr_copy = arr.copy()
n = len(arr_copy)
for i in range(n - 1):
swapped = False
for j in range(n - i - 1):
if arr_copy[j] > arr_copy[j + 1]:
arr_copy[j], arr_copy[j + 1] = arr_copy[j + 1], arr_c... | simplelr_Algorithm | [
{
"content": "Question:\n### Sorting and Swapping Adjacent Elements\n\n#### Objective\n\nYou are required to implement a function that sorts an input list of integers in non-decreasing order using a custom sorting algorithm. The algorithm only allows adjacent elements to be swapped if they are out of order.\n\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9891,
"level": 1,
"question": "### Sorting and Swapping Adjacent Elements\n\n#### Objective\n\nYou are required to implement a function that sorts an input list of integers in non-decreasing order using a custom sorting algorithm. The algorithm only allows adjacent elements to be sw... |
def can_split_array(arr, threshold):
sum_total = sum(arr)
if sum_total <= 2 * threshold:
return False
current_sum = 0
for i in range(len(arr) - 1):
current_sum += arr[i]
if current_sum > threshold and (sum_total - current_sum) > threshold:
return True
return False | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `arr` and an integer `threshold`. You need to determine if it is possible to split `arr` into two non-empty subarrays such that the sum of the elements in each subarray is greater than `threshold`. Return `true` if it is possible, and `false` otherwise... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9892,
"level": 1,
"question": "You are given an array of integers `arr` and an integer `threshold`. You need to determine if it is possible to split `arr` into two non-empty subarrays such that the sum of the elements in each subarray is greater than `threshold`. Return `true` if it... |
def longest_substring_with_two_distinct(s):
if not s:
return 0
max_length = 0
left = 0
char_count = {}
unique = 0
for right, char in enumerate(s):
if char not in char_count or char_count[char] == 0:
unique += 1
char_count[char] = char_count.get(char,... | simplelr_Leetcode | [
{
"content": "Question:\nWrite a function that accepts a string `s` consisting of lowercase alphabetic characters and returns the length of the longest substring of `s` that contains at most two distinct characters. If the input string is empty, return `0`. A substring is defined as a contiguous sequence of cha... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9893,
"level": 1,
"question": "Write a function that accepts a string `s` consisting of lowercase alphabetic characters and returns the length of the longest substring of `s` that contains at most two distinct characters. If the input string is empty, return `0`. A substring is defi... |
from typing import List
def replace_elements(nums: List[int], val: int) -> List[int]:
for i in range(len(nums)):
if nums[i] == val:
nums[i] = 2 * val
return nums | simplelr_Package | [
{
"content": "Question:\nImplement a function called `replace_elements` that takes a list of integers `nums` and an integer `val`, and replaces every occurrence of `val` in the list with double its value. The function should return the updated list. The function should iterate over the list one time only (O(n) ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9894,
"level": 1,
"question": "Implement a function called `replace_elements` that takes a list of integers `nums` and an integer `val`, and replaces every occurrence of `val` in the list with double its value. The function should return the updated list. The function should iterate... |
def sum_of_even_numbers(numbers):
"""
This function takes a list of numbers as input and returns the sum of all even numbers in the list.
"""
total_sum = 0
for number in numbers:
if number % 2 == 0:
total_sum += number
return total_sum | simplelr_Filter | [
{
"content": "Question:\nThis is an example:\n\n```python\ndef sum_of_even_numbers(numbers):\n \"\"\"\n This function takes a list of numbers as input and returns the sum of all even numbers in the list.\n \"\"\"\n sum = 0\n for number in numbers:\n if number % 2 == 0:\n sum += number\n return sum... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9895,
"level": 1,
"question": "This is an example:\n\n```python\ndef sum_of_even_numbers(numbers):\n \"\"\"\n This function takes a list of numbers as input and returns the sum of all even numbers in the list.\n \"\"\"\n sum = 0\n for number in numbers:\n if number % 2 == 0:... |
from typing import List, Tuple
def evaluate_recommendations(recommended: List[str], clicked: List[str]) -> Tuple[int, float]:
# Convert clicked items to a set to remove duplicates
unique_clicked = set(clicked)
# Count each recommended item that is in the unique clicked set
correct = sum(1 for item... | simplelr_Package | [
{
"content": "Question:\n**A company is developing a new recommendation engine to suggest products to users based on their browsing history. To evaluate the performance of their new algorithm, they need to compare the items recommended by the new algorithm against the items actually clicked by users. \n\nYou ne... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9896,
"level": 1,
"question": "**A company is developing a new recommendation engine to suggest products to users based on their browsing history. To evaluate the performance of their new algorithm, they need to compare the items recommended by the new algorithm against the items ac... |
from collections import defaultdict
def count_occurrences(lst):
counts = defaultdict(int)
for s in lst:
counts[s] += 1
return dict(counts) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to read a list of strings and count the occurrences of each string in the list. Return the counts as a dictionary.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9897,
"level": 1,
"question": "Write a python function to read a list of strings and count the occurrences of each string in the list. Return the counts as a dictionary.",
"split": "train"
} |
def consolidate_orders(orders: list[(str, int)]) -> dict[str, int]:
totals = {}
for product, quantity in orders:
if product in totals:
totals[product] += quantity
else:
totals[product] = quantity
return totals | simplelr_Algorithm | [
{
"content": "Question:\n### Consolidated Order Inventory Management\n\nA prominent logistics company needs to manage its order inventory efficiently. You have been tasked with developing a solution that consolidates the orders based on the products ordered. Each order consists of a single product type and a qu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9898,
"level": 1,
"question": "### Consolidated Order Inventory Management\n\nA prominent logistics company needs to manage its order inventory efficiently. You have been tasked with developing a solution that consolidates the orders based on the products ordered. Each order consist... |
def merge_shifts(shifts):
if not shifts:
return []
sorted_shifts = sorted(shifts, key=lambda x: x[0])
merged = [list(sorted_shifts[0])]
for shift in sorted_shifts[1:]:
last = merged[-1]
s, e = shift
if s <= last[1]:
if e > last[1]:
last[1] = e
... | simplelr_Algorithm | [
{
"content": "Question:\nEmployee Schedule Adjustment\n\nYou are tasked with developing an automated system for a company to manage its employees' work schedules. In this system, each employee is assigned a list of work shifts, represented as pairs of integers where the first integer is the start time and the s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 9899,
"level": 1,
"question": "Employee Schedule Adjustment\n\nYou are tasked with developing an automated system for a company to manage its employees' work schedules. In this system, each employee is assigned a list of work shifts, represented as pairs of integers where the first ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.